blob: 616ab05eaec80458efc2404b77ca55d97a596dd7 [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);
Faisal Valid143a0c2017-04-01 21:30:49 +00001053 PushExpressionEvaluationContext(
1054 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001055}
1056
Alexey Bataevaac108a2015-06-23 04:51:00 +00001057void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1058 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001059}
1060
Alexey Bataevaac108a2015-06-23 04:51:00 +00001061void Sema::EndOpenMPClause() {
1062 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001063}
1064
Alexey Bataev758e55e2013-09-06 18:03:48 +00001065void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001066 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1067 // A variable of class type (or array thereof) that appears in a lastprivate
1068 // clause requires an accessible, unambiguous default constructor for the
1069 // class type, unless the list item is also specified in a firstprivate
1070 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001071 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001072 for (auto *C : D->clauses()) {
1073 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1074 SmallVector<Expr *, 8> PrivateCopies;
1075 for (auto *DE : Clause->varlists()) {
1076 if (DE->isValueDependent() || DE->isTypeDependent()) {
1077 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001078 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001079 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001080 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001081 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1082 QualType Type = VD->getType().getNonReferenceType();
1083 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001084 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001085 // Generate helper private variable and initialize it with the
1086 // default value. The address of the original variable is replaced
1087 // by the address of the new private variable in CodeGen. This new
1088 // variable is not added to IdResolver, so the code in the OpenMP
1089 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001090 auto *VDPrivate = buildVarDecl(
1091 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001092 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001093 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001094 if (VDPrivate->isInvalidDecl())
1095 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001096 PrivateCopies.push_back(buildDeclRefExpr(
1097 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001098 } else {
1099 // The variable is also a firstprivate, so initialization sequence
1100 // for private copy is generated already.
1101 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001102 }
1103 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001104 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001105 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001106 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001107 }
1108 }
1109 }
1110
Alexey Bataev758e55e2013-09-06 18:03:48 +00001111 DSAStack->pop();
1112 DiscardCleanupsInEvaluationContext();
1113 PopExpressionEvaluationContext();
1114}
1115
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001116static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1117 Expr *NumIterations, Sema &SemaRef,
1118 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001119
Alexey Bataeva769e072013-03-22 06:34:35 +00001120namespace {
1121
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001122class VarDeclFilterCCC : public CorrectionCandidateCallback {
1123private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001124 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001125
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001126public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001127 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001128 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001129 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001130 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001131 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001132 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1133 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001134 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001135 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001136 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001137};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001138
1139class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1140private:
1141 Sema &SemaRef;
1142
1143public:
1144 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1145 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1146 NamedDecl *ND = Candidate.getCorrectionDecl();
1147 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1148 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1149 SemaRef.getCurScope());
1150 }
1151 return false;
1152 }
1153};
1154
Alexey Bataeved09d242014-05-28 05:53:51 +00001155} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001156
1157ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1158 CXXScopeSpec &ScopeSpec,
1159 const DeclarationNameInfo &Id) {
1160 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1161 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1162
1163 if (Lookup.isAmbiguous())
1164 return ExprError();
1165
1166 VarDecl *VD;
1167 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001168 if (TypoCorrection Corrected = CorrectTypo(
1169 Id, LookupOrdinaryName, CurScope, nullptr,
1170 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001171 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001172 PDiag(Lookup.empty()
1173 ? diag::err_undeclared_var_use_suggest
1174 : diag::err_omp_expected_var_arg_suggest)
1175 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001176 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001177 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001178 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1179 : diag::err_omp_expected_var_arg)
1180 << Id.getName();
1181 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001183 } else {
1184 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001185 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001186 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1187 return ExprError();
1188 }
1189 }
1190 Lookup.suppressDiagnostics();
1191
1192 // OpenMP [2.9.2, Syntax, C/C++]
1193 // Variables must be file-scope, namespace-scope, or static block-scope.
1194 if (!VD->hasGlobalStorage()) {
1195 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001196 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1197 bool IsDecl =
1198 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001199 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001200 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1201 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001202 return ExprError();
1203 }
1204
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001205 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1206 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001207 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1208 // A threadprivate directive for file-scope variables must appear outside
1209 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001210 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1211 !getCurLexicalContext()->isTranslationUnit()) {
1212 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001213 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1214 bool IsDecl =
1215 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1216 Diag(VD->getLocation(),
1217 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1218 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001219 return ExprError();
1220 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001221 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1222 // A threadprivate directive for static class member variables must appear
1223 // in the class definition, in the same scope in which the member
1224 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001225 if (CanonicalVD->isStaticDataMember() &&
1226 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1227 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001228 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1229 bool IsDecl =
1230 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1231 Diag(VD->getLocation(),
1232 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1233 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001234 return ExprError();
1235 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001236 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1237 // A threadprivate directive for namespace-scope variables must appear
1238 // outside any definition or declaration other than the namespace
1239 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001240 if (CanonicalVD->getDeclContext()->isNamespace() &&
1241 (!getCurLexicalContext()->isFileContext() ||
1242 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1243 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001244 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1245 bool IsDecl =
1246 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1247 Diag(VD->getLocation(),
1248 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1249 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001250 return ExprError();
1251 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001252 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1253 // A threadprivate directive for static block-scope variables must appear
1254 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001255 if (CanonicalVD->isStaticLocal() && CurScope &&
1256 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001257 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001258 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1259 bool IsDecl =
1260 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1261 Diag(VD->getLocation(),
1262 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1263 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001264 return ExprError();
1265 }
1266
1267 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1268 // A threadprivate directive must lexically precede all references to any
1269 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001270 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001271 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001272 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001273 return ExprError();
1274 }
1275
1276 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001277 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1278 SourceLocation(), VD,
1279 /*RefersToEnclosingVariableOrCapture=*/false,
1280 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001281}
1282
Alexey Bataeved09d242014-05-28 05:53:51 +00001283Sema::DeclGroupPtrTy
1284Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1285 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001286 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001287 CurContext->addDecl(D);
1288 return DeclGroupPtrTy::make(DeclGroupRef(D));
1289 }
David Blaikie0403cb12016-01-15 23:43:25 +00001290 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001291}
1292
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001293namespace {
1294class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1295 Sema &SemaRef;
1296
1297public:
1298 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001299 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001300 if (VD->hasLocalStorage()) {
1301 SemaRef.Diag(E->getLocStart(),
1302 diag::err_omp_local_var_in_threadprivate_init)
1303 << E->getSourceRange();
1304 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1305 << VD << VD->getSourceRange();
1306 return true;
1307 }
1308 }
1309 return false;
1310 }
1311 bool VisitStmt(const Stmt *S) {
1312 for (auto Child : S->children()) {
1313 if (Child && Visit(Child))
1314 return true;
1315 }
1316 return false;
1317 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001318 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001319};
1320} // namespace
1321
Alexey Bataeved09d242014-05-28 05:53:51 +00001322OMPThreadPrivateDecl *
1323Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001324 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001325 for (auto &RefExpr : VarList) {
1326 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001327 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1328 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001329
Alexey Bataev376b4a42016-02-09 09:41:09 +00001330 // Mark variable as used.
1331 VD->setReferenced();
1332 VD->markUsed(Context);
1333
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001334 QualType QType = VD->getType();
1335 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1336 // It will be analyzed later.
1337 Vars.push_back(DE);
1338 continue;
1339 }
1340
Alexey Bataeva769e072013-03-22 06:34:35 +00001341 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1342 // A threadprivate variable must not have an incomplete type.
1343 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001344 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001345 continue;
1346 }
1347
1348 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1349 // A threadprivate variable must not have a reference type.
1350 if (VD->getType()->isReferenceType()) {
1351 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001352 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1353 bool IsDecl =
1354 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1355 Diag(VD->getLocation(),
1356 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1357 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001358 continue;
1359 }
1360
Samuel Antaof8b50122015-07-13 22:54:53 +00001361 // Check if this is a TLS variable. If TLS is not being supported, produce
1362 // the corresponding diagnostic.
1363 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1364 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1365 getLangOpts().OpenMPUseTLS &&
1366 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001367 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1368 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001369 Diag(ILoc, diag::err_omp_var_thread_local)
1370 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001371 bool IsDecl =
1372 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1373 Diag(VD->getLocation(),
1374 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1375 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001376 continue;
1377 }
1378
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001379 // Check if initial value of threadprivate variable reference variable with
1380 // local storage (it is not supported by runtime).
1381 if (auto Init = VD->getAnyInitializer()) {
1382 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001383 if (Checker.Visit(Init))
1384 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001385 }
1386
Alexey Bataeved09d242014-05-28 05:53:51 +00001387 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001388 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001389 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1390 Context, SourceRange(Loc, Loc)));
1391 if (auto *ML = Context.getASTMutationListener())
1392 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001393 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001394 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001395 if (!Vars.empty()) {
1396 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1397 Vars);
1398 D->setAccess(AS_public);
1399 }
1400 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001401}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001402
Alexey Bataev7ff55242014-06-19 09:13:45 +00001403static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001404 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001405 bool IsLoopIterVar = false) {
1406 if (DVar.RefExpr) {
1407 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1408 << getOpenMPClauseName(DVar.CKind);
1409 return;
1410 }
1411 enum {
1412 PDSA_StaticMemberShared,
1413 PDSA_StaticLocalVarShared,
1414 PDSA_LoopIterVarPrivate,
1415 PDSA_LoopIterVarLinear,
1416 PDSA_LoopIterVarLastprivate,
1417 PDSA_ConstVarShared,
1418 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001419 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001420 PDSA_LocalVarPrivate,
1421 PDSA_Implicit
1422 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001423 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001424 auto ReportLoc = D->getLocation();
1425 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001426 if (IsLoopIterVar) {
1427 if (DVar.CKind == OMPC_private)
1428 Reason = PDSA_LoopIterVarPrivate;
1429 else if (DVar.CKind == OMPC_lastprivate)
1430 Reason = PDSA_LoopIterVarLastprivate;
1431 else
1432 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001433 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1434 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001435 Reason = PDSA_TaskVarFirstprivate;
1436 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001437 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001438 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001439 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001440 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001441 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001442 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001443 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001444 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001445 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001446 ReportHint = true;
1447 Reason = PDSA_LocalVarPrivate;
1448 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001449 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001450 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001451 << Reason << ReportHint
1452 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1453 } else if (DVar.ImplicitDSALoc.isValid()) {
1454 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1455 << getOpenMPClauseName(DVar.CKind);
1456 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001457}
1458
Alexey Bataev758e55e2013-09-06 18:03:48 +00001459namespace {
1460class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1461 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001462 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001463 bool ErrorFound;
1464 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001465 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001466 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001467
Alexey Bataev758e55e2013-09-06 18:03:48 +00001468public:
1469 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001470 if (E->isTypeDependent() || E->isValueDependent() ||
1471 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1472 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001473 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001474 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001475 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1476 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001477
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001478 auto DVar = Stack->getTopDSA(VD, false);
1479 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001480 if (DVar.RefExpr)
1481 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001482
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001483 auto ELoc = E->getExprLoc();
1484 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001485 // The default(none) clause requires that each variable that is referenced
1486 // in the construct, and does not have a predetermined data-sharing
1487 // attribute, must have its data-sharing attribute explicitly determined
1488 // by being listed in a data-sharing attribute clause.
1489 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001490 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001491 VarsWithInheritedDSA.count(VD) == 0) {
1492 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001493 return;
1494 }
1495
1496 // OpenMP [2.9.3.6, Restrictions, p.2]
1497 // A list item that appears in a reduction clause of the innermost
1498 // enclosing worksharing or parallel construct may not be accessed in an
1499 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001500 DVar = Stack->hasInnermostDSA(
1501 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1502 [](OpenMPDirectiveKind K) -> bool {
1503 return isOpenMPParallelDirective(K) ||
1504 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1505 },
1506 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001507 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001508 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001509 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1510 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001511 return;
1512 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001513
1514 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001515 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001516 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1517 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001518 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001519 }
1520 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001521 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001522 if (E->isTypeDependent() || E->isValueDependent() ||
1523 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1524 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001525 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1526 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1527 auto DVar = Stack->getTopDSA(FD, false);
1528 // Check if the variable has explicit DSA set and stop analysis if it
1529 // so.
1530 if (DVar.RefExpr)
1531 return;
1532
1533 auto ELoc = E->getExprLoc();
1534 auto DKind = Stack->getCurrentDirective();
1535 // OpenMP [2.9.3.6, Restrictions, p.2]
1536 // A list item that appears in a reduction clause of the innermost
1537 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001538 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001539 DVar = Stack->hasInnermostDSA(
1540 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1541 [](OpenMPDirectiveKind K) -> bool {
1542 return isOpenMPParallelDirective(K) ||
1543 isOpenMPWorksharingDirective(K) ||
1544 isOpenMPTeamsDirective(K);
1545 },
1546 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001547 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001548 ErrorFound = true;
1549 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1550 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1551 return;
1552 }
1553
1554 // Define implicit data-sharing attributes for task.
1555 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001556 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1557 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001558 ImplicitFirstprivate.push_back(E);
1559 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001560 } else
1561 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001562 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001563 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001564 for (auto *C : S->clauses()) {
1565 // Skip analysis of arguments of implicitly defined firstprivate clause
1566 // for task directives.
1567 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1568 for (auto *CC : C->children()) {
1569 if (CC)
1570 Visit(CC);
1571 }
1572 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001573 }
1574 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001575 for (auto *C : S->children()) {
1576 if (C && !isa<OMPExecutableDirective>(C))
1577 Visit(C);
1578 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001579 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001580
1581 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001582 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001583 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001584 return VarsWithInheritedDSA;
1585 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001586
Alexey Bataev7ff55242014-06-19 09:13:45 +00001587 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1588 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001589};
Alexey Bataeved09d242014-05-28 05:53:51 +00001590} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001591
Alexey Bataevbae9a792014-06-27 10:37:06 +00001592void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001593 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001594 case OMPD_parallel:
1595 case OMPD_parallel_for:
1596 case OMPD_parallel_for_simd:
1597 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001598 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001611 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001612 case OMPD_target_parallel: {
1613 Sema::CapturedParamNameType ParamsTarget[] = {
1614 std::make_pair(StringRef(), QualType()) // __context with shared vars
1615 };
1616 // Start a captured region for 'target' with no implicit parameters.
1617 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1618 ParamsTarget);
1619 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1620 QualType KmpInt32PtrTy =
1621 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001622 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001623 std::make_pair(".global_tid.", KmpInt32PtrTy),
1624 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1625 std::make_pair(StringRef(), QualType()) // __context with shared vars
1626 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001627 // Start a captured region for 'teams' or 'parallel'. Both regions have
1628 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001629 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001630 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001631 break;
1632 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001633 case OMPD_simd:
1634 case OMPD_for:
1635 case OMPD_for_simd:
1636 case OMPD_sections:
1637 case OMPD_section:
1638 case OMPD_single:
1639 case OMPD_master:
1640 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001641 case OMPD_taskgroup:
1642 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001643 case OMPD_ordered:
1644 case OMPD_atomic:
1645 case OMPD_target_data:
1646 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001647 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001648 case OMPD_target_parallel_for_simd:
1649 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001650 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001651 std::make_pair(StringRef(), QualType()) // __context with shared vars
1652 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001653 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1654 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001655 break;
1656 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001657 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001658 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001659 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1660 FunctionProtoType::ExtProtoInfo EPI;
1661 EPI.Variadic = true;
1662 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001663 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001664 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001665 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1666 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1667 std::make_pair(".copy_fn.",
1668 Context.getPointerType(CopyFnType).withConst()),
1669 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001670 std::make_pair(StringRef(), QualType()) // __context with shared vars
1671 };
1672 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1673 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001674 // Mark this captured region as inlined, because we don't use outlined
1675 // function directly.
1676 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1677 AlwaysInlineAttr::CreateImplicit(
1678 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001679 break;
1680 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001681 case OMPD_taskloop:
1682 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001683 QualType KmpInt32Ty =
1684 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1685 QualType KmpUInt64Ty =
1686 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1687 QualType KmpInt64Ty =
1688 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1689 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1690 FunctionProtoType::ExtProtoInfo EPI;
1691 EPI.Variadic = true;
1692 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001693 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001694 std::make_pair(".global_tid.", KmpInt32Ty),
1695 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1696 std::make_pair(".privates.",
1697 Context.VoidPtrTy.withConst().withRestrict()),
1698 std::make_pair(
1699 ".copy_fn.",
1700 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1701 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1702 std::make_pair(".lb.", KmpUInt64Ty),
1703 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1704 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001705 std::make_pair(StringRef(), QualType()) // __context with shared vars
1706 };
1707 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1708 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001709 // Mark this captured region as inlined, because we don't use outlined
1710 // function directly.
1711 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1712 AlwaysInlineAttr::CreateImplicit(
1713 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001714 break;
1715 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001716 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001717 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001718 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001719 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001720 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001721 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001722 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001723 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001724 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001725 case OMPD_target_teams_distribute_parallel_for_simd:
1726 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001727 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1728 QualType KmpInt32PtrTy =
1729 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1730 Sema::CapturedParamNameType Params[] = {
1731 std::make_pair(".global_tid.", KmpInt32PtrTy),
1732 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1733 std::make_pair(".previous.lb.", Context.getSizeType()),
1734 std::make_pair(".previous.ub.", Context.getSizeType()),
1735 std::make_pair(StringRef(), QualType()) // __context with shared vars
1736 };
1737 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1738 Params);
1739 break;
1740 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001741 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001742 case OMPD_taskyield:
1743 case OMPD_barrier:
1744 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001745 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001746 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001747 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001748 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001749 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001750 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001751 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001752 case OMPD_declare_target:
1753 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001754 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001755 llvm_unreachable("OpenMP Directive is not allowed");
1756 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001757 llvm_unreachable("Unknown OpenMP directive");
1758 }
1759}
1760
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001761int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1762 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1763 getOpenMPCaptureRegions(CaptureRegions, DKind);
1764 return CaptureRegions.size();
1765}
1766
Alexey Bataev3392d762016-02-16 11:18:12 +00001767static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001768 Expr *CaptureExpr, bool WithInit,
1769 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001770 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001771 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001772 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001773 QualType Ty = Init->getType();
1774 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1775 if (S.getLangOpts().CPlusPlus)
1776 Ty = C.getLValueReferenceType(Ty);
1777 else {
1778 Ty = C.getPointerType(Ty);
1779 ExprResult Res =
1780 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1781 if (!Res.isUsable())
1782 return nullptr;
1783 Init = Res.get();
1784 }
Alexey Bataev61205072016-03-02 04:57:40 +00001785 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001786 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001787 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1788 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001789 if (!WithInit)
1790 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001791 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001792 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001793 return CED;
1794}
1795
Alexey Bataev61205072016-03-02 04:57:40 +00001796static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1797 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001798 OMPCapturedExprDecl *CD;
1799 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1800 CD = cast<OMPCapturedExprDecl>(VD);
1801 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001802 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1803 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001804 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001805 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001806}
1807
Alexey Bataev5a3af132016-03-29 08:58:54 +00001808static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1809 if (!Ref) {
1810 auto *CD =
1811 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1812 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1813 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1814 CaptureExpr->getExprLoc());
1815 }
1816 ExprResult Res = Ref;
1817 if (!S.getLangOpts().CPlusPlus &&
1818 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1819 Ref->getType()->isPointerType())
1820 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1821 if (!Res.isUsable())
1822 return ExprError();
1823 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001824}
1825
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001826namespace {
1827// OpenMP directives parsed in this section are represented as a
1828// CapturedStatement with an associated statement. If a syntax error
1829// is detected during the parsing of the associated statement, the
1830// compiler must abort processing and close the CapturedStatement.
1831//
1832// Combined directives such as 'target parallel' have more than one
1833// nested CapturedStatements. This RAII ensures that we unwind out
1834// of all the nested CapturedStatements when an error is found.
1835class CaptureRegionUnwinderRAII {
1836private:
1837 Sema &S;
1838 bool &ErrorFound;
1839 OpenMPDirectiveKind DKind;
1840
1841public:
1842 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1843 OpenMPDirectiveKind DKind)
1844 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1845 ~CaptureRegionUnwinderRAII() {
1846 if (ErrorFound) {
1847 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1848 while (--ThisCaptureLevel >= 0)
1849 S.ActOnCapturedRegionError();
1850 }
1851 }
1852};
1853} // namespace
1854
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001855StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1856 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001857 bool ErrorFound = false;
1858 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1859 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001860 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001861 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001862 return StmtError();
1863 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001864
1865 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001866 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001867 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001868 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001869 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001870 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001871 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001872 Clause->getClauseKind() == OMPC_copyprivate ||
1873 (getLangOpts().OpenMPUseTLS &&
1874 getASTContext().getTargetInfo().isTLSSupported() &&
1875 Clause->getClauseKind() == OMPC_copyin)) {
1876 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001877 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001878 for (auto *VarRef : Clause->children()) {
1879 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001880 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001881 }
1882 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001883 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001884 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001885 if (auto *C = OMPClauseWithPreInit::get(Clause))
1886 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001887 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1888 if (auto *E = C->getPostUpdateExpr())
1889 MarkDeclarationsReferencedInExpr(E);
1890 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001891 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001892 if (Clause->getClauseKind() == OMPC_schedule)
1893 SC = cast<OMPScheduleClause>(Clause);
1894 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001895 OC = cast<OMPOrderedClause>(Clause);
1896 else if (Clause->getClauseKind() == OMPC_linear)
1897 LCs.push_back(cast<OMPLinearClause>(Clause));
1898 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001899 // OpenMP, 2.7.1 Loop Construct, Restrictions
1900 // The nonmonotonic modifier cannot be specified if an ordered clause is
1901 // specified.
1902 if (SC &&
1903 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1904 SC->getSecondScheduleModifier() ==
1905 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1906 OC) {
1907 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1908 ? SC->getFirstScheduleModifierLoc()
1909 : SC->getSecondScheduleModifierLoc(),
1910 diag::err_omp_schedule_nonmonotonic_ordered)
1911 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1912 ErrorFound = true;
1913 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001914 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1915 for (auto *C : LCs) {
1916 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1917 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1918 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001919 ErrorFound = true;
1920 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001921 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1922 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1923 OC->getNumForLoops()) {
1924 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1925 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1926 ErrorFound = true;
1927 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001928 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001929 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001930 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001931 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001932 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1933 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1934 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1935 // Mark all variables in private list clauses as used in inner region.
1936 // Required for proper codegen of combined directives.
1937 // TODO: add processing for other clauses.
1938 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1939 for (auto *C : PICs) {
1940 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1941 // Find the particular capture region for the clause if the
1942 // directive is a combined one with multiple capture regions.
1943 // If the directive is not a combined one, the capture region
1944 // associated with the clause is OMPD_unknown and is generated
1945 // only once.
1946 if (CaptureRegion == ThisCaptureRegion ||
1947 CaptureRegion == OMPD_unknown) {
1948 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1949 for (auto *D : DS->decls())
1950 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1951 }
1952 }
1953 }
1954 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001955 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001956 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001957 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001958}
1959
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00001960static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
1961 OpenMPDirectiveKind CancelRegion,
1962 SourceLocation StartLoc) {
1963 // CancelRegion is only needed for cancel and cancellation_point.
1964 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
1965 return false;
1966
1967 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
1968 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
1969 return false;
1970
1971 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
1972 << getOpenMPDirectiveName(CancelRegion);
1973 return true;
1974}
1975
1976static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001977 OpenMPDirectiveKind CurrentRegion,
1978 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001979 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001980 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001981 if (Stack->getCurScope()) {
1982 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001983 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001984 bool NestingProhibited = false;
1985 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001986 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001987 enum {
1988 NoRecommend,
1989 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001990 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001991 ShouldBeInTargetRegion,
1992 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001993 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001994 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001995 // OpenMP [2.16, Nesting of Regions]
1996 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001997 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001998 // An ordered construct with the simd clause is the only OpenMP
1999 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002000 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002001 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2002 // message.
2003 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2004 ? diag::err_omp_prohibited_region_simd
2005 : diag::warn_omp_nesting_simd);
2006 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002007 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002008 if (ParentRegion == OMPD_atomic) {
2009 // OpenMP [2.16, Nesting of Regions]
2010 // OpenMP constructs may not be nested inside an atomic region.
2011 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2012 return true;
2013 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002014 if (CurrentRegion == OMPD_section) {
2015 // OpenMP [2.7.2, sections Construct, Restrictions]
2016 // Orphaned section directives are prohibited. That is, the section
2017 // directives must appear within the sections construct and must not be
2018 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002019 if (ParentRegion != OMPD_sections &&
2020 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002021 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2022 << (ParentRegion != OMPD_unknown)
2023 << getOpenMPDirectiveName(ParentRegion);
2024 return true;
2025 }
2026 return false;
2027 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002028 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002029 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002030 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002031 if (ParentRegion == OMPD_unknown &&
2032 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002033 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002034 if (CurrentRegion == OMPD_cancellation_point ||
2035 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002036 // OpenMP [2.16, Nesting of Regions]
2037 // A cancellation point construct for which construct-type-clause is
2038 // taskgroup must be nested inside a task construct. A cancellation
2039 // point construct for which construct-type-clause is not taskgroup must
2040 // be closely nested inside an OpenMP construct that matches the type
2041 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002042 // A cancel construct for which construct-type-clause is taskgroup must be
2043 // nested inside a task construct. A cancel construct for which
2044 // construct-type-clause is not taskgroup must be closely nested inside an
2045 // OpenMP construct that matches the type specified in
2046 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002047 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002048 !((CancelRegion == OMPD_parallel &&
2049 (ParentRegion == OMPD_parallel ||
2050 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002051 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002052 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2053 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002054 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2055 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002056 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2057 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002058 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002059 // OpenMP [2.16, Nesting of Regions]
2060 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002061 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002062 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002063 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002064 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2065 // OpenMP [2.16, Nesting of Regions]
2066 // A critical region may not be nested (closely or otherwise) inside a
2067 // critical region with the same name. Note that this restriction is not
2068 // sufficient to prevent deadlock.
2069 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002070 bool DeadLock = Stack->hasDirective(
2071 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2072 const DeclarationNameInfo &DNI,
2073 SourceLocation Loc) -> bool {
2074 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2075 PreviousCriticalLoc = Loc;
2076 return true;
2077 } else
2078 return false;
2079 },
2080 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002081 if (DeadLock) {
2082 SemaRef.Diag(StartLoc,
2083 diag::err_omp_prohibited_region_critical_same_name)
2084 << CurrentName.getName();
2085 if (PreviousCriticalLoc.isValid())
2086 SemaRef.Diag(PreviousCriticalLoc,
2087 diag::note_omp_previous_critical_region);
2088 return true;
2089 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002090 } else if (CurrentRegion == OMPD_barrier) {
2091 // OpenMP [2.16, Nesting of Regions]
2092 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002093 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002094 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2095 isOpenMPTaskingDirective(ParentRegion) ||
2096 ParentRegion == OMPD_master ||
2097 ParentRegion == OMPD_critical ||
2098 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002099 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002100 !isOpenMPParallelDirective(CurrentRegion) &&
2101 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002102 // OpenMP [2.16, Nesting of Regions]
2103 // A worksharing region may not be closely nested inside a worksharing,
2104 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002105 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2106 isOpenMPTaskingDirective(ParentRegion) ||
2107 ParentRegion == OMPD_master ||
2108 ParentRegion == OMPD_critical ||
2109 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002110 Recommend = ShouldBeInParallelRegion;
2111 } else if (CurrentRegion == OMPD_ordered) {
2112 // OpenMP [2.16, Nesting of Regions]
2113 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002114 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002115 // An ordered region must be closely nested inside a loop region (or
2116 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002117 // OpenMP [2.8.1,simd Construct, Restrictions]
2118 // An ordered construct with the simd clause is the only OpenMP construct
2119 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002120 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002121 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002122 !(isOpenMPSimdDirective(ParentRegion) ||
2123 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002124 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002125 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002126 // OpenMP [2.16, Nesting of Regions]
2127 // If specified, a teams construct must be contained within a target
2128 // construct.
2129 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002130 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002131 Recommend = ShouldBeInTargetRegion;
2132 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2133 }
Kelvin Libf594a52016-12-17 05:48:59 +00002134 if (!NestingProhibited &&
2135 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2136 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2137 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002138 // OpenMP [2.16, Nesting of Regions]
2139 // distribute, parallel, parallel sections, parallel workshare, and the
2140 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2141 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002142 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2143 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002144 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002145 }
David Majnemer9d168222016-08-05 17:44:54 +00002146 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002147 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002148 // OpenMP 4.5 [2.17 Nesting of Regions]
2149 // The region associated with the distribute construct must be strictly
2150 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002151 NestingProhibited =
2152 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002153 Recommend = ShouldBeInTeamsRegion;
2154 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002155 if (!NestingProhibited &&
2156 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2157 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2158 // OpenMP 4.5 [2.17 Nesting of Regions]
2159 // If a target, target update, target data, target enter data, or
2160 // target exit data construct is encountered during execution of a
2161 // target region, the behavior is unspecified.
2162 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002163 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2164 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002165 if (isOpenMPTargetExecutionDirective(K)) {
2166 OffendingRegion = K;
2167 return true;
2168 } else
2169 return false;
2170 },
2171 false /* don't skip top directive */);
2172 CloseNesting = false;
2173 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002174 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002175 if (OrphanSeen) {
2176 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2177 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2178 } else {
2179 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2180 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2181 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2182 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002183 return true;
2184 }
2185 }
2186 return false;
2187}
2188
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002189static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2190 ArrayRef<OMPClause *> Clauses,
2191 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2192 bool ErrorFound = false;
2193 unsigned NamedModifiersNumber = 0;
2194 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2195 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002196 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002197 for (const auto *C : Clauses) {
2198 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2199 // At most one if clause without a directive-name-modifier can appear on
2200 // the directive.
2201 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2202 if (FoundNameModifiers[CurNM]) {
2203 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2204 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2205 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2206 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002207 } else if (CurNM != OMPD_unknown) {
2208 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002209 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002210 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002211 FoundNameModifiers[CurNM] = IC;
2212 if (CurNM == OMPD_unknown)
2213 continue;
2214 // Check if the specified name modifier is allowed for the current
2215 // directive.
2216 // At most one if clause with the particular directive-name-modifier can
2217 // appear on the directive.
2218 bool MatchFound = false;
2219 for (auto NM : AllowedNameModifiers) {
2220 if (CurNM == NM) {
2221 MatchFound = true;
2222 break;
2223 }
2224 }
2225 if (!MatchFound) {
2226 S.Diag(IC->getNameModifierLoc(),
2227 diag::err_omp_wrong_if_directive_name_modifier)
2228 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2229 ErrorFound = true;
2230 }
2231 }
2232 }
2233 // If any if clause on the directive includes a directive-name-modifier then
2234 // all if clauses on the directive must include a directive-name-modifier.
2235 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2236 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2237 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2238 diag::err_omp_no_more_if_clause);
2239 } else {
2240 std::string Values;
2241 std::string Sep(", ");
2242 unsigned AllowedCnt = 0;
2243 unsigned TotalAllowedNum =
2244 AllowedNameModifiers.size() - NamedModifiersNumber;
2245 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2246 ++Cnt) {
2247 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2248 if (!FoundNameModifiers[NM]) {
2249 Values += "'";
2250 Values += getOpenMPDirectiveName(NM);
2251 Values += "'";
2252 if (AllowedCnt + 2 == TotalAllowedNum)
2253 Values += " or ";
2254 else if (AllowedCnt + 1 != TotalAllowedNum)
2255 Values += Sep;
2256 ++AllowedCnt;
2257 }
2258 }
2259 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2260 diag::err_omp_unnamed_if_clause)
2261 << (TotalAllowedNum > 1) << Values;
2262 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002263 for (auto Loc : NameModifierLoc) {
2264 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2265 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002266 ErrorFound = true;
2267 }
2268 return ErrorFound;
2269}
2270
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002271StmtResult Sema::ActOnOpenMPExecutableDirective(
2272 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2273 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2274 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002275 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002276 // First check CancelRegion which is then used in checkNestingOfRegions.
2277 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2278 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002279 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002280 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002281
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002282 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002283 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002284 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002285 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002286 if (AStmt) {
2287 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2288
2289 // Check default data sharing attributes for referenced variables.
2290 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002291 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2292 Stmt *S = AStmt;
2293 while (--ThisCaptureLevel >= 0)
2294 S = cast<CapturedStmt>(S)->getCapturedStmt();
2295 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002296 if (DSAChecker.isErrorFound())
2297 return StmtError();
2298 // Generate list of implicitly defined firstprivate variables.
2299 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002300
2301 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2302 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2303 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2304 SourceLocation(), SourceLocation())) {
2305 ClausesWithImplicit.push_back(Implicit);
2306 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2307 DSAChecker.getImplicitFirstprivate().size();
2308 } else
2309 ErrorFound = true;
2310 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002311 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002312
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002313 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002314 switch (Kind) {
2315 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002316 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2317 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002318 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002319 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002320 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002321 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2322 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002323 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002324 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002325 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2326 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002327 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002328 case OMPD_for_simd:
2329 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2330 EndLoc, VarsWithInheritedDSA);
2331 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002332 case OMPD_sections:
2333 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2334 EndLoc);
2335 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002336 case OMPD_section:
2337 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002338 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002339 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2340 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002341 case OMPD_single:
2342 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2343 EndLoc);
2344 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002345 case OMPD_master:
2346 assert(ClausesWithImplicit.empty() &&
2347 "No clauses are allowed for 'omp master' directive");
2348 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2349 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002350 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002351 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2352 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002353 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002354 case OMPD_parallel_for:
2355 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2356 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002357 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002358 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002359 case OMPD_parallel_for_simd:
2360 Res = ActOnOpenMPParallelForSimdDirective(
2361 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002362 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002363 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002364 case OMPD_parallel_sections:
2365 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2366 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002367 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002368 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002369 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002370 Res =
2371 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002372 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002373 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002374 case OMPD_taskyield:
2375 assert(ClausesWithImplicit.empty() &&
2376 "No clauses are allowed for 'omp taskyield' directive");
2377 assert(AStmt == nullptr &&
2378 "No associated statement allowed for 'omp taskyield' directive");
2379 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2380 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002381 case OMPD_barrier:
2382 assert(ClausesWithImplicit.empty() &&
2383 "No clauses are allowed for 'omp barrier' directive");
2384 assert(AStmt == nullptr &&
2385 "No associated statement allowed for 'omp barrier' directive");
2386 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2387 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002388 case OMPD_taskwait:
2389 assert(ClausesWithImplicit.empty() &&
2390 "No clauses are allowed for 'omp taskwait' directive");
2391 assert(AStmt == nullptr &&
2392 "No associated statement allowed for 'omp taskwait' directive");
2393 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2394 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002395 case OMPD_taskgroup:
2396 assert(ClausesWithImplicit.empty() &&
2397 "No clauses are allowed for 'omp taskgroup' directive");
2398 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2399 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002400 case OMPD_flush:
2401 assert(AStmt == nullptr &&
2402 "No associated statement allowed for 'omp flush' directive");
2403 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2404 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002405 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002406 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2407 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002408 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002409 case OMPD_atomic:
2410 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2411 EndLoc);
2412 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002413 case OMPD_teams:
2414 Res =
2415 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2416 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002417 case OMPD_target:
2418 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2419 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002420 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002421 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002422 case OMPD_target_parallel:
2423 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2424 StartLoc, EndLoc);
2425 AllowedNameModifiers.push_back(OMPD_target);
2426 AllowedNameModifiers.push_back(OMPD_parallel);
2427 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002428 case OMPD_target_parallel_for:
2429 Res = ActOnOpenMPTargetParallelForDirective(
2430 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2431 AllowedNameModifiers.push_back(OMPD_target);
2432 AllowedNameModifiers.push_back(OMPD_parallel);
2433 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002434 case OMPD_cancellation_point:
2435 assert(ClausesWithImplicit.empty() &&
2436 "No clauses are allowed for 'omp cancellation point' directive");
2437 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2438 "cancellation point' directive");
2439 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2440 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002441 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002442 assert(AStmt == nullptr &&
2443 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002444 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2445 CancelRegion);
2446 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002447 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002448 case OMPD_target_data:
2449 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2450 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002451 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002452 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002453 case OMPD_target_enter_data:
2454 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2455 EndLoc);
2456 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2457 break;
Samuel Antao72590762016-01-19 20:04:50 +00002458 case OMPD_target_exit_data:
2459 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2460 EndLoc);
2461 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2462 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002463 case OMPD_taskloop:
2464 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2465 EndLoc, VarsWithInheritedDSA);
2466 AllowedNameModifiers.push_back(OMPD_taskloop);
2467 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002468 case OMPD_taskloop_simd:
2469 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2470 EndLoc, VarsWithInheritedDSA);
2471 AllowedNameModifiers.push_back(OMPD_taskloop);
2472 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002473 case OMPD_distribute:
2474 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2475 EndLoc, VarsWithInheritedDSA);
2476 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002477 case OMPD_target_update:
2478 assert(!AStmt && "Statement is not allowed for target update");
2479 Res =
2480 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2481 AllowedNameModifiers.push_back(OMPD_target_update);
2482 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002483 case OMPD_distribute_parallel_for:
2484 Res = ActOnOpenMPDistributeParallelForDirective(
2485 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2486 AllowedNameModifiers.push_back(OMPD_parallel);
2487 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002488 case OMPD_distribute_parallel_for_simd:
2489 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2490 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2491 AllowedNameModifiers.push_back(OMPD_parallel);
2492 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002493 case OMPD_distribute_simd:
2494 Res = ActOnOpenMPDistributeSimdDirective(
2495 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2496 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002497 case OMPD_target_parallel_for_simd:
2498 Res = ActOnOpenMPTargetParallelForSimdDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_target);
2501 AllowedNameModifiers.push_back(OMPD_parallel);
2502 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002503 case OMPD_target_simd:
2504 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2505 EndLoc, VarsWithInheritedDSA);
2506 AllowedNameModifiers.push_back(OMPD_target);
2507 break;
Kelvin Li02532872016-08-05 14:37:37 +00002508 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002509 Res = ActOnOpenMPTeamsDistributeDirective(
2510 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002511 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002512 case OMPD_teams_distribute_simd:
2513 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2515 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002516 case OMPD_teams_distribute_parallel_for_simd:
2517 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2518 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2519 AllowedNameModifiers.push_back(OMPD_parallel);
2520 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002521 case OMPD_teams_distribute_parallel_for:
2522 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2523 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2524 AllowedNameModifiers.push_back(OMPD_parallel);
2525 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002526 case OMPD_target_teams:
2527 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2528 EndLoc);
2529 AllowedNameModifiers.push_back(OMPD_target);
2530 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002531 case OMPD_target_teams_distribute:
2532 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2533 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2534 AllowedNameModifiers.push_back(OMPD_target);
2535 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002536 case OMPD_target_teams_distribute_parallel_for:
2537 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2538 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2539 AllowedNameModifiers.push_back(OMPD_target);
2540 AllowedNameModifiers.push_back(OMPD_parallel);
2541 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002542 case OMPD_target_teams_distribute_parallel_for_simd:
2543 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2544 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2545 AllowedNameModifiers.push_back(OMPD_target);
2546 AllowedNameModifiers.push_back(OMPD_parallel);
2547 break;
Kelvin Lida681182017-01-10 18:08:18 +00002548 case OMPD_target_teams_distribute_simd:
2549 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2550 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2551 AllowedNameModifiers.push_back(OMPD_target);
2552 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002553 case OMPD_declare_target:
2554 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002555 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002556 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002557 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002558 llvm_unreachable("OpenMP Directive is not allowed");
2559 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002560 llvm_unreachable("Unknown OpenMP directive");
2561 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002562
Alexey Bataev4acb8592014-07-07 13:01:15 +00002563 for (auto P : VarsWithInheritedDSA) {
2564 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2565 << P.first << P.second->getSourceRange();
2566 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002567 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2568
2569 if (!AllowedNameModifiers.empty())
2570 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2571 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002572
Alexey Bataeved09d242014-05-28 05:53:51 +00002573 if (ErrorFound)
2574 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002575 return Res;
2576}
2577
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002578Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2579 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002580 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002581 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2582 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002583 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002584 assert(Linears.size() == LinModifiers.size());
2585 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002586 if (!DG || DG.get().isNull())
2587 return DeclGroupPtrTy();
2588
2589 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002590 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002591 return DG;
2592 }
2593 auto *ADecl = DG.get().getSingleDecl();
2594 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2595 ADecl = FTD->getTemplatedDecl();
2596
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002597 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2598 if (!FD) {
2599 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002600 return DeclGroupPtrTy();
2601 }
2602
Alexey Bataev2af33e32016-04-07 12:45:37 +00002603 // OpenMP [2.8.2, declare simd construct, Description]
2604 // The parameter of the simdlen clause must be a constant positive integer
2605 // expression.
2606 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002607 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002608 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002609 // OpenMP [2.8.2, declare simd construct, Description]
2610 // The special this pointer can be used as if was one of the arguments to the
2611 // function in any of the linear, aligned, or uniform clauses.
2612 // The uniform clause declares one or more arguments to have an invariant
2613 // value for all concurrent invocations of the function in the execution of a
2614 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002615 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2616 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002617 for (auto *E : Uniforms) {
2618 E = E->IgnoreParenImpCasts();
2619 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2620 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2621 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2622 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002623 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2624 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002625 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002626 }
2627 if (isa<CXXThisExpr>(E)) {
2628 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002629 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002630 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002631 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2632 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002633 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002634 // OpenMP [2.8.2, declare simd construct, Description]
2635 // The aligned clause declares that the object to which each list item points
2636 // is aligned to the number of bytes expressed in the optional parameter of
2637 // the aligned clause.
2638 // The special this pointer can be used as if was one of the arguments to the
2639 // function in any of the linear, aligned, or uniform clauses.
2640 // The type of list items appearing in the aligned clause must be array,
2641 // pointer, reference to array, or reference to pointer.
2642 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2643 Expr *AlignedThis = nullptr;
2644 for (auto *E : Aligneds) {
2645 E = E->IgnoreParenImpCasts();
2646 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2647 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2648 auto *CanonPVD = PVD->getCanonicalDecl();
2649 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2650 FD->getParamDecl(PVD->getFunctionScopeIndex())
2651 ->getCanonicalDecl() == CanonPVD) {
2652 // OpenMP [2.8.1, simd construct, Restrictions]
2653 // A list-item cannot appear in more than one aligned clause.
2654 if (AlignedArgs.count(CanonPVD) > 0) {
2655 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2656 << 1 << E->getSourceRange();
2657 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2658 diag::note_omp_explicit_dsa)
2659 << getOpenMPClauseName(OMPC_aligned);
2660 continue;
2661 }
2662 AlignedArgs[CanonPVD] = E;
2663 QualType QTy = PVD->getType()
2664 .getNonReferenceType()
2665 .getUnqualifiedType()
2666 .getCanonicalType();
2667 const Type *Ty = QTy.getTypePtrOrNull();
2668 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2669 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2670 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2671 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2672 }
2673 continue;
2674 }
2675 }
2676 if (isa<CXXThisExpr>(E)) {
2677 if (AlignedThis) {
2678 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2679 << 2 << E->getSourceRange();
2680 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2681 << getOpenMPClauseName(OMPC_aligned);
2682 }
2683 AlignedThis = E;
2684 continue;
2685 }
2686 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2687 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2688 }
2689 // The optional parameter of the aligned clause, alignment, must be a constant
2690 // positive integer expression. If no optional parameter is specified,
2691 // implementation-defined default alignments for SIMD instructions on the
2692 // target platforms are assumed.
2693 SmallVector<Expr *, 4> NewAligns;
2694 for (auto *E : Alignments) {
2695 ExprResult Align;
2696 if (E)
2697 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2698 NewAligns.push_back(Align.get());
2699 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002700 // OpenMP [2.8.2, declare simd construct, Description]
2701 // The linear clause declares one or more list items to be private to a SIMD
2702 // lane and to have a linear relationship with respect to the iteration space
2703 // of a loop.
2704 // The special this pointer can be used as if was one of the arguments to the
2705 // function in any of the linear, aligned, or uniform clauses.
2706 // When a linear-step expression is specified in a linear clause it must be
2707 // either a constant integer expression or an integer-typed parameter that is
2708 // specified in a uniform clause on the directive.
2709 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2710 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2711 auto MI = LinModifiers.begin();
2712 for (auto *E : Linears) {
2713 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2714 ++MI;
2715 E = E->IgnoreParenImpCasts();
2716 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2717 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2718 auto *CanonPVD = PVD->getCanonicalDecl();
2719 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2720 FD->getParamDecl(PVD->getFunctionScopeIndex())
2721 ->getCanonicalDecl() == CanonPVD) {
2722 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2723 // A list-item cannot appear in more than one linear clause.
2724 if (LinearArgs.count(CanonPVD) > 0) {
2725 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2726 << getOpenMPClauseName(OMPC_linear)
2727 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2728 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2729 diag::note_omp_explicit_dsa)
2730 << getOpenMPClauseName(OMPC_linear);
2731 continue;
2732 }
2733 // Each argument can appear in at most one uniform or linear clause.
2734 if (UniformedArgs.count(CanonPVD) > 0) {
2735 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2736 << getOpenMPClauseName(OMPC_linear)
2737 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2738 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2739 diag::note_omp_explicit_dsa)
2740 << getOpenMPClauseName(OMPC_uniform);
2741 continue;
2742 }
2743 LinearArgs[CanonPVD] = E;
2744 if (E->isValueDependent() || E->isTypeDependent() ||
2745 E->isInstantiationDependent() ||
2746 E->containsUnexpandedParameterPack())
2747 continue;
2748 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2749 PVD->getOriginalType());
2750 continue;
2751 }
2752 }
2753 if (isa<CXXThisExpr>(E)) {
2754 if (UniformedLinearThis) {
2755 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2756 << getOpenMPClauseName(OMPC_linear)
2757 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2758 << E->getSourceRange();
2759 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2760 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2761 : OMPC_linear);
2762 continue;
2763 }
2764 UniformedLinearThis = E;
2765 if (E->isValueDependent() || E->isTypeDependent() ||
2766 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2767 continue;
2768 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2769 E->getType());
2770 continue;
2771 }
2772 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2773 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2774 }
2775 Expr *Step = nullptr;
2776 Expr *NewStep = nullptr;
2777 SmallVector<Expr *, 4> NewSteps;
2778 for (auto *E : Steps) {
2779 // Skip the same step expression, it was checked already.
2780 if (Step == E || !E) {
2781 NewSteps.push_back(E ? NewStep : nullptr);
2782 continue;
2783 }
2784 Step = E;
2785 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2786 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2787 auto *CanonPVD = PVD->getCanonicalDecl();
2788 if (UniformedArgs.count(CanonPVD) == 0) {
2789 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2790 << Step->getSourceRange();
2791 } else if (E->isValueDependent() || E->isTypeDependent() ||
2792 E->isInstantiationDependent() ||
2793 E->containsUnexpandedParameterPack() ||
2794 CanonPVD->getType()->hasIntegerRepresentation())
2795 NewSteps.push_back(Step);
2796 else {
2797 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2798 << Step->getSourceRange();
2799 }
2800 continue;
2801 }
2802 NewStep = Step;
2803 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2804 !Step->isInstantiationDependent() &&
2805 !Step->containsUnexpandedParameterPack()) {
2806 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2807 .get();
2808 if (NewStep)
2809 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2810 }
2811 NewSteps.push_back(NewStep);
2812 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002813 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2814 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002815 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002816 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2817 const_cast<Expr **>(Linears.data()), Linears.size(),
2818 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2819 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002820 ADecl->addAttr(NewAttr);
2821 return ConvertDeclToDeclGroup(ADecl);
2822}
2823
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002824StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2825 Stmt *AStmt,
2826 SourceLocation StartLoc,
2827 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002828 if (!AStmt)
2829 return StmtError();
2830
Alexey Bataev9959db52014-05-06 10:08:46 +00002831 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2832 // 1.2.2 OpenMP Language Terminology
2833 // Structured block - An executable statement with a single entry at the
2834 // top and a single exit at the bottom.
2835 // The point of exit cannot be a branch out of the structured block.
2836 // longjmp() and throw() must not violate the entry/exit criteria.
2837 CS->getCapturedDecl()->setNothrow();
2838
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002839 getCurFunction()->setHasBranchProtectedScope();
2840
Alexey Bataev25e5b442015-09-15 12:52:43 +00002841 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2842 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002843}
2844
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002845namespace {
2846/// \brief Helper class for checking canonical form of the OpenMP loops and
2847/// extracting iteration space of each loop in the loop nest, that will be used
2848/// for IR generation.
2849class OpenMPIterationSpaceChecker {
2850 /// \brief Reference to Sema.
2851 Sema &SemaRef;
2852 /// \brief A location for diagnostics (when there is no some better location).
2853 SourceLocation DefaultLoc;
2854 /// \brief A location for diagnostics (when increment is not compatible).
2855 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002856 /// \brief A source location for referring to loop init later.
2857 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002858 /// \brief A source location for referring to condition later.
2859 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002860 /// \brief A source location for referring to increment later.
2861 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002862 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002863 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002864 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002865 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002866 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002867 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002868 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002869 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002870 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002871 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002872 /// \brief This flag is true when condition is one of:
2873 /// Var < UB
2874 /// Var <= UB
2875 /// UB > Var
2876 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002877 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002878 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002879 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002880 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002881 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002882
2883public:
2884 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002885 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002886 /// \brief Check init-expr for canonical loop form and save loop counter
2887 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002888 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002889 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2890 /// for less/greater and for strict/non-strict comparison.
2891 bool CheckCond(Expr *S);
2892 /// \brief Check incr-expr for canonical loop form and return true if it
2893 /// does not conform, otherwise save loop step (#Step).
2894 bool CheckInc(Expr *S);
2895 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002896 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002897 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002898 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002899 /// \brief Source range of the loop init.
2900 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2901 /// \brief Source range of the loop condition.
2902 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2903 /// \brief Source range of the loop increment.
2904 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2905 /// \brief True if the step should be subtracted.
2906 bool ShouldSubtractStep() const { return SubtractStep; }
2907 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002908 Expr *
2909 BuildNumIterations(Scope *S, const bool LimitedType,
2910 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002911 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002912 Expr *BuildPreCond(Scope *S, Expr *Cond,
2913 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002914 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002915 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2916 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002917 /// \brief Build reference expression to the private counter be used for
2918 /// codegen.
2919 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002920 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002921 Expr *BuildCounterInit() const;
2922 /// \brief Build step of the counter be used for codegen.
2923 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002924 /// \brief Return true if any expression is dependent.
2925 bool Dependent() const;
2926
2927private:
2928 /// \brief Check the right-hand side of an assignment in the increment
2929 /// expression.
2930 bool CheckIncRHS(Expr *RHS);
2931 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002932 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002933 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002934 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002935 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002936 /// \brief Helper to set loop increment.
2937 bool SetStep(Expr *NewStep, bool Subtract);
2938};
2939
2940bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002941 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002942 assert(!LB && !UB && !Step);
2943 return false;
2944 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002945 return LCDecl->getType()->isDependentType() ||
2946 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2947 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002948}
2949
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002950static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002951 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2952 E = ExprTemp->getSubExpr();
2953
2954 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2955 E = MTE->GetTemporaryExpr();
2956
2957 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2958 E = Binder->getSubExpr();
2959
2960 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2961 E = ICE->getSubExprAsWritten();
2962 return E->IgnoreParens();
2963}
2964
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002965bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2966 Expr *NewLCRefExpr,
2967 Expr *NewLB) {
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 && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002970 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002971 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002972 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002973 LCDecl = getCanonicalDecl(NewLCDecl);
2974 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002975 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2976 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002977 if ((Ctor->isCopyOrMoveConstructor() ||
2978 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2979 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002980 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002981 LB = NewLB;
2982 return false;
2983}
2984
2985bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002986 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002987 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002988 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2989 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002990 if (!NewUB)
2991 return true;
2992 UB = NewUB;
2993 TestIsLessOp = LessOp;
2994 TestIsStrictOp = StrictOp;
2995 ConditionSrcRange = SR;
2996 ConditionLoc = SL;
2997 return false;
2998}
2999
3000bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3001 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003002 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003003 if (!NewStep)
3004 return true;
3005 if (!NewStep->isValueDependent()) {
3006 // Check that the step is integer expression.
3007 SourceLocation StepLoc = NewStep->getLocStart();
3008 ExprResult Val =
3009 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3010 if (Val.isInvalid())
3011 return true;
3012 NewStep = Val.get();
3013
3014 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3015 // If test-expr is of form var relational-op b and relational-op is < or
3016 // <= then incr-expr must cause var to increase on each iteration of the
3017 // loop. If test-expr is of form var relational-op b and relational-op is
3018 // > or >= then incr-expr must cause var to decrease on each iteration of
3019 // the loop.
3020 // If test-expr is of form b relational-op var and relational-op is < or
3021 // <= then incr-expr must cause var to decrease on each iteration of the
3022 // loop. If test-expr is of form b relational-op var and relational-op is
3023 // > or >= then incr-expr must cause var to increase on each iteration of
3024 // the loop.
3025 llvm::APSInt Result;
3026 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3027 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3028 bool IsConstNeg =
3029 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003030 bool IsConstPos =
3031 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003032 bool IsConstZero = IsConstant && !Result.getBoolValue();
3033 if (UB && (IsConstZero ||
3034 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003035 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003036 SemaRef.Diag(NewStep->getExprLoc(),
3037 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003038 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003039 SemaRef.Diag(ConditionLoc,
3040 diag::note_omp_loop_cond_requres_compatible_incr)
3041 << TestIsLessOp << ConditionSrcRange;
3042 return true;
3043 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003044 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003045 NewStep =
3046 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3047 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003048 Subtract = !Subtract;
3049 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003050 }
3051
3052 Step = NewStep;
3053 SubtractStep = Subtract;
3054 return false;
3055}
3056
Alexey Bataev9c821032015-04-30 04:23:23 +00003057bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003058 // Check init-expr for canonical loop form and save loop counter
3059 // variable - #Var and its initialization value - #LB.
3060 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3061 // var = lb
3062 // integer-type var = lb
3063 // random-access-iterator-type var = lb
3064 // pointer-type var = lb
3065 //
3066 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003067 if (EmitDiags) {
3068 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3069 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003070 return true;
3071 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003072 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3073 if (!ExprTemp->cleanupsHaveSideEffects())
3074 S = ExprTemp->getSubExpr();
3075
Alexander Musmana5f070a2014-10-01 06:03:56 +00003076 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003077 if (Expr *E = dyn_cast<Expr>(S))
3078 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003079 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003080 if (BO->getOpcode() == BO_Assign) {
3081 auto *LHS = BO->getLHS()->IgnoreParens();
3082 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3083 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3084 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3085 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3086 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3087 }
3088 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3089 if (ME->isArrow() &&
3090 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3091 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3092 }
3093 }
David Majnemer9d168222016-08-05 17:44:54 +00003094 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003095 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003096 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003097 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003098 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003099 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003100 SemaRef.Diag(S->getLocStart(),
3101 diag::ext_omp_loop_not_canonical_init)
3102 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003103 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003104 }
3105 }
3106 }
David Majnemer9d168222016-08-05 17:44:54 +00003107 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003108 if (CE->getOperator() == OO_Equal) {
3109 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003110 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003111 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3112 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3113 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3114 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3115 }
3116 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3117 if (ME->isArrow() &&
3118 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3119 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3120 }
3121 }
3122 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003123
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003124 if (Dependent() || SemaRef.CurContext->isDependentContext())
3125 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003126 if (EmitDiags) {
3127 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3128 << S->getSourceRange();
3129 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003130 return true;
3131}
3132
Alexey Bataev23b69422014-06-18 07:08:49 +00003133/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003134/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003135static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003136 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003137 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003138 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003139 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3140 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003141 if ((Ctor->isCopyOrMoveConstructor() ||
3142 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3143 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003144 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003145 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3146 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3147 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3148 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3149 return getCanonicalDecl(ME->getMemberDecl());
3150 return getCanonicalDecl(VD);
3151 }
3152 }
3153 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3154 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3155 return getCanonicalDecl(ME->getMemberDecl());
3156 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003157}
3158
3159bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3160 // Check test-expr for canonical form, save upper-bound UB, flags for
3161 // less/greater and for strict/non-strict comparison.
3162 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3163 // var relational-op b
3164 // b relational-op var
3165 //
3166 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003167 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 return true;
3169 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003170 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003171 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003172 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003173 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003175 return SetUB(BO->getRHS(),
3176 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3177 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3178 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003179 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003180 return SetUB(BO->getLHS(),
3181 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3182 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3183 BO->getSourceRange(), BO->getOperatorLoc());
3184 }
David Majnemer9d168222016-08-05 17:44:54 +00003185 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 if (CE->getNumArgs() == 2) {
3187 auto Op = CE->getOperator();
3188 switch (Op) {
3189 case OO_Greater:
3190 case OO_GreaterEqual:
3191 case OO_Less:
3192 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003193 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003194 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3195 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3196 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003197 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003198 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3199 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3200 CE->getOperatorLoc());
3201 break;
3202 default:
3203 break;
3204 }
3205 }
3206 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003207 if (Dependent() || SemaRef.CurContext->isDependentContext())
3208 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003209 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003210 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003211 return true;
3212}
3213
3214bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3215 // RHS of canonical loop form increment can be:
3216 // var + incr
3217 // incr + var
3218 // var - incr
3219 //
3220 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003221 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003222 if (BO->isAdditiveOp()) {
3223 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003224 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003225 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003226 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003227 return SetStep(BO->getLHS(), false);
3228 }
David Majnemer9d168222016-08-05 17:44:54 +00003229 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003230 bool IsAdd = CE->getOperator() == OO_Plus;
3231 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003232 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003233 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003234 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003235 return SetStep(CE->getArg(0), false);
3236 }
3237 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003238 if (Dependent() || SemaRef.CurContext->isDependentContext())
3239 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003240 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003241 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003242 return true;
3243}
3244
3245bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3246 // Check incr-expr for canonical loop form and return true if it
3247 // does not conform.
3248 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3249 // ++var
3250 // var++
3251 // --var
3252 // var--
3253 // var += incr
3254 // var -= incr
3255 // var = var + incr
3256 // var = incr + var
3257 // var = var - incr
3258 //
3259 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003260 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003261 return true;
3262 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003263 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3264 if (!ExprTemp->cleanupsHaveSideEffects())
3265 S = ExprTemp->getSubExpr();
3266
Alexander Musmana5f070a2014-10-01 06:03:56 +00003267 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003268 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003269 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003270 if (UO->isIncrementDecrementOp() &&
3271 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003272 return SetStep(SemaRef
3273 .ActOnIntegerConstant(UO->getLocStart(),
3274 (UO->isDecrementOp() ? -1 : 1))
3275 .get(),
3276 false);
3277 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003278 switch (BO->getOpcode()) {
3279 case BO_AddAssign:
3280 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003281 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003282 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3283 break;
3284 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003285 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003286 return CheckIncRHS(BO->getRHS());
3287 break;
3288 default:
3289 break;
3290 }
David Majnemer9d168222016-08-05 17:44:54 +00003291 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003292 switch (CE->getOperator()) {
3293 case OO_PlusPlus:
3294 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003295 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003296 return SetStep(SemaRef
3297 .ActOnIntegerConstant(
3298 CE->getLocStart(),
3299 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3300 .get(),
3301 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003302 break;
3303 case OO_PlusEqual:
3304 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003305 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003306 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3307 break;
3308 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003309 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003310 return CheckIncRHS(CE->getArg(1));
3311 break;
3312 default:
3313 break;
3314 }
3315 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003316 if (Dependent() || SemaRef.CurContext->isDependentContext())
3317 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003318 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003319 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003320 return true;
3321}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003322
Alexey Bataev5a3af132016-03-29 08:58:54 +00003323static ExprResult
3324tryBuildCapture(Sema &SemaRef, Expr *Capture,
3325 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003326 if (SemaRef.CurContext->isDependentContext())
3327 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003328 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3329 return SemaRef.PerformImplicitConversion(
3330 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3331 /*AllowExplicit=*/true);
3332 auto I = Captures.find(Capture);
3333 if (I != Captures.end())
3334 return buildCapture(SemaRef, Capture, I->second);
3335 DeclRefExpr *Ref = nullptr;
3336 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3337 Captures[Capture] = Ref;
3338 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003339}
3340
Alexander Musmana5f070a2014-10-01 06:03:56 +00003341/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003342Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3343 Scope *S, const bool LimitedType,
3344 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003345 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003346 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003347 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003348 SemaRef.getLangOpts().CPlusPlus) {
3349 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003350 auto *UBExpr = TestIsLessOp ? UB : LB;
3351 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003352 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3353 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003354 if (!Upper || !Lower)
3355 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003356
3357 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3358
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003359 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003360 // BuildBinOp already emitted error, this one is to point user to upper
3361 // and lower bound, and to tell what is passed to 'operator-'.
3362 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3363 << Upper->getSourceRange() << Lower->getSourceRange();
3364 return nullptr;
3365 }
3366 }
3367
3368 if (!Diff.isUsable())
3369 return nullptr;
3370
3371 // Upper - Lower [- 1]
3372 if (TestIsStrictOp)
3373 Diff = SemaRef.BuildBinOp(
3374 S, DefaultLoc, BO_Sub, Diff.get(),
3375 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3376 if (!Diff.isUsable())
3377 return nullptr;
3378
3379 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003380 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3381 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003382 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003383 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003384 if (!Diff.isUsable())
3385 return nullptr;
3386
3387 // Parentheses (for dumping/debugging purposes only).
3388 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3389 if (!Diff.isUsable())
3390 return nullptr;
3391
3392 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003393 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003394 if (!Diff.isUsable())
3395 return nullptr;
3396
Alexander Musman174b3ca2014-10-06 11:16:29 +00003397 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003398 QualType Type = Diff.get()->getType();
3399 auto &C = SemaRef.Context;
3400 bool UseVarType = VarType->hasIntegerRepresentation() &&
3401 C.getTypeSize(Type) > C.getTypeSize(VarType);
3402 if (!Type->isIntegerType() || UseVarType) {
3403 unsigned NewSize =
3404 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3405 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3406 : Type->hasSignedIntegerRepresentation();
3407 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003408 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3409 Diff = SemaRef.PerformImplicitConversion(
3410 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3411 if (!Diff.isUsable())
3412 return nullptr;
3413 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003414 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003415 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003416 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3417 if (NewSize != C.getTypeSize(Type)) {
3418 if (NewSize < C.getTypeSize(Type)) {
3419 assert(NewSize == 64 && "incorrect loop var size");
3420 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3421 << InitSrcRange << ConditionSrcRange;
3422 }
3423 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003424 NewSize, Type->hasSignedIntegerRepresentation() ||
3425 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003426 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3427 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3428 Sema::AA_Converting, true);
3429 if (!Diff.isUsable())
3430 return nullptr;
3431 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003432 }
3433 }
3434
Alexander Musmana5f070a2014-10-01 06:03:56 +00003435 return Diff.get();
3436}
3437
Alexey Bataev5a3af132016-03-29 08:58:54 +00003438Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3439 Scope *S, Expr *Cond,
3440 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003441 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3442 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3443 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003444
Alexey Bataev5a3af132016-03-29 08:58:54 +00003445 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3446 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3447 if (!NewLB.isUsable() || !NewUB.isUsable())
3448 return nullptr;
3449
Alexey Bataev62dbb972015-04-22 11:59:37 +00003450 auto CondExpr = SemaRef.BuildBinOp(
3451 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3452 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003453 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003454 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003455 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3456 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003457 CondExpr = SemaRef.PerformImplicitConversion(
3458 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3459 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003460 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003461 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3462 // Otherwise use original loop conditon and evaluate it in runtime.
3463 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3464}
3465
Alexander Musmana5f070a2014-10-01 06:03:56 +00003466/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003467DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003468 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003469 auto *VD = dyn_cast<VarDecl>(LCDecl);
3470 if (!VD) {
3471 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3472 auto *Ref = buildDeclRefExpr(
3473 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003474 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3475 // If the loop control decl is explicitly marked as private, do not mark it
3476 // as captured again.
3477 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3478 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003479 return Ref;
3480 }
3481 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003482 DefaultLoc);
3483}
3484
3485Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003486 if (LCDecl && !LCDecl->isInvalidDecl()) {
3487 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003488 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003489 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3490 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003491 if (PrivateVar->isInvalidDecl())
3492 return nullptr;
3493 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3494 }
3495 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003496}
3497
Samuel Antao4c8035b2016-12-12 18:00:20 +00003498/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003499Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3500
3501/// \brief Build step of the counter be used for codegen.
3502Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3503
3504/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003505struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003506 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003507 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003508 /// \brief This expression calculates the number of iterations in the loop.
3509 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003510 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003511 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003512 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003513 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003514 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003515 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003516 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003517 /// \brief This is step for the #CounterVar used to generate its update:
3518 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003519 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003520 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003521 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003522 /// \brief Source range of the loop init.
3523 SourceRange InitSrcRange;
3524 /// \brief Source range of the loop condition.
3525 SourceRange CondSrcRange;
3526 /// \brief Source range of the loop increment.
3527 SourceRange IncSrcRange;
3528};
3529
Alexey Bataev23b69422014-06-18 07:08:49 +00003530} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003531
Alexey Bataev9c821032015-04-30 04:23:23 +00003532void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3533 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3534 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003535 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3536 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003537 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3538 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003539 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3540 if (auto *D = ISC.GetLoopDecl()) {
3541 auto *VD = dyn_cast<VarDecl>(D);
3542 if (!VD) {
3543 if (auto *Private = IsOpenMPCapturedDecl(D))
3544 VD = Private;
3545 else {
3546 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3547 /*WithInit=*/false);
3548 VD = cast<VarDecl>(Ref->getDecl());
3549 }
3550 }
3551 DSAStack->addLoopControlVariable(D, VD);
3552 }
3553 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003554 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003555 }
3556}
3557
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003558/// \brief Called on a for stmt to check and extract its iteration space
3559/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003560static bool CheckOpenMPIterationSpace(
3561 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3562 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003563 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003564 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003565 LoopIterationSpace &ResultIterSpace,
3566 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003567 // OpenMP [2.6, Canonical Loop Form]
3568 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003569 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003570 if (!For) {
3571 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003572 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3573 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3574 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3575 if (NestedLoopCount > 1) {
3576 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3577 SemaRef.Diag(DSA.getConstructLoc(),
3578 diag::note_omp_collapse_ordered_expr)
3579 << 2 << CollapseLoopCountExpr->getSourceRange()
3580 << OrderedLoopCountExpr->getSourceRange();
3581 else if (CollapseLoopCountExpr)
3582 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3583 diag::note_omp_collapse_ordered_expr)
3584 << 0 << CollapseLoopCountExpr->getSourceRange();
3585 else
3586 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3587 diag::note_omp_collapse_ordered_expr)
3588 << 1 << OrderedLoopCountExpr->getSourceRange();
3589 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003590 return true;
3591 }
3592 assert(For->getBody());
3593
3594 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3595
3596 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003597 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003598 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003599 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003600
3601 bool HasErrors = false;
3602
3603 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003604 if (auto *LCDecl = ISC.GetLoopDecl()) {
3605 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003606
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003607 // OpenMP [2.6, Canonical Loop Form]
3608 // Var is one of the following:
3609 // A variable of signed or unsigned integer type.
3610 // For C++, a variable of a random access iterator type.
3611 // For C, a variable of a pointer type.
3612 auto VarType = LCDecl->getType().getNonReferenceType();
3613 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3614 !VarType->isPointerType() &&
3615 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3616 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3617 << SemaRef.getLangOpts().CPlusPlus;
3618 HasErrors = true;
3619 }
3620
3621 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3622 // a Construct
3623 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3624 // parallel for construct is (are) private.
3625 // The loop iteration variable in the associated for-loop of a simd
3626 // construct with just one associated for-loop is linear with a
3627 // constant-linear-step that is the increment of the associated for-loop.
3628 // Exclude loop var from the list of variables with implicitly defined data
3629 // sharing attributes.
3630 VarsWithImplicitDSA.erase(LCDecl);
3631
3632 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3633 // in a Construct, C/C++].
3634 // The loop iteration variable in the associated for-loop of a simd
3635 // construct with just one associated for-loop may be listed in a linear
3636 // clause with a constant-linear-step that is the increment of the
3637 // associated for-loop.
3638 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3639 // parallel for construct may be listed in a private or lastprivate clause.
3640 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3641 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3642 // declared in the loop and it is predetermined as a private.
3643 auto PredeterminedCKind =
3644 isOpenMPSimdDirective(DKind)
3645 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3646 : OMPC_private;
3647 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3648 DVar.CKind != PredeterminedCKind) ||
3649 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3650 isOpenMPDistributeDirective(DKind)) &&
3651 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3652 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3653 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3654 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3655 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3656 << getOpenMPClauseName(PredeterminedCKind);
3657 if (DVar.RefExpr == nullptr)
3658 DVar.CKind = PredeterminedCKind;
3659 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3660 HasErrors = true;
3661 } else if (LoopDeclRefExpr != nullptr) {
3662 // Make the loop iteration variable private (for worksharing constructs),
3663 // linear (for simd directives with the only one associated loop) or
3664 // lastprivate (for simd directives with several collapsed or ordered
3665 // loops).
3666 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003667 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3668 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003669 /*FromParent=*/false);
3670 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3671 }
3672
3673 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3674
3675 // Check test-expr.
3676 HasErrors |= ISC.CheckCond(For->getCond());
3677
3678 // Check incr-expr.
3679 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003680 }
3681
Alexander Musmana5f070a2014-10-01 06:03:56 +00003682 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003683 return HasErrors;
3684
Alexander Musmana5f070a2014-10-01 06:03:56 +00003685 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003686 ResultIterSpace.PreCond =
3687 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003688 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003689 DSA.getCurScope(),
3690 (isOpenMPWorksharingDirective(DKind) ||
3691 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3692 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003693 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003694 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003695 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3696 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3697 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3698 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3699 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3700 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3701
Alexey Bataev62dbb972015-04-22 11:59:37 +00003702 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3703 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003704 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003705 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003706 ResultIterSpace.CounterInit == nullptr ||
3707 ResultIterSpace.CounterStep == nullptr);
3708
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003709 return HasErrors;
3710}
3711
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003712/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003713static ExprResult
3714BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3715 ExprResult Start,
3716 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003717 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003718 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3719 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003720 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003721 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003722 VarRef.get()->getType())) {
3723 NewStart = SemaRef.PerformImplicitConversion(
3724 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3725 /*AllowExplicit=*/true);
3726 if (!NewStart.isUsable())
3727 return ExprError();
3728 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003729
3730 auto Init =
3731 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3732 return Init;
3733}
3734
Alexander Musmana5f070a2014-10-01 06:03:56 +00003735/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003736static ExprResult
3737BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3738 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3739 ExprResult Step, bool Subtract,
3740 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003741 // Add parentheses (for debugging purposes only).
3742 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3743 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3744 !Step.isUsable())
3745 return ExprError();
3746
Alexey Bataev5a3af132016-03-29 08:58:54 +00003747 ExprResult NewStep = Step;
3748 if (Captures)
3749 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003750 if (NewStep.isInvalid())
3751 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003752 ExprResult Update =
3753 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003754 if (!Update.isUsable())
3755 return ExprError();
3756
Alexey Bataevc0214e02016-02-16 12:13:49 +00003757 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3758 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003759 ExprResult NewStart = Start;
3760 if (Captures)
3761 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003762 if (NewStart.isInvalid())
3763 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003764
Alexey Bataevc0214e02016-02-16 12:13:49 +00003765 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3766 ExprResult SavedUpdate = Update;
3767 ExprResult UpdateVal;
3768 if (VarRef.get()->getType()->isOverloadableType() ||
3769 NewStart.get()->getType()->isOverloadableType() ||
3770 Update.get()->getType()->isOverloadableType()) {
3771 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3772 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3773 Update =
3774 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3775 if (Update.isUsable()) {
3776 UpdateVal =
3777 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3778 VarRef.get(), SavedUpdate.get());
3779 if (UpdateVal.isUsable()) {
3780 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3781 UpdateVal.get());
3782 }
3783 }
3784 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3785 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003786
Alexey Bataevc0214e02016-02-16 12:13:49 +00003787 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3788 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3789 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3790 NewStart.get(), SavedUpdate.get());
3791 if (!Update.isUsable())
3792 return ExprError();
3793
Alexey Bataev11481f52016-02-17 10:29:05 +00003794 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3795 VarRef.get()->getType())) {
3796 Update = SemaRef.PerformImplicitConversion(
3797 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3798 if (!Update.isUsable())
3799 return ExprError();
3800 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003801
3802 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3803 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003804 return Update;
3805}
3806
3807/// \brief Convert integer expression \a E to make it have at least \a Bits
3808/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003809static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003810 if (E == nullptr)
3811 return ExprError();
3812 auto &C = SemaRef.Context;
3813 QualType OldType = E->getType();
3814 unsigned HasBits = C.getTypeSize(OldType);
3815 if (HasBits >= Bits)
3816 return ExprResult(E);
3817 // OK to convert to signed, because new type has more bits than old.
3818 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3819 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3820 true);
3821}
3822
3823/// \brief Check if the given expression \a E is a constant integer that fits
3824/// into \a Bits bits.
3825static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3826 if (E == nullptr)
3827 return false;
3828 llvm::APSInt Result;
3829 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3830 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3831 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003832}
3833
Alexey Bataev5a3af132016-03-29 08:58:54 +00003834/// Build preinits statement for the given declarations.
3835static Stmt *buildPreInits(ASTContext &Context,
3836 SmallVectorImpl<Decl *> &PreInits) {
3837 if (!PreInits.empty()) {
3838 return new (Context) DeclStmt(
3839 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3840 SourceLocation(), SourceLocation());
3841 }
3842 return nullptr;
3843}
3844
3845/// Build preinits statement for the given declarations.
3846static Stmt *buildPreInits(ASTContext &Context,
3847 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3848 if (!Captures.empty()) {
3849 SmallVector<Decl *, 16> PreInits;
3850 for (auto &Pair : Captures)
3851 PreInits.push_back(Pair.second->getDecl());
3852 return buildPreInits(Context, PreInits);
3853 }
3854 return nullptr;
3855}
3856
3857/// Build postupdate expression for the given list of postupdates expressions.
3858static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3859 Expr *PostUpdate = nullptr;
3860 if (!PostUpdates.empty()) {
3861 for (auto *E : PostUpdates) {
3862 Expr *ConvE = S.BuildCStyleCastExpr(
3863 E->getExprLoc(),
3864 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3865 E->getExprLoc(), E)
3866 .get();
3867 PostUpdate = PostUpdate
3868 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3869 PostUpdate, ConvE)
3870 .get()
3871 : ConvE;
3872 }
3873 }
3874 return PostUpdate;
3875}
3876
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003877/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003878/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3879/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003880static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003881CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3882 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3883 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003884 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003885 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003886 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003887 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003888 // Found 'collapse' clause - calculate collapse number.
3889 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003890 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003891 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003892 }
3893 if (OrderedLoopCountExpr) {
3894 // Found 'ordered' clause - calculate collapse number.
3895 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003896 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3897 if (Result.getLimitedValue() < NestedLoopCount) {
3898 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3899 diag::err_omp_wrong_ordered_loop_count)
3900 << OrderedLoopCountExpr->getSourceRange();
3901 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3902 diag::note_collapse_loop_count)
3903 << CollapseLoopCountExpr->getSourceRange();
3904 }
3905 NestedLoopCount = Result.getLimitedValue();
3906 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003907 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003908 // This is helper routine for loop directives (e.g., 'for', 'simd',
3909 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003910 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003911 SmallVector<LoopIterationSpace, 4> IterSpaces;
3912 IterSpaces.resize(NestedLoopCount);
3913 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003914 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003915 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003916 NestedLoopCount, CollapseLoopCountExpr,
3917 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003918 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003919 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003920 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003921 // OpenMP [2.8.1, simd construct, Restrictions]
3922 // All loops associated with the construct must be perfectly nested; that
3923 // is, there must be no intervening code nor any OpenMP directive between
3924 // any two loops.
3925 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003926 }
3927
Alexander Musmana5f070a2014-10-01 06:03:56 +00003928 Built.clear(/* size */ NestedLoopCount);
3929
3930 if (SemaRef.CurContext->isDependentContext())
3931 return NestedLoopCount;
3932
3933 // An example of what is generated for the following code:
3934 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003935 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003936 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003937 // for (k = 0; k < NK; ++k)
3938 // for (j = J0; j < NJ; j+=2) {
3939 // <loop body>
3940 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003941 //
3942 // We generate the code below.
3943 // Note: the loop body may be outlined in CodeGen.
3944 // Note: some counters may be C++ classes, operator- is used to find number of
3945 // iterations and operator+= to calculate counter value.
3946 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3947 // or i64 is currently supported).
3948 //
3949 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3950 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3951 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3952 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3953 // // similar updates for vars in clauses (e.g. 'linear')
3954 // <loop body (using local i and j)>
3955 // }
3956 // i = NI; // assign final values of counters
3957 // j = NJ;
3958 //
3959
3960 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3961 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003962 // Precondition tests if there is at least one iteration (all conditions are
3963 // true).
3964 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003965 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003966 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003967 32 /* Bits */, SemaRef
3968 .PerformImplicitConversion(
3969 N0->IgnoreImpCasts(), N0->getType(),
3970 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003971 .get(),
3972 SemaRef);
3973 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003974 64 /* Bits */, SemaRef
3975 .PerformImplicitConversion(
3976 N0->IgnoreImpCasts(), N0->getType(),
3977 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003978 .get(),
3979 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003980
3981 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3982 return NestedLoopCount;
3983
3984 auto &C = SemaRef.Context;
3985 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3986
3987 Scope *CurScope = DSA.getCurScope();
3988 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003989 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003990 PreCond =
3991 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3992 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003993 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003994 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003995 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003996 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3997 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003998 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003999 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004000 SemaRef
4001 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4002 Sema::AA_Converting,
4003 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004004 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004005 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004006 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004007 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004008 SemaRef
4009 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4010 Sema::AA_Converting,
4011 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004012 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004013 }
4014
4015 // Choose either the 32-bit or 64-bit version.
4016 ExprResult LastIteration = LastIteration64;
4017 if (LastIteration32.isUsable() &&
4018 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4019 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4020 FitsInto(
4021 32 /* Bits */,
4022 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4023 LastIteration64.get(), SemaRef)))
4024 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004025 QualType VType = LastIteration.get()->getType();
4026 QualType RealVType = VType;
4027 QualType StrideVType = VType;
4028 if (isOpenMPTaskLoopDirective(DKind)) {
4029 VType =
4030 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4031 StrideVType =
4032 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4033 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004034
4035 if (!LastIteration.isUsable())
4036 return 0;
4037
4038 // Save the number of iterations.
4039 ExprResult NumIterations = LastIteration;
4040 {
4041 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004042 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4043 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4045 if (!LastIteration.isUsable())
4046 return 0;
4047 }
4048
4049 // Calculate the last iteration number beforehand instead of doing this on
4050 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4051 llvm::APSInt Result;
4052 bool IsConstant =
4053 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4054 ExprResult CalcLastIteration;
4055 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004056 ExprResult SaveRef =
4057 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004058 LastIteration = SaveRef;
4059
4060 // Prepare SaveRef + 1.
4061 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004062 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004063 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4064 if (!NumIterations.isUsable())
4065 return 0;
4066 }
4067
4068 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4069
David Majnemer9d168222016-08-05 17:44:54 +00004070 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00004071 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004072 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4073 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004074 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004075 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4076 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004077 SemaRef.AddInitializerToDecl(LBDecl,
4078 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4079 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004080
4081 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004082 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4083 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004084 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004085 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004086
4087 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4088 // This will be used to implement clause 'lastprivate'.
4089 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004090 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4091 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004092 SemaRef.AddInitializerToDecl(ILDecl,
4093 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4094 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004095
4096 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004097 VarDecl *STDecl =
4098 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4099 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004100 SemaRef.AddInitializerToDecl(STDecl,
4101 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4102 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004103
4104 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004105 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004106 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4107 UB.get(), LastIteration.get());
4108 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4109 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4110 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4111 CondOp.get());
4112 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004113
4114 // If we have a combined directive that combines 'distribute', 'for' or
4115 // 'simd' we need to be able to access the bounds of the schedule of the
4116 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4117 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4118 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4119 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4120
4121 // We expect to have at least 2 more parameters than the 'parallel'
4122 // directive does - the lower and upper bounds of the previous schedule.
4123 assert(CD->getNumParams() >= 4 &&
4124 "Unexpected number of parameters in loop combined directive");
4125
4126 // Set the proper type for the bounds given what we learned from the
4127 // enclosed loops.
4128 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4129 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4130
4131 // Previous lower and upper bounds are obtained from the region
4132 // parameters.
4133 PrevLB =
4134 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4135 PrevUB =
4136 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4137 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004138 }
4139
4140 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004141 ExprResult IV;
4142 ExprResult Init;
4143 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004144 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4145 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004146 Expr *RHS =
4147 (isOpenMPWorksharingDirective(DKind) ||
4148 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4149 ? LB.get()
4150 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004151 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4152 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004153 }
4154
Alexander Musmanc6388682014-12-15 07:07:06 +00004155 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004156 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004157 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004158 (isOpenMPWorksharingDirective(DKind) ||
4159 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004160 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4161 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4162 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004163
4164 // Loop increment (IV = IV + 1)
4165 SourceLocation IncLoc;
4166 ExprResult Inc =
4167 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4168 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4169 if (!Inc.isUsable())
4170 return 0;
4171 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004172 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4173 if (!Inc.isUsable())
4174 return 0;
4175
4176 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4177 // Used for directives with static scheduling.
4178 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004179 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4180 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004181 // LB + ST
4182 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4183 if (!NextLB.isUsable())
4184 return 0;
4185 // LB = LB + ST
4186 NextLB =
4187 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4188 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4189 if (!NextLB.isUsable())
4190 return 0;
4191 // UB + ST
4192 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4193 if (!NextUB.isUsable())
4194 return 0;
4195 // UB = UB + ST
4196 NextUB =
4197 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4198 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4199 if (!NextUB.isUsable())
4200 return 0;
4201 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004202
Carlo Bertolli8429d812017-02-17 21:29:13 +00004203 // Create: increment expression for distribute loop when combined in a same
4204 // directive with for as IV = IV + ST; ensure upper bound expression based
4205 // on PrevUB instead of NumIterations - used to implement 'for' when found
4206 // in combination with 'distribute', like in 'distribute parallel for'
4207 SourceLocation DistIncLoc;
4208 ExprResult DistCond, DistInc, PrevEUB;
4209 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4210 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4211 assert(DistCond.isUsable() && "distribute cond expr was not built");
4212
4213 DistInc =
4214 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4215 assert(DistInc.isUsable() && "distribute inc expr was not built");
4216 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4217 DistInc.get());
4218 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4219 assert(DistInc.isUsable() && "distribute inc expr was not built");
4220
4221 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4222 // construct
4223 SourceLocation DistEUBLoc;
4224 ExprResult IsUBGreater =
4225 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4226 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4227 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4228 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4229 CondOp.get());
4230 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4231 }
4232
Alexander Musmana5f070a2014-10-01 06:03:56 +00004233 // Build updates and final values of the loop counters.
4234 bool HasErrors = false;
4235 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004236 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004237 Built.Updates.resize(NestedLoopCount);
4238 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004239 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004240 {
4241 ExprResult Div;
4242 // Go from inner nested loop to outer.
4243 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4244 LoopIterationSpace &IS = IterSpaces[Cnt];
4245 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4246 // Build: Iter = (IV / Div) % IS.NumIters
4247 // where Div is product of previous iterations' IS.NumIters.
4248 ExprResult Iter;
4249 if (Div.isUsable()) {
4250 Iter =
4251 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4252 } else {
4253 Iter = IV;
4254 assert((Cnt == (int)NestedLoopCount - 1) &&
4255 "unusable div expected on first iteration only");
4256 }
4257
4258 if (Cnt != 0 && Iter.isUsable())
4259 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4260 IS.NumIterations);
4261 if (!Iter.isUsable()) {
4262 HasErrors = true;
4263 break;
4264 }
4265
Alexey Bataev39f915b82015-05-08 10:41:21 +00004266 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004267 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4268 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4269 IS.CounterVar->getExprLoc(),
4270 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004271 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004272 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004273 if (!Init.isUsable()) {
4274 HasErrors = true;
4275 break;
4276 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004277 ExprResult Update = BuildCounterUpdate(
4278 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4279 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004280 if (!Update.isUsable()) {
4281 HasErrors = true;
4282 break;
4283 }
4284
4285 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4286 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004287 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004288 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004289 if (!Final.isUsable()) {
4290 HasErrors = true;
4291 break;
4292 }
4293
4294 // Build Div for the next iteration: Div <- Div * IS.NumIters
4295 if (Cnt != 0) {
4296 if (Div.isUnset())
4297 Div = IS.NumIterations;
4298 else
4299 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4300 IS.NumIterations);
4301
4302 // Add parentheses (for debugging purposes only).
4303 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004304 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004305 if (!Div.isUsable()) {
4306 HasErrors = true;
4307 break;
4308 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004309 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004310 }
4311 if (!Update.isUsable() || !Final.isUsable()) {
4312 HasErrors = true;
4313 break;
4314 }
4315 // Save results
4316 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004317 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004318 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004319 Built.Updates[Cnt] = Update.get();
4320 Built.Finals[Cnt] = Final.get();
4321 }
4322 }
4323
4324 if (HasErrors)
4325 return 0;
4326
4327 // Save results
4328 Built.IterationVarRef = IV.get();
4329 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004330 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004331 Built.CalcLastIteration =
4332 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004333 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004334 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004335 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004336 Built.Init = Init.get();
4337 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004338 Built.LB = LB.get();
4339 Built.UB = UB.get();
4340 Built.IL = IL.get();
4341 Built.ST = ST.get();
4342 Built.EUB = EUB.get();
4343 Built.NLB = NextLB.get();
4344 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004345 Built.PrevLB = PrevLB.get();
4346 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004347 Built.DistInc = DistInc.get();
4348 Built.PrevEUB = PrevEUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004349
Alexey Bataev8b427062016-05-25 12:36:08 +00004350 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4351 // Fill data for doacross depend clauses.
4352 for (auto Pair : DSA.getDoacrossDependClauses()) {
4353 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4354 Pair.first->setCounterValue(CounterVal);
4355 else {
4356 if (NestedLoopCount != Pair.second.size() ||
4357 NestedLoopCount != LoopMultipliers.size() + 1) {
4358 // Erroneous case - clause has some problems.
4359 Pair.first->setCounterValue(CounterVal);
4360 continue;
4361 }
4362 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4363 auto I = Pair.second.rbegin();
4364 auto IS = IterSpaces.rbegin();
4365 auto ILM = LoopMultipliers.rbegin();
4366 Expr *UpCounterVal = CounterVal;
4367 Expr *Multiplier = nullptr;
4368 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4369 if (I->first) {
4370 assert(IS->CounterStep);
4371 Expr *NormalizedOffset =
4372 SemaRef
4373 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4374 I->first, IS->CounterStep)
4375 .get();
4376 if (Multiplier) {
4377 NormalizedOffset =
4378 SemaRef
4379 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4380 NormalizedOffset, Multiplier)
4381 .get();
4382 }
4383 assert(I->second == OO_Plus || I->second == OO_Minus);
4384 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004385 UpCounterVal = SemaRef
4386 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4387 UpCounterVal, NormalizedOffset)
4388 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004389 }
4390 Multiplier = *ILM;
4391 ++I;
4392 ++IS;
4393 ++ILM;
4394 }
4395 Pair.first->setCounterValue(UpCounterVal);
4396 }
4397 }
4398
Alexey Bataevabfc0692014-06-25 06:52:00 +00004399 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004400}
4401
Alexey Bataev10e775f2015-07-30 11:36:16 +00004402static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004403 auto CollapseClauses =
4404 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4405 if (CollapseClauses.begin() != CollapseClauses.end())
4406 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004407 return nullptr;
4408}
4409
Alexey Bataev10e775f2015-07-30 11:36:16 +00004410static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004411 auto OrderedClauses =
4412 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4413 if (OrderedClauses.begin() != OrderedClauses.end())
4414 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004415 return nullptr;
4416}
4417
Kelvin Lic5609492016-07-15 04:39:07 +00004418static bool checkSimdlenSafelenSpecified(Sema &S,
4419 const ArrayRef<OMPClause *> Clauses) {
4420 OMPSafelenClause *Safelen = nullptr;
4421 OMPSimdlenClause *Simdlen = nullptr;
4422
4423 for (auto *Clause : Clauses) {
4424 if (Clause->getClauseKind() == OMPC_safelen)
4425 Safelen = cast<OMPSafelenClause>(Clause);
4426 else if (Clause->getClauseKind() == OMPC_simdlen)
4427 Simdlen = cast<OMPSimdlenClause>(Clause);
4428 if (Safelen && Simdlen)
4429 break;
4430 }
4431
4432 if (Simdlen && Safelen) {
4433 llvm::APSInt SimdlenRes, SafelenRes;
4434 auto SimdlenLength = Simdlen->getSimdlen();
4435 auto SafelenLength = Safelen->getSafelen();
4436 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4437 SimdlenLength->isInstantiationDependent() ||
4438 SimdlenLength->containsUnexpandedParameterPack())
4439 return false;
4440 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4441 SafelenLength->isInstantiationDependent() ||
4442 SafelenLength->containsUnexpandedParameterPack())
4443 return false;
4444 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4445 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4446 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4447 // If both simdlen and safelen clauses are specified, the value of the
4448 // simdlen parameter must be less than or equal to the value of the safelen
4449 // parameter.
4450 if (SimdlenRes > SafelenRes) {
4451 S.Diag(SimdlenLength->getExprLoc(),
4452 diag::err_omp_wrong_simdlen_safelen_values)
4453 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4454 return true;
4455 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004456 }
4457 return false;
4458}
4459
Alexey Bataev4acb8592014-07-07 13:01:15 +00004460StmtResult Sema::ActOnOpenMPSimdDirective(
4461 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4462 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004463 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004464 if (!AStmt)
4465 return StmtError();
4466
4467 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004468 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004469 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4470 // define the nested loops number.
4471 unsigned NestedLoopCount = CheckOpenMPLoop(
4472 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4473 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004474 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004475 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004476
Alexander Musmana5f070a2014-10-01 06:03:56 +00004477 assert((CurContext->isDependentContext() || B.builtAll()) &&
4478 "omp simd loop exprs were not built");
4479
Alexander Musman3276a272015-03-21 10:12:56 +00004480 if (!CurContext->isDependentContext()) {
4481 // Finalize the clauses that need pre-built expressions for CodeGen.
4482 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004483 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004484 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004485 B.NumIterations, *this, CurScope,
4486 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004487 return StmtError();
4488 }
4489 }
4490
Kelvin Lic5609492016-07-15 04:39:07 +00004491 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004492 return StmtError();
4493
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004494 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004495 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4496 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004497}
4498
Alexey Bataev4acb8592014-07-07 13:01:15 +00004499StmtResult Sema::ActOnOpenMPForDirective(
4500 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4501 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004502 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004503 if (!AStmt)
4504 return StmtError();
4505
4506 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004507 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004508 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4509 // define the nested loops number.
4510 unsigned NestedLoopCount = CheckOpenMPLoop(
4511 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4512 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004513 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004514 return StmtError();
4515
Alexander Musmana5f070a2014-10-01 06:03:56 +00004516 assert((CurContext->isDependentContext() || B.builtAll()) &&
4517 "omp for loop exprs were not built");
4518
Alexey Bataev54acd402015-08-04 11:18:19 +00004519 if (!CurContext->isDependentContext()) {
4520 // Finalize the clauses that need pre-built expressions for CodeGen.
4521 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004522 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004523 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004524 B.NumIterations, *this, CurScope,
4525 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004526 return StmtError();
4527 }
4528 }
4529
Alexey Bataevf29276e2014-06-18 04:14:57 +00004530 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004531 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004532 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004533}
4534
Alexander Musmanf82886e2014-09-18 05:12:34 +00004535StmtResult Sema::ActOnOpenMPForSimdDirective(
4536 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4537 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004538 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004539 if (!AStmt)
4540 return StmtError();
4541
4542 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004543 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004544 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4545 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004546 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004547 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4548 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4549 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004550 if (NestedLoopCount == 0)
4551 return StmtError();
4552
Alexander Musmanc6388682014-12-15 07:07:06 +00004553 assert((CurContext->isDependentContext() || B.builtAll()) &&
4554 "omp for simd loop exprs were not built");
4555
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004556 if (!CurContext->isDependentContext()) {
4557 // Finalize the clauses that need pre-built expressions for CodeGen.
4558 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004559 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004560 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004561 B.NumIterations, *this, CurScope,
4562 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004563 return StmtError();
4564 }
4565 }
4566
Kelvin Lic5609492016-07-15 04:39:07 +00004567 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004568 return StmtError();
4569
Alexander Musmanf82886e2014-09-18 05:12:34 +00004570 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004571 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4572 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004573}
4574
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004575StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4576 Stmt *AStmt,
4577 SourceLocation StartLoc,
4578 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004579 if (!AStmt)
4580 return StmtError();
4581
4582 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004583 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004584 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004585 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004586 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004587 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004588 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004589 return StmtError();
4590 // All associated statements must be '#pragma omp section' except for
4591 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004592 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004593 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4594 if (SectionStmt)
4595 Diag(SectionStmt->getLocStart(),
4596 diag::err_omp_sections_substmt_not_section);
4597 return StmtError();
4598 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004599 cast<OMPSectionDirective>(SectionStmt)
4600 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004601 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004602 } else {
4603 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4604 return StmtError();
4605 }
4606
4607 getCurFunction()->setHasBranchProtectedScope();
4608
Alexey Bataev25e5b442015-09-15 12:52:43 +00004609 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4610 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004611}
4612
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004613StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4614 SourceLocation StartLoc,
4615 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004616 if (!AStmt)
4617 return StmtError();
4618
4619 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004620
4621 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004622 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004623
Alexey Bataev25e5b442015-09-15 12:52:43 +00004624 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4625 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004626}
4627
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004628StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4629 Stmt *AStmt,
4630 SourceLocation StartLoc,
4631 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004632 if (!AStmt)
4633 return StmtError();
4634
4635 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004636
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004637 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004638
Alexey Bataev3255bf32015-01-19 05:20:46 +00004639 // OpenMP [2.7.3, single Construct, Restrictions]
4640 // The copyprivate clause must not be used with the nowait clause.
4641 OMPClause *Nowait = nullptr;
4642 OMPClause *Copyprivate = nullptr;
4643 for (auto *Clause : Clauses) {
4644 if (Clause->getClauseKind() == OMPC_nowait)
4645 Nowait = Clause;
4646 else if (Clause->getClauseKind() == OMPC_copyprivate)
4647 Copyprivate = Clause;
4648 if (Copyprivate && Nowait) {
4649 Diag(Copyprivate->getLocStart(),
4650 diag::err_omp_single_copyprivate_with_nowait);
4651 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4652 return StmtError();
4653 }
4654 }
4655
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004656 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4657}
4658
Alexander Musman80c22892014-07-17 08:54:58 +00004659StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4660 SourceLocation StartLoc,
4661 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004662 if (!AStmt)
4663 return StmtError();
4664
4665 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004666
4667 getCurFunction()->setHasBranchProtectedScope();
4668
4669 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4670}
4671
Alexey Bataev28c75412015-12-15 08:19:24 +00004672StmtResult Sema::ActOnOpenMPCriticalDirective(
4673 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4674 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004675 if (!AStmt)
4676 return StmtError();
4677
4678 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004679
Alexey Bataev28c75412015-12-15 08:19:24 +00004680 bool ErrorFound = false;
4681 llvm::APSInt Hint;
4682 SourceLocation HintLoc;
4683 bool DependentHint = false;
4684 for (auto *C : Clauses) {
4685 if (C->getClauseKind() == OMPC_hint) {
4686 if (!DirName.getName()) {
4687 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4688 ErrorFound = true;
4689 }
4690 Expr *E = cast<OMPHintClause>(C)->getHint();
4691 if (E->isTypeDependent() || E->isValueDependent() ||
4692 E->isInstantiationDependent())
4693 DependentHint = true;
4694 else {
4695 Hint = E->EvaluateKnownConstInt(Context);
4696 HintLoc = C->getLocStart();
4697 }
4698 }
4699 }
4700 if (ErrorFound)
4701 return StmtError();
4702 auto Pair = DSAStack->getCriticalWithHint(DirName);
4703 if (Pair.first && DirName.getName() && !DependentHint) {
4704 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4705 Diag(StartLoc, diag::err_omp_critical_with_hint);
4706 if (HintLoc.isValid()) {
4707 Diag(HintLoc, diag::note_omp_critical_hint_here)
4708 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4709 } else
4710 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4711 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4712 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4713 << 1
4714 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4715 /*Radix=*/10, /*Signed=*/false);
4716 } else
4717 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4718 }
4719 }
4720
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004721 getCurFunction()->setHasBranchProtectedScope();
4722
Alexey Bataev28c75412015-12-15 08:19:24 +00004723 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4724 Clauses, AStmt);
4725 if (!Pair.first && DirName.getName() && !DependentHint)
4726 DSAStack->addCriticalWithHint(Dir, Hint);
4727 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004728}
4729
Alexey Bataev4acb8592014-07-07 13:01:15 +00004730StmtResult Sema::ActOnOpenMPParallelForDirective(
4731 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4732 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004733 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004734 if (!AStmt)
4735 return StmtError();
4736
Alexey Bataev4acb8592014-07-07 13:01:15 +00004737 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4738 // 1.2.2 OpenMP Language Terminology
4739 // Structured block - An executable statement with a single entry at the
4740 // top and a single exit at the bottom.
4741 // The point of exit cannot be a branch out of the structured block.
4742 // longjmp() and throw() must not violate the entry/exit criteria.
4743 CS->getCapturedDecl()->setNothrow();
4744
Alexander Musmanc6388682014-12-15 07:07:06 +00004745 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004746 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4747 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004748 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004749 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4750 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4751 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004752 if (NestedLoopCount == 0)
4753 return StmtError();
4754
Alexander Musmana5f070a2014-10-01 06:03:56 +00004755 assert((CurContext->isDependentContext() || B.builtAll()) &&
4756 "omp parallel for loop exprs were not built");
4757
Alexey Bataev54acd402015-08-04 11:18:19 +00004758 if (!CurContext->isDependentContext()) {
4759 // Finalize the clauses that need pre-built expressions for CodeGen.
4760 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004761 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004762 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004763 B.NumIterations, *this, CurScope,
4764 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004765 return StmtError();
4766 }
4767 }
4768
Alexey Bataev4acb8592014-07-07 13:01:15 +00004769 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004770 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004771 NestedLoopCount, Clauses, AStmt, B,
4772 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004773}
4774
Alexander Musmane4e893b2014-09-23 09:33:00 +00004775StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4776 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4777 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004778 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004779 if (!AStmt)
4780 return StmtError();
4781
Alexander Musmane4e893b2014-09-23 09:33:00 +00004782 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4783 // 1.2.2 OpenMP Language Terminology
4784 // Structured block - An executable statement with a single entry at the
4785 // top and a single exit at the bottom.
4786 // The point of exit cannot be a branch out of the structured block.
4787 // longjmp() and throw() must not violate the entry/exit criteria.
4788 CS->getCapturedDecl()->setNothrow();
4789
Alexander Musmanc6388682014-12-15 07:07:06 +00004790 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004791 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4792 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004793 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004794 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4795 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4796 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004797 if (NestedLoopCount == 0)
4798 return StmtError();
4799
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004800 if (!CurContext->isDependentContext()) {
4801 // Finalize the clauses that need pre-built expressions for CodeGen.
4802 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004803 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004804 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004805 B.NumIterations, *this, CurScope,
4806 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004807 return StmtError();
4808 }
4809 }
4810
Kelvin Lic5609492016-07-15 04:39:07 +00004811 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004812 return StmtError();
4813
Alexander Musmane4e893b2014-09-23 09:33:00 +00004814 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004815 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004816 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004817}
4818
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004819StmtResult
4820Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4821 Stmt *AStmt, SourceLocation StartLoc,
4822 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004823 if (!AStmt)
4824 return StmtError();
4825
4826 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004827 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004828 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004829 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004830 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004831 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004832 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004833 return StmtError();
4834 // All associated statements must be '#pragma omp section' except for
4835 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004836 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004837 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4838 if (SectionStmt)
4839 Diag(SectionStmt->getLocStart(),
4840 diag::err_omp_parallel_sections_substmt_not_section);
4841 return StmtError();
4842 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004843 cast<OMPSectionDirective>(SectionStmt)
4844 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004845 }
4846 } else {
4847 Diag(AStmt->getLocStart(),
4848 diag::err_omp_parallel_sections_not_compound_stmt);
4849 return StmtError();
4850 }
4851
4852 getCurFunction()->setHasBranchProtectedScope();
4853
Alexey Bataev25e5b442015-09-15 12:52:43 +00004854 return OMPParallelSectionsDirective::Create(
4855 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004856}
4857
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004858StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4859 Stmt *AStmt, SourceLocation StartLoc,
4860 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004861 if (!AStmt)
4862 return StmtError();
4863
David Majnemer9d168222016-08-05 17:44:54 +00004864 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004865 // 1.2.2 OpenMP Language Terminology
4866 // Structured block - An executable statement with a single entry at the
4867 // top and a single exit at the bottom.
4868 // The point of exit cannot be a branch out of the structured block.
4869 // longjmp() and throw() must not violate the entry/exit criteria.
4870 CS->getCapturedDecl()->setNothrow();
4871
4872 getCurFunction()->setHasBranchProtectedScope();
4873
Alexey Bataev25e5b442015-09-15 12:52:43 +00004874 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4875 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004876}
4877
Alexey Bataev68446b72014-07-18 07:47:19 +00004878StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4879 SourceLocation EndLoc) {
4880 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4881}
4882
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004883StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4884 SourceLocation EndLoc) {
4885 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4886}
4887
Alexey Bataev2df347a2014-07-18 10:17:07 +00004888StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4889 SourceLocation EndLoc) {
4890 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4891}
4892
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004893StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4894 SourceLocation StartLoc,
4895 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004896 if (!AStmt)
4897 return StmtError();
4898
4899 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004900
4901 getCurFunction()->setHasBranchProtectedScope();
4902
4903 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4904}
4905
Alexey Bataev6125da92014-07-21 11:26:11 +00004906StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4907 SourceLocation StartLoc,
4908 SourceLocation EndLoc) {
4909 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4910 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4911}
4912
Alexey Bataev346265e2015-09-25 10:37:12 +00004913StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4914 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004915 SourceLocation StartLoc,
4916 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004917 OMPClause *DependFound = nullptr;
4918 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004919 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004920 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004921 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004922 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004923 for (auto *C : Clauses) {
4924 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4925 DependFound = C;
4926 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4927 if (DependSourceClause) {
4928 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4929 << getOpenMPDirectiveName(OMPD_ordered)
4930 << getOpenMPClauseName(OMPC_depend) << 2;
4931 ErrorFound = true;
4932 } else
4933 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004934 if (DependSinkClause) {
4935 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4936 << 0;
4937 ErrorFound = true;
4938 }
4939 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4940 if (DependSourceClause) {
4941 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4942 << 1;
4943 ErrorFound = true;
4944 }
4945 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004946 }
4947 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004948 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004949 else if (C->getClauseKind() == OMPC_simd)
4950 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004951 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004952 if (!ErrorFound && !SC &&
4953 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004954 // OpenMP [2.8.1,simd Construct, Restrictions]
4955 // An ordered construct with the simd clause is the only OpenMP construct
4956 // that can appear in the simd region.
4957 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004958 ErrorFound = true;
4959 } else if (DependFound && (TC || SC)) {
4960 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4961 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4962 ErrorFound = true;
4963 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4964 Diag(DependFound->getLocStart(),
4965 diag::err_omp_ordered_directive_without_param);
4966 ErrorFound = true;
4967 } else if (TC || Clauses.empty()) {
4968 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4969 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4970 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4971 << (TC != nullptr);
4972 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4973 ErrorFound = true;
4974 }
4975 }
4976 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004977 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004978
4979 if (AStmt) {
4980 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4981
4982 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004983 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004984
4985 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004986}
4987
Alexey Bataev1d160b12015-03-13 12:27:31 +00004988namespace {
4989/// \brief Helper class for checking expression in 'omp atomic [update]'
4990/// construct.
4991class OpenMPAtomicUpdateChecker {
4992 /// \brief Error results for atomic update expressions.
4993 enum ExprAnalysisErrorCode {
4994 /// \brief A statement is not an expression statement.
4995 NotAnExpression,
4996 /// \brief Expression is not builtin binary or unary operation.
4997 NotABinaryOrUnaryExpression,
4998 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4999 NotAnUnaryIncDecExpression,
5000 /// \brief An expression is not of scalar type.
5001 NotAScalarType,
5002 /// \brief A binary operation is not an assignment operation.
5003 NotAnAssignmentOp,
5004 /// \brief RHS part of the binary operation is not a binary expression.
5005 NotABinaryExpression,
5006 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5007 /// expression.
5008 NotABinaryOperator,
5009 /// \brief RHS binary operation does not have reference to the updated LHS
5010 /// part.
5011 NotAnUpdateExpression,
5012 /// \brief No errors is found.
5013 NoError
5014 };
5015 /// \brief Reference to Sema.
5016 Sema &SemaRef;
5017 /// \brief A location for note diagnostics (when error is found).
5018 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005019 /// \brief 'x' lvalue part of the source atomic expression.
5020 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005021 /// \brief 'expr' rvalue part of the source atomic expression.
5022 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005023 /// \brief Helper expression of the form
5024 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5025 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5026 Expr *UpdateExpr;
5027 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5028 /// important for non-associative operations.
5029 bool IsXLHSInRHSPart;
5030 BinaryOperatorKind Op;
5031 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005032 /// \brief true if the source expression is a postfix unary operation, false
5033 /// if it is a prefix unary operation.
5034 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005035
5036public:
5037 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005038 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005039 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005040 /// \brief Check specified statement that it is suitable for 'atomic update'
5041 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005042 /// expression. If DiagId and NoteId == 0, then only check is performed
5043 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005044 /// \param DiagId Diagnostic which should be emitted if error is found.
5045 /// \param NoteId Diagnostic note for the main error message.
5046 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005047 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005048 /// \brief Return the 'x' lvalue part of the source atomic expression.
5049 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005050 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5051 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005052 /// \brief Return the update expression used in calculation of the updated
5053 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5054 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5055 Expr *getUpdateExpr() const { return UpdateExpr; }
5056 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5057 /// false otherwise.
5058 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5059
Alexey Bataevb78ca832015-04-01 03:33:17 +00005060 /// \brief true if the source expression is a postfix unary operation, false
5061 /// if it is a prefix unary operation.
5062 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5063
Alexey Bataev1d160b12015-03-13 12:27:31 +00005064private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005065 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5066 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005067};
5068} // namespace
5069
5070bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5071 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5072 ExprAnalysisErrorCode ErrorFound = NoError;
5073 SourceLocation ErrorLoc, NoteLoc;
5074 SourceRange ErrorRange, NoteRange;
5075 // Allowed constructs are:
5076 // x = x binop expr;
5077 // x = expr binop x;
5078 if (AtomicBinOp->getOpcode() == BO_Assign) {
5079 X = AtomicBinOp->getLHS();
5080 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5081 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5082 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5083 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5084 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005085 Op = AtomicInnerBinOp->getOpcode();
5086 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005087 auto *LHS = AtomicInnerBinOp->getLHS();
5088 auto *RHS = AtomicInnerBinOp->getRHS();
5089 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5090 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5091 /*Canonical=*/true);
5092 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5093 /*Canonical=*/true);
5094 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5095 /*Canonical=*/true);
5096 if (XId == LHSId) {
5097 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005098 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005099 } else if (XId == RHSId) {
5100 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005101 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005102 } else {
5103 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5104 ErrorRange = AtomicInnerBinOp->getSourceRange();
5105 NoteLoc = X->getExprLoc();
5106 NoteRange = X->getSourceRange();
5107 ErrorFound = NotAnUpdateExpression;
5108 }
5109 } else {
5110 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5111 ErrorRange = AtomicInnerBinOp->getSourceRange();
5112 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5113 NoteRange = SourceRange(NoteLoc, NoteLoc);
5114 ErrorFound = NotABinaryOperator;
5115 }
5116 } else {
5117 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5118 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5119 ErrorFound = NotABinaryExpression;
5120 }
5121 } else {
5122 ErrorLoc = AtomicBinOp->getExprLoc();
5123 ErrorRange = AtomicBinOp->getSourceRange();
5124 NoteLoc = AtomicBinOp->getOperatorLoc();
5125 NoteRange = SourceRange(NoteLoc, NoteLoc);
5126 ErrorFound = NotAnAssignmentOp;
5127 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005128 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005129 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5130 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5131 return true;
5132 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005133 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005134 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005135}
5136
5137bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5138 unsigned NoteId) {
5139 ExprAnalysisErrorCode ErrorFound = NoError;
5140 SourceLocation ErrorLoc, NoteLoc;
5141 SourceRange ErrorRange, NoteRange;
5142 // Allowed constructs are:
5143 // x++;
5144 // x--;
5145 // ++x;
5146 // --x;
5147 // x binop= expr;
5148 // x = x binop expr;
5149 // x = expr binop x;
5150 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5151 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5152 if (AtomicBody->getType()->isScalarType() ||
5153 AtomicBody->isInstantiationDependent()) {
5154 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5155 AtomicBody->IgnoreParenImpCasts())) {
5156 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005157 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005158 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005159 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005160 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005161 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005162 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005163 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5164 AtomicBody->IgnoreParenImpCasts())) {
5165 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005166 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005167 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005168 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5169 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005170 // Check for Unary Operation
5171 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005172 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005173 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5174 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005175 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005176 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5177 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005178 } else {
5179 ErrorFound = NotAnUnaryIncDecExpression;
5180 ErrorLoc = AtomicUnaryOp->getExprLoc();
5181 ErrorRange = AtomicUnaryOp->getSourceRange();
5182 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5183 NoteRange = SourceRange(NoteLoc, NoteLoc);
5184 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005185 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005186 ErrorFound = NotABinaryOrUnaryExpression;
5187 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5188 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5189 }
5190 } else {
5191 ErrorFound = NotAScalarType;
5192 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5193 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5194 }
5195 } else {
5196 ErrorFound = NotAnExpression;
5197 NoteLoc = ErrorLoc = S->getLocStart();
5198 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5199 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005200 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005201 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5202 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5203 return true;
5204 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005205 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005206 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005207 // Build an update expression of form 'OpaqueValueExpr(x) binop
5208 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5209 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5210 auto *OVEX = new (SemaRef.getASTContext())
5211 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5212 auto *OVEExpr = new (SemaRef.getASTContext())
5213 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5214 auto Update =
5215 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5216 IsXLHSInRHSPart ? OVEExpr : OVEX);
5217 if (Update.isInvalid())
5218 return true;
5219 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5220 Sema::AA_Casting);
5221 if (Update.isInvalid())
5222 return true;
5223 UpdateExpr = Update.get();
5224 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005225 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005226}
5227
Alexey Bataev0162e452014-07-22 10:10:35 +00005228StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5229 Stmt *AStmt,
5230 SourceLocation StartLoc,
5231 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005232 if (!AStmt)
5233 return StmtError();
5234
David Majnemer9d168222016-08-05 17:44:54 +00005235 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005236 // 1.2.2 OpenMP Language Terminology
5237 // Structured block - An executable statement with a single entry at the
5238 // top and a single exit at the bottom.
5239 // The point of exit cannot be a branch out of the structured block.
5240 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005241 OpenMPClauseKind AtomicKind = OMPC_unknown;
5242 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005243 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005244 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005245 C->getClauseKind() == OMPC_update ||
5246 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005247 if (AtomicKind != OMPC_unknown) {
5248 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5249 << SourceRange(C->getLocStart(), C->getLocEnd());
5250 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5251 << getOpenMPClauseName(AtomicKind);
5252 } else {
5253 AtomicKind = C->getClauseKind();
5254 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005255 }
5256 }
5257 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005258
Alexey Bataev459dec02014-07-24 06:46:57 +00005259 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005260 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5261 Body = EWC->getSubExpr();
5262
Alexey Bataev62cec442014-11-18 10:14:22 +00005263 Expr *X = nullptr;
5264 Expr *V = nullptr;
5265 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005266 Expr *UE = nullptr;
5267 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005268 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005269 // OpenMP [2.12.6, atomic Construct]
5270 // In the next expressions:
5271 // * x and v (as applicable) are both l-value expressions with scalar type.
5272 // * During the execution of an atomic region, multiple syntactic
5273 // occurrences of x must designate the same storage location.
5274 // * Neither of v and expr (as applicable) may access the storage location
5275 // designated by x.
5276 // * Neither of x and expr (as applicable) may access the storage location
5277 // designated by v.
5278 // * expr is an expression with scalar type.
5279 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5280 // * binop, binop=, ++, and -- are not overloaded operators.
5281 // * The expression x binop expr must be numerically equivalent to x binop
5282 // (expr). This requirement is satisfied if the operators in expr have
5283 // precedence greater than binop, or by using parentheses around expr or
5284 // subexpressions of expr.
5285 // * The expression expr binop x must be numerically equivalent to (expr)
5286 // binop x. This requirement is satisfied if the operators in expr have
5287 // precedence equal to or greater than binop, or by using parentheses around
5288 // expr or subexpressions of expr.
5289 // * For forms that allow multiple occurrences of x, the number of times
5290 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005291 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005292 enum {
5293 NotAnExpression,
5294 NotAnAssignmentOp,
5295 NotAScalarType,
5296 NotAnLValue,
5297 NoError
5298 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005299 SourceLocation ErrorLoc, NoteLoc;
5300 SourceRange ErrorRange, NoteRange;
5301 // If clause is read:
5302 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005303 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5304 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005305 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5306 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5307 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5308 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5309 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5310 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5311 if (!X->isLValue() || !V->isLValue()) {
5312 auto NotLValueExpr = X->isLValue() ? V : X;
5313 ErrorFound = NotAnLValue;
5314 ErrorLoc = AtomicBinOp->getExprLoc();
5315 ErrorRange = AtomicBinOp->getSourceRange();
5316 NoteLoc = NotLValueExpr->getExprLoc();
5317 NoteRange = NotLValueExpr->getSourceRange();
5318 }
5319 } else if (!X->isInstantiationDependent() ||
5320 !V->isInstantiationDependent()) {
5321 auto NotScalarExpr =
5322 (X->isInstantiationDependent() || X->getType()->isScalarType())
5323 ? V
5324 : X;
5325 ErrorFound = NotAScalarType;
5326 ErrorLoc = AtomicBinOp->getExprLoc();
5327 ErrorRange = AtomicBinOp->getSourceRange();
5328 NoteLoc = NotScalarExpr->getExprLoc();
5329 NoteRange = NotScalarExpr->getSourceRange();
5330 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005331 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005332 ErrorFound = NotAnAssignmentOp;
5333 ErrorLoc = AtomicBody->getExprLoc();
5334 ErrorRange = AtomicBody->getSourceRange();
5335 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5336 : AtomicBody->getExprLoc();
5337 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5338 : AtomicBody->getSourceRange();
5339 }
5340 } else {
5341 ErrorFound = NotAnExpression;
5342 NoteLoc = ErrorLoc = Body->getLocStart();
5343 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005344 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005345 if (ErrorFound != NoError) {
5346 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5347 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005348 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5349 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005350 return StmtError();
5351 } else if (CurContext->isDependentContext())
5352 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005353 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005354 enum {
5355 NotAnExpression,
5356 NotAnAssignmentOp,
5357 NotAScalarType,
5358 NotAnLValue,
5359 NoError
5360 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005361 SourceLocation ErrorLoc, NoteLoc;
5362 SourceRange ErrorRange, NoteRange;
5363 // If clause is write:
5364 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005365 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5366 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005367 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5368 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005369 X = AtomicBinOp->getLHS();
5370 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005371 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5372 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5373 if (!X->isLValue()) {
5374 ErrorFound = NotAnLValue;
5375 ErrorLoc = AtomicBinOp->getExprLoc();
5376 ErrorRange = AtomicBinOp->getSourceRange();
5377 NoteLoc = X->getExprLoc();
5378 NoteRange = X->getSourceRange();
5379 }
5380 } else if (!X->isInstantiationDependent() ||
5381 !E->isInstantiationDependent()) {
5382 auto NotScalarExpr =
5383 (X->isInstantiationDependent() || X->getType()->isScalarType())
5384 ? E
5385 : X;
5386 ErrorFound = NotAScalarType;
5387 ErrorLoc = AtomicBinOp->getExprLoc();
5388 ErrorRange = AtomicBinOp->getSourceRange();
5389 NoteLoc = NotScalarExpr->getExprLoc();
5390 NoteRange = NotScalarExpr->getSourceRange();
5391 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005392 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005393 ErrorFound = NotAnAssignmentOp;
5394 ErrorLoc = AtomicBody->getExprLoc();
5395 ErrorRange = AtomicBody->getSourceRange();
5396 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5397 : AtomicBody->getExprLoc();
5398 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5399 : AtomicBody->getSourceRange();
5400 }
5401 } else {
5402 ErrorFound = NotAnExpression;
5403 NoteLoc = ErrorLoc = Body->getLocStart();
5404 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005405 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005406 if (ErrorFound != NoError) {
5407 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5408 << ErrorRange;
5409 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5410 << NoteRange;
5411 return StmtError();
5412 } else if (CurContext->isDependentContext())
5413 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005414 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005415 // If clause is update:
5416 // x++;
5417 // x--;
5418 // ++x;
5419 // --x;
5420 // x binop= expr;
5421 // x = x binop expr;
5422 // x = expr binop x;
5423 OpenMPAtomicUpdateChecker Checker(*this);
5424 if (Checker.checkStatement(
5425 Body, (AtomicKind == OMPC_update)
5426 ? diag::err_omp_atomic_update_not_expression_statement
5427 : diag::err_omp_atomic_not_expression_statement,
5428 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005429 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005430 if (!CurContext->isDependentContext()) {
5431 E = Checker.getExpr();
5432 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005433 UE = Checker.getUpdateExpr();
5434 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005435 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005436 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005437 enum {
5438 NotAnAssignmentOp,
5439 NotACompoundStatement,
5440 NotTwoSubstatements,
5441 NotASpecificExpression,
5442 NoError
5443 } ErrorFound = NoError;
5444 SourceLocation ErrorLoc, NoteLoc;
5445 SourceRange ErrorRange, NoteRange;
5446 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5447 // If clause is a capture:
5448 // v = x++;
5449 // v = x--;
5450 // v = ++x;
5451 // v = --x;
5452 // v = x binop= expr;
5453 // v = x = x binop expr;
5454 // v = x = expr binop x;
5455 auto *AtomicBinOp =
5456 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5457 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5458 V = AtomicBinOp->getLHS();
5459 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5460 OpenMPAtomicUpdateChecker Checker(*this);
5461 if (Checker.checkStatement(
5462 Body, diag::err_omp_atomic_capture_not_expression_statement,
5463 diag::note_omp_atomic_update))
5464 return StmtError();
5465 E = Checker.getExpr();
5466 X = Checker.getX();
5467 UE = Checker.getUpdateExpr();
5468 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5469 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005470 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005471 ErrorLoc = AtomicBody->getExprLoc();
5472 ErrorRange = AtomicBody->getSourceRange();
5473 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5474 : AtomicBody->getExprLoc();
5475 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5476 : AtomicBody->getSourceRange();
5477 ErrorFound = NotAnAssignmentOp;
5478 }
5479 if (ErrorFound != NoError) {
5480 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5481 << ErrorRange;
5482 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5483 return StmtError();
5484 } else if (CurContext->isDependentContext()) {
5485 UE = V = E = X = nullptr;
5486 }
5487 } else {
5488 // If clause is a capture:
5489 // { v = x; x = expr; }
5490 // { v = x; x++; }
5491 // { v = x; x--; }
5492 // { v = x; ++x; }
5493 // { v = x; --x; }
5494 // { v = x; x binop= expr; }
5495 // { v = x; x = x binop expr; }
5496 // { v = x; x = expr binop x; }
5497 // { x++; v = x; }
5498 // { x--; v = x; }
5499 // { ++x; v = x; }
5500 // { --x; v = x; }
5501 // { x binop= expr; v = x; }
5502 // { x = x binop expr; v = x; }
5503 // { x = expr binop x; v = x; }
5504 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5505 // Check that this is { expr1; expr2; }
5506 if (CS->size() == 2) {
5507 auto *First = CS->body_front();
5508 auto *Second = CS->body_back();
5509 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5510 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5511 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5512 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5513 // Need to find what subexpression is 'v' and what is 'x'.
5514 OpenMPAtomicUpdateChecker Checker(*this);
5515 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5516 BinaryOperator *BinOp = nullptr;
5517 if (IsUpdateExprFound) {
5518 BinOp = dyn_cast<BinaryOperator>(First);
5519 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5520 }
5521 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5522 // { v = x; x++; }
5523 // { v = x; x--; }
5524 // { v = x; ++x; }
5525 // { v = x; --x; }
5526 // { v = x; x binop= expr; }
5527 // { v = x; x = x binop expr; }
5528 // { v = x; x = expr binop x; }
5529 // Check that the first expression has form v = x.
5530 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5531 llvm::FoldingSetNodeID XId, PossibleXId;
5532 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5533 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5534 IsUpdateExprFound = XId == PossibleXId;
5535 if (IsUpdateExprFound) {
5536 V = BinOp->getLHS();
5537 X = Checker.getX();
5538 E = Checker.getExpr();
5539 UE = Checker.getUpdateExpr();
5540 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005541 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005542 }
5543 }
5544 if (!IsUpdateExprFound) {
5545 IsUpdateExprFound = !Checker.checkStatement(First);
5546 BinOp = nullptr;
5547 if (IsUpdateExprFound) {
5548 BinOp = dyn_cast<BinaryOperator>(Second);
5549 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5550 }
5551 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5552 // { x++; v = x; }
5553 // { x--; v = x; }
5554 // { ++x; v = x; }
5555 // { --x; v = x; }
5556 // { x binop= expr; v = x; }
5557 // { x = x binop expr; v = x; }
5558 // { x = expr binop x; v = x; }
5559 // Check that the second expression has form v = x.
5560 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5561 llvm::FoldingSetNodeID XId, PossibleXId;
5562 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5563 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5564 IsUpdateExprFound = XId == PossibleXId;
5565 if (IsUpdateExprFound) {
5566 V = BinOp->getLHS();
5567 X = Checker.getX();
5568 E = Checker.getExpr();
5569 UE = Checker.getUpdateExpr();
5570 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005571 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005572 }
5573 }
5574 }
5575 if (!IsUpdateExprFound) {
5576 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005577 auto *FirstExpr = dyn_cast<Expr>(First);
5578 auto *SecondExpr = dyn_cast<Expr>(Second);
5579 if (!FirstExpr || !SecondExpr ||
5580 !(FirstExpr->isInstantiationDependent() ||
5581 SecondExpr->isInstantiationDependent())) {
5582 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5583 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005584 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005585 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5586 : First->getLocStart();
5587 NoteRange = ErrorRange = FirstBinOp
5588 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005589 : SourceRange(ErrorLoc, ErrorLoc);
5590 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005591 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5592 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5593 ErrorFound = NotAnAssignmentOp;
5594 NoteLoc = ErrorLoc = SecondBinOp
5595 ? SecondBinOp->getOperatorLoc()
5596 : Second->getLocStart();
5597 NoteRange = ErrorRange =
5598 SecondBinOp ? SecondBinOp->getSourceRange()
5599 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005600 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005601 auto *PossibleXRHSInFirst =
5602 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5603 auto *PossibleXLHSInSecond =
5604 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5605 llvm::FoldingSetNodeID X1Id, X2Id;
5606 PossibleXRHSInFirst->Profile(X1Id, Context,
5607 /*Canonical=*/true);
5608 PossibleXLHSInSecond->Profile(X2Id, Context,
5609 /*Canonical=*/true);
5610 IsUpdateExprFound = X1Id == X2Id;
5611 if (IsUpdateExprFound) {
5612 V = FirstBinOp->getLHS();
5613 X = SecondBinOp->getLHS();
5614 E = SecondBinOp->getRHS();
5615 UE = nullptr;
5616 IsXLHSInRHSPart = false;
5617 IsPostfixUpdate = true;
5618 } else {
5619 ErrorFound = NotASpecificExpression;
5620 ErrorLoc = FirstBinOp->getExprLoc();
5621 ErrorRange = FirstBinOp->getSourceRange();
5622 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5623 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5624 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005625 }
5626 }
5627 }
5628 }
5629 } else {
5630 NoteLoc = ErrorLoc = Body->getLocStart();
5631 NoteRange = ErrorRange =
5632 SourceRange(Body->getLocStart(), Body->getLocStart());
5633 ErrorFound = NotTwoSubstatements;
5634 }
5635 } else {
5636 NoteLoc = ErrorLoc = Body->getLocStart();
5637 NoteRange = ErrorRange =
5638 SourceRange(Body->getLocStart(), Body->getLocStart());
5639 ErrorFound = NotACompoundStatement;
5640 }
5641 if (ErrorFound != NoError) {
5642 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5643 << ErrorRange;
5644 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5645 return StmtError();
5646 } else if (CurContext->isDependentContext()) {
5647 UE = V = E = X = nullptr;
5648 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005649 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005650 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005651
5652 getCurFunction()->setHasBranchProtectedScope();
5653
Alexey Bataev62cec442014-11-18 10:14:22 +00005654 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005655 X, V, E, UE, IsXLHSInRHSPart,
5656 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005657}
5658
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005659StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5660 Stmt *AStmt,
5661 SourceLocation StartLoc,
5662 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005663 if (!AStmt)
5664 return StmtError();
5665
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005666 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5667 // 1.2.2 OpenMP Language Terminology
5668 // Structured block - An executable statement with a single entry at the
5669 // top and a single exit at the bottom.
5670 // The point of exit cannot be a branch out of the structured block.
5671 // longjmp() and throw() must not violate the entry/exit criteria.
5672 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005673
Alexey Bataev13314bf2014-10-09 04:18:56 +00005674 // OpenMP [2.16, Nesting of Regions]
5675 // If specified, a teams construct must be contained within a target
5676 // construct. That target construct must contain no statements or directives
5677 // outside of the teams construct.
5678 if (DSAStack->hasInnerTeamsRegion()) {
5679 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5680 bool OMPTeamsFound = true;
5681 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5682 auto I = CS->body_begin();
5683 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005684 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005685 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5686 OMPTeamsFound = false;
5687 break;
5688 }
5689 ++I;
5690 }
5691 assert(I != CS->body_end() && "Not found statement");
5692 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005693 } else {
5694 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5695 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005696 }
5697 if (!OMPTeamsFound) {
5698 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5699 Diag(DSAStack->getInnerTeamsRegionLoc(),
5700 diag::note_omp_nested_teams_construct_here);
5701 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5702 << isa<OMPExecutableDirective>(S);
5703 return StmtError();
5704 }
5705 }
5706
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005707 getCurFunction()->setHasBranchProtectedScope();
5708
5709 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5710}
5711
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005712StmtResult
5713Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5714 Stmt *AStmt, SourceLocation StartLoc,
5715 SourceLocation EndLoc) {
5716 if (!AStmt)
5717 return StmtError();
5718
5719 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5720 // 1.2.2 OpenMP Language Terminology
5721 // Structured block - An executable statement with a single entry at the
5722 // top and a single exit at the bottom.
5723 // The point of exit cannot be a branch out of the structured block.
5724 // longjmp() and throw() must not violate the entry/exit criteria.
5725 CS->getCapturedDecl()->setNothrow();
5726
5727 getCurFunction()->setHasBranchProtectedScope();
5728
5729 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5730 AStmt);
5731}
5732
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005733StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5734 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5735 SourceLocation EndLoc,
5736 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5737 if (!AStmt)
5738 return StmtError();
5739
5740 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5741 // 1.2.2 OpenMP Language Terminology
5742 // Structured block - An executable statement with a single entry at the
5743 // top and a single exit at the bottom.
5744 // The point of exit cannot be a branch out of the structured block.
5745 // longjmp() and throw() must not violate the entry/exit criteria.
5746 CS->getCapturedDecl()->setNothrow();
5747
5748 OMPLoopDirective::HelperExprs B;
5749 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5750 // define the nested loops number.
5751 unsigned NestedLoopCount =
5752 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5753 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5754 VarsWithImplicitDSA, B);
5755 if (NestedLoopCount == 0)
5756 return StmtError();
5757
5758 assert((CurContext->isDependentContext() || B.builtAll()) &&
5759 "omp target parallel for loop exprs were not built");
5760
5761 if (!CurContext->isDependentContext()) {
5762 // Finalize the clauses that need pre-built expressions for CodeGen.
5763 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005764 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005765 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005766 B.NumIterations, *this, CurScope,
5767 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005768 return StmtError();
5769 }
5770 }
5771
5772 getCurFunction()->setHasBranchProtectedScope();
5773 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5774 NestedLoopCount, Clauses, AStmt,
5775 B, DSAStack->isCancelRegion());
5776}
5777
Samuel Antaodf67fc42016-01-19 19:15:56 +00005778/// \brief Check for existence of a map clause in the list of clauses.
5779static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5780 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5781 I != E; ++I) {
5782 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5783 return true;
5784 }
5785 }
5786
5787 return false;
5788}
5789
Michael Wong65f367f2015-07-21 13:44:28 +00005790StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5791 Stmt *AStmt,
5792 SourceLocation StartLoc,
5793 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005794 if (!AStmt)
5795 return StmtError();
5796
5797 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5798
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005799 // OpenMP [2.10.1, Restrictions, p. 97]
5800 // At least one map clause must appear on the directive.
5801 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005802 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5803 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005804 return StmtError();
5805 }
5806
Michael Wong65f367f2015-07-21 13:44:28 +00005807 getCurFunction()->setHasBranchProtectedScope();
5808
5809 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5810 AStmt);
5811}
5812
Samuel Antaodf67fc42016-01-19 19:15:56 +00005813StmtResult
5814Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5815 SourceLocation StartLoc,
5816 SourceLocation EndLoc) {
5817 // OpenMP [2.10.2, Restrictions, p. 99]
5818 // At least one map clause must appear on the directive.
5819 if (!HasMapClause(Clauses)) {
5820 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5821 << getOpenMPDirectiveName(OMPD_target_enter_data);
5822 return StmtError();
5823 }
5824
5825 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5826 Clauses);
5827}
5828
Samuel Antao72590762016-01-19 20:04:50 +00005829StmtResult
5830Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5831 SourceLocation StartLoc,
5832 SourceLocation EndLoc) {
5833 // OpenMP [2.10.3, Restrictions, p. 102]
5834 // At least one map clause must appear on the directive.
5835 if (!HasMapClause(Clauses)) {
5836 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5837 << getOpenMPDirectiveName(OMPD_target_exit_data);
5838 return StmtError();
5839 }
5840
5841 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5842}
5843
Samuel Antao686c70c2016-05-26 17:30:50 +00005844StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5845 SourceLocation StartLoc,
5846 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005847 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005848 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005849 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005850 seenMotionClause = true;
5851 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005852 if (!seenMotionClause) {
5853 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5854 return StmtError();
5855 }
5856 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5857}
5858
Alexey Bataev13314bf2014-10-09 04:18:56 +00005859StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5860 Stmt *AStmt, SourceLocation StartLoc,
5861 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005862 if (!AStmt)
5863 return StmtError();
5864
Alexey Bataev13314bf2014-10-09 04:18:56 +00005865 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5866 // 1.2.2 OpenMP Language Terminology
5867 // Structured block - An executable statement with a single entry at the
5868 // top and a single exit at the bottom.
5869 // The point of exit cannot be a branch out of the structured block.
5870 // longjmp() and throw() must not violate the entry/exit criteria.
5871 CS->getCapturedDecl()->setNothrow();
5872
5873 getCurFunction()->setHasBranchProtectedScope();
5874
5875 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5876}
5877
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005878StmtResult
5879Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5880 SourceLocation EndLoc,
5881 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005882 if (DSAStack->isParentNowaitRegion()) {
5883 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5884 return StmtError();
5885 }
5886 if (DSAStack->isParentOrderedRegion()) {
5887 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5888 return StmtError();
5889 }
5890 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5891 CancelRegion);
5892}
5893
Alexey Bataev87933c72015-09-18 08:07:34 +00005894StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5895 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005896 SourceLocation EndLoc,
5897 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00005898 if (DSAStack->isParentNowaitRegion()) {
5899 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5900 return StmtError();
5901 }
5902 if (DSAStack->isParentOrderedRegion()) {
5903 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5904 return StmtError();
5905 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005906 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005907 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5908 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005909}
5910
Alexey Bataev382967a2015-12-08 12:06:20 +00005911static bool checkGrainsizeNumTasksClauses(Sema &S,
5912 ArrayRef<OMPClause *> Clauses) {
5913 OMPClause *PrevClause = nullptr;
5914 bool ErrorFound = false;
5915 for (auto *C : Clauses) {
5916 if (C->getClauseKind() == OMPC_grainsize ||
5917 C->getClauseKind() == OMPC_num_tasks) {
5918 if (!PrevClause)
5919 PrevClause = C;
5920 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5921 S.Diag(C->getLocStart(),
5922 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5923 << getOpenMPClauseName(C->getClauseKind())
5924 << getOpenMPClauseName(PrevClause->getClauseKind());
5925 S.Diag(PrevClause->getLocStart(),
5926 diag::note_omp_previous_grainsize_num_tasks)
5927 << getOpenMPClauseName(PrevClause->getClauseKind());
5928 ErrorFound = true;
5929 }
5930 }
5931 }
5932 return ErrorFound;
5933}
5934
Alexey Bataev49f6e782015-12-01 04:18:41 +00005935StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5936 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5937 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005938 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005939 if (!AStmt)
5940 return StmtError();
5941
5942 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5943 OMPLoopDirective::HelperExprs B;
5944 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5945 // define the nested loops number.
5946 unsigned NestedLoopCount =
5947 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005948 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005949 VarsWithImplicitDSA, B);
5950 if (NestedLoopCount == 0)
5951 return StmtError();
5952
5953 assert((CurContext->isDependentContext() || B.builtAll()) &&
5954 "omp for loop exprs were not built");
5955
Alexey Bataev382967a2015-12-08 12:06:20 +00005956 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5957 // The grainsize clause and num_tasks clause are mutually exclusive and may
5958 // not appear on the same taskloop directive.
5959 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5960 return StmtError();
5961
Alexey Bataev49f6e782015-12-01 04:18:41 +00005962 getCurFunction()->setHasBranchProtectedScope();
5963 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5964 NestedLoopCount, Clauses, AStmt, B);
5965}
5966
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005967StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5968 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5969 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005970 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005971 if (!AStmt)
5972 return StmtError();
5973
5974 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5975 OMPLoopDirective::HelperExprs B;
5976 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5977 // define the nested loops number.
5978 unsigned NestedLoopCount =
5979 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5980 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5981 VarsWithImplicitDSA, B);
5982 if (NestedLoopCount == 0)
5983 return StmtError();
5984
5985 assert((CurContext->isDependentContext() || B.builtAll()) &&
5986 "omp for loop exprs were not built");
5987
Alexey Bataev5a3af132016-03-29 08:58:54 +00005988 if (!CurContext->isDependentContext()) {
5989 // Finalize the clauses that need pre-built expressions for CodeGen.
5990 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005991 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005992 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005993 B.NumIterations, *this, CurScope,
5994 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005995 return StmtError();
5996 }
5997 }
5998
Alexey Bataev382967a2015-12-08 12:06:20 +00005999 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6000 // The grainsize clause and num_tasks clause are mutually exclusive and may
6001 // not appear on the same taskloop directive.
6002 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6003 return StmtError();
6004
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006005 getCurFunction()->setHasBranchProtectedScope();
6006 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6007 NestedLoopCount, Clauses, AStmt, B);
6008}
6009
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006010StmtResult Sema::ActOnOpenMPDistributeDirective(
6011 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6012 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006013 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006014 if (!AStmt)
6015 return StmtError();
6016
6017 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6018 OMPLoopDirective::HelperExprs B;
6019 // In presence of clause 'collapse' with number of loops, it will
6020 // define the nested loops number.
6021 unsigned NestedLoopCount =
6022 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6023 nullptr /*ordered not a clause on distribute*/, AStmt,
6024 *this, *DSAStack, VarsWithImplicitDSA, B);
6025 if (NestedLoopCount == 0)
6026 return StmtError();
6027
6028 assert((CurContext->isDependentContext() || B.builtAll()) &&
6029 "omp for loop exprs were not built");
6030
6031 getCurFunction()->setHasBranchProtectedScope();
6032 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6033 NestedLoopCount, Clauses, AStmt, B);
6034}
6035
Carlo Bertolli9925f152016-06-27 14:55:37 +00006036StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6037 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6038 SourceLocation EndLoc,
6039 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6040 if (!AStmt)
6041 return StmtError();
6042
6043 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6044 // 1.2.2 OpenMP Language Terminology
6045 // Structured block - An executable statement with a single entry at the
6046 // top and a single exit at the bottom.
6047 // The point of exit cannot be a branch out of the structured block.
6048 // longjmp() and throw() must not violate the entry/exit criteria.
6049 CS->getCapturedDecl()->setNothrow();
6050
6051 OMPLoopDirective::HelperExprs B;
6052 // In presence of clause 'collapse' with number of loops, it will
6053 // define the nested loops number.
6054 unsigned NestedLoopCount = CheckOpenMPLoop(
6055 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6056 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6057 VarsWithImplicitDSA, B);
6058 if (NestedLoopCount == 0)
6059 return StmtError();
6060
6061 assert((CurContext->isDependentContext() || B.builtAll()) &&
6062 "omp for loop exprs were not built");
6063
6064 getCurFunction()->setHasBranchProtectedScope();
6065 return OMPDistributeParallelForDirective::Create(
6066 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6067}
6068
Kelvin Li4a39add2016-07-05 05:00:15 +00006069StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6071 SourceLocation EndLoc,
6072 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6073 if (!AStmt)
6074 return StmtError();
6075
6076 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6077 // 1.2.2 OpenMP Language Terminology
6078 // Structured block - An executable statement with a single entry at the
6079 // top and a single exit at the bottom.
6080 // The point of exit cannot be a branch out of the structured block.
6081 // longjmp() and throw() must not violate the entry/exit criteria.
6082 CS->getCapturedDecl()->setNothrow();
6083
6084 OMPLoopDirective::HelperExprs B;
6085 // In presence of clause 'collapse' with number of loops, it will
6086 // define the nested loops number.
6087 unsigned NestedLoopCount = CheckOpenMPLoop(
6088 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6089 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6090 VarsWithImplicitDSA, B);
6091 if (NestedLoopCount == 0)
6092 return StmtError();
6093
6094 assert((CurContext->isDependentContext() || B.builtAll()) &&
6095 "omp for loop exprs were not built");
6096
Kelvin Lic5609492016-07-15 04:39:07 +00006097 if (checkSimdlenSafelenSpecified(*this, Clauses))
6098 return StmtError();
6099
Kelvin Li4a39add2016-07-05 05:00:15 +00006100 getCurFunction()->setHasBranchProtectedScope();
6101 return OMPDistributeParallelForSimdDirective::Create(
6102 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6103}
6104
Kelvin Li787f3fc2016-07-06 04:45:38 +00006105StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6106 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6107 SourceLocation EndLoc,
6108 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6109 if (!AStmt)
6110 return StmtError();
6111
6112 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6113 // 1.2.2 OpenMP Language Terminology
6114 // Structured block - An executable statement with a single entry at the
6115 // top and a single exit at the bottom.
6116 // The point of exit cannot be a branch out of the structured block.
6117 // longjmp() and throw() must not violate the entry/exit criteria.
6118 CS->getCapturedDecl()->setNothrow();
6119
6120 OMPLoopDirective::HelperExprs B;
6121 // In presence of clause 'collapse' with number of loops, it will
6122 // define the nested loops number.
6123 unsigned NestedLoopCount =
6124 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6125 nullptr /*ordered not a clause on distribute*/, AStmt,
6126 *this, *DSAStack, VarsWithImplicitDSA, B);
6127 if (NestedLoopCount == 0)
6128 return StmtError();
6129
6130 assert((CurContext->isDependentContext() || B.builtAll()) &&
6131 "omp for loop exprs were not built");
6132
Kelvin Lic5609492016-07-15 04:39:07 +00006133 if (checkSimdlenSafelenSpecified(*this, Clauses))
6134 return StmtError();
6135
Kelvin Li787f3fc2016-07-06 04:45:38 +00006136 getCurFunction()->setHasBranchProtectedScope();
6137 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6138 NestedLoopCount, Clauses, AStmt, B);
6139}
6140
Kelvin Lia579b912016-07-14 02:54:56 +00006141StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6142 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6143 SourceLocation EndLoc,
6144 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6145 if (!AStmt)
6146 return StmtError();
6147
6148 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6149 // 1.2.2 OpenMP Language Terminology
6150 // Structured block - An executable statement with a single entry at the
6151 // top and a single exit at the bottom.
6152 // The point of exit cannot be a branch out of the structured block.
6153 // longjmp() and throw() must not violate the entry/exit criteria.
6154 CS->getCapturedDecl()->setNothrow();
6155
6156 OMPLoopDirective::HelperExprs B;
6157 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6158 // define the nested loops number.
6159 unsigned NestedLoopCount = CheckOpenMPLoop(
6160 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6161 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6162 VarsWithImplicitDSA, B);
6163 if (NestedLoopCount == 0)
6164 return StmtError();
6165
6166 assert((CurContext->isDependentContext() || B.builtAll()) &&
6167 "omp target parallel for simd loop exprs were not built");
6168
6169 if (!CurContext->isDependentContext()) {
6170 // Finalize the clauses that need pre-built expressions for CodeGen.
6171 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006172 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006173 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6174 B.NumIterations, *this, CurScope,
6175 DSAStack))
6176 return StmtError();
6177 }
6178 }
Kelvin Lic5609492016-07-15 04:39:07 +00006179 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006180 return StmtError();
6181
6182 getCurFunction()->setHasBranchProtectedScope();
6183 return OMPTargetParallelForSimdDirective::Create(
6184 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6185}
6186
Kelvin Li986330c2016-07-20 22:57:10 +00006187StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6188 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6189 SourceLocation EndLoc,
6190 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6191 if (!AStmt)
6192 return StmtError();
6193
6194 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6195 // 1.2.2 OpenMP Language Terminology
6196 // Structured block - An executable statement with a single entry at the
6197 // top and a single exit at the bottom.
6198 // The point of exit cannot be a branch out of the structured block.
6199 // longjmp() and throw() must not violate the entry/exit criteria.
6200 CS->getCapturedDecl()->setNothrow();
6201
6202 OMPLoopDirective::HelperExprs B;
6203 // In presence of clause 'collapse' with number of loops, it will define the
6204 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006205 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006206 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6207 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6208 VarsWithImplicitDSA, B);
6209 if (NestedLoopCount == 0)
6210 return StmtError();
6211
6212 assert((CurContext->isDependentContext() || B.builtAll()) &&
6213 "omp target simd loop exprs were not built");
6214
6215 if (!CurContext->isDependentContext()) {
6216 // Finalize the clauses that need pre-built expressions for CodeGen.
6217 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006218 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006219 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6220 B.NumIterations, *this, CurScope,
6221 DSAStack))
6222 return StmtError();
6223 }
6224 }
6225
6226 if (checkSimdlenSafelenSpecified(*this, Clauses))
6227 return StmtError();
6228
6229 getCurFunction()->setHasBranchProtectedScope();
6230 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6231 NestedLoopCount, Clauses, AStmt, B);
6232}
6233
Kelvin Li02532872016-08-05 14:37:37 +00006234StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6235 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6236 SourceLocation EndLoc,
6237 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6238 if (!AStmt)
6239 return StmtError();
6240
6241 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6242 // 1.2.2 OpenMP Language Terminology
6243 // Structured block - An executable statement with a single entry at the
6244 // top and a single exit at the bottom.
6245 // The point of exit cannot be a branch out of the structured block.
6246 // longjmp() and throw() must not violate the entry/exit criteria.
6247 CS->getCapturedDecl()->setNothrow();
6248
6249 OMPLoopDirective::HelperExprs B;
6250 // In presence of clause 'collapse' with number of loops, it will
6251 // define the nested loops number.
6252 unsigned NestedLoopCount =
6253 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6254 nullptr /*ordered not a clause on distribute*/, AStmt,
6255 *this, *DSAStack, VarsWithImplicitDSA, B);
6256 if (NestedLoopCount == 0)
6257 return StmtError();
6258
6259 assert((CurContext->isDependentContext() || B.builtAll()) &&
6260 "omp teams distribute loop exprs were not built");
6261
6262 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006263 return OMPTeamsDistributeDirective::Create(
6264 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006265}
6266
Kelvin Li4e325f72016-10-25 12:50:55 +00006267StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6268 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6269 SourceLocation EndLoc,
6270 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6271 if (!AStmt)
6272 return StmtError();
6273
6274 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6275 // 1.2.2 OpenMP Language Terminology
6276 // Structured block - An executable statement with a single entry at the
6277 // top and a single exit at the bottom.
6278 // The point of exit cannot be a branch out of the structured block.
6279 // longjmp() and throw() must not violate the entry/exit criteria.
6280 CS->getCapturedDecl()->setNothrow();
6281
6282 OMPLoopDirective::HelperExprs B;
6283 // In presence of clause 'collapse' with number of loops, it will
6284 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006285 unsigned NestedLoopCount = CheckOpenMPLoop(
6286 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6287 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6288 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006289
6290 if (NestedLoopCount == 0)
6291 return StmtError();
6292
6293 assert((CurContext->isDependentContext() || B.builtAll()) &&
6294 "omp teams distribute simd loop exprs were not built");
6295
6296 if (!CurContext->isDependentContext()) {
6297 // Finalize the clauses that need pre-built expressions for CodeGen.
6298 for (auto C : Clauses) {
6299 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6300 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6301 B.NumIterations, *this, CurScope,
6302 DSAStack))
6303 return StmtError();
6304 }
6305 }
6306
6307 if (checkSimdlenSafelenSpecified(*this, Clauses))
6308 return StmtError();
6309
6310 getCurFunction()->setHasBranchProtectedScope();
6311 return OMPTeamsDistributeSimdDirective::Create(
6312 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6313}
6314
Kelvin Li579e41c2016-11-30 23:51:03 +00006315StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6316 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6317 SourceLocation EndLoc,
6318 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6319 if (!AStmt)
6320 return StmtError();
6321
6322 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6323 // 1.2.2 OpenMP Language Terminology
6324 // Structured block - An executable statement with a single entry at the
6325 // top and a single exit at the bottom.
6326 // The point of exit cannot be a branch out of the structured block.
6327 // longjmp() and throw() must not violate the entry/exit criteria.
6328 CS->getCapturedDecl()->setNothrow();
6329
6330 OMPLoopDirective::HelperExprs B;
6331 // In presence of clause 'collapse' with number of loops, it will
6332 // define the nested loops number.
6333 auto NestedLoopCount = CheckOpenMPLoop(
6334 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6335 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6336 VarsWithImplicitDSA, B);
6337
6338 if (NestedLoopCount == 0)
6339 return StmtError();
6340
6341 assert((CurContext->isDependentContext() || B.builtAll()) &&
6342 "omp for loop exprs were not built");
6343
6344 if (!CurContext->isDependentContext()) {
6345 // Finalize the clauses that need pre-built expressions for CodeGen.
6346 for (auto C : Clauses) {
6347 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6348 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6349 B.NumIterations, *this, CurScope,
6350 DSAStack))
6351 return StmtError();
6352 }
6353 }
6354
6355 if (checkSimdlenSafelenSpecified(*this, Clauses))
6356 return StmtError();
6357
6358 getCurFunction()->setHasBranchProtectedScope();
6359 return OMPTeamsDistributeParallelForSimdDirective::Create(
6360 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6361}
6362
Kelvin Li7ade93f2016-12-09 03:24:30 +00006363StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6364 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6365 SourceLocation EndLoc,
6366 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6367 if (!AStmt)
6368 return StmtError();
6369
6370 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6371 // 1.2.2 OpenMP Language Terminology
6372 // Structured block - An executable statement with a single entry at the
6373 // top and a single exit at the bottom.
6374 // The point of exit cannot be a branch out of the structured block.
6375 // longjmp() and throw() must not violate the entry/exit criteria.
6376 CS->getCapturedDecl()->setNothrow();
6377
6378 OMPLoopDirective::HelperExprs B;
6379 // In presence of clause 'collapse' with number of loops, it will
6380 // define the nested loops number.
6381 unsigned NestedLoopCount = CheckOpenMPLoop(
6382 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6383 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6384 VarsWithImplicitDSA, B);
6385
6386 if (NestedLoopCount == 0)
6387 return StmtError();
6388
6389 assert((CurContext->isDependentContext() || B.builtAll()) &&
6390 "omp for loop exprs were not built");
6391
6392 if (!CurContext->isDependentContext()) {
6393 // Finalize the clauses that need pre-built expressions for CodeGen.
6394 for (auto C : Clauses) {
6395 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6396 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6397 B.NumIterations, *this, CurScope,
6398 DSAStack))
6399 return StmtError();
6400 }
6401 }
6402
6403 getCurFunction()->setHasBranchProtectedScope();
6404 return OMPTeamsDistributeParallelForDirective::Create(
6405 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6406}
6407
Kelvin Libf594a52016-12-17 05:48:59 +00006408StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6409 Stmt *AStmt,
6410 SourceLocation StartLoc,
6411 SourceLocation EndLoc) {
6412 if (!AStmt)
6413 return StmtError();
6414
6415 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6416 // 1.2.2 OpenMP Language Terminology
6417 // Structured block - An executable statement with a single entry at the
6418 // top and a single exit at the bottom.
6419 // The point of exit cannot be a branch out of the structured block.
6420 // longjmp() and throw() must not violate the entry/exit criteria.
6421 CS->getCapturedDecl()->setNothrow();
6422
6423 getCurFunction()->setHasBranchProtectedScope();
6424
6425 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6426 AStmt);
6427}
6428
Kelvin Li83c451e2016-12-25 04:52:54 +00006429StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6430 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6431 SourceLocation EndLoc,
6432 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6433 if (!AStmt)
6434 return StmtError();
6435
6436 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6437 // 1.2.2 OpenMP Language Terminology
6438 // Structured block - An executable statement with a single entry at the
6439 // top and a single exit at the bottom.
6440 // The point of exit cannot be a branch out of the structured block.
6441 // longjmp() and throw() must not violate the entry/exit criteria.
6442 CS->getCapturedDecl()->setNothrow();
6443
6444 OMPLoopDirective::HelperExprs B;
6445 // In presence of clause 'collapse' with number of loops, it will
6446 // define the nested loops number.
6447 auto NestedLoopCount = CheckOpenMPLoop(
6448 OMPD_target_teams_distribute,
6449 getCollapseNumberExpr(Clauses),
6450 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6451 VarsWithImplicitDSA, B);
6452 if (NestedLoopCount == 0)
6453 return StmtError();
6454
6455 assert((CurContext->isDependentContext() || B.builtAll()) &&
6456 "omp target teams distribute loop exprs were not built");
6457
6458 getCurFunction()->setHasBranchProtectedScope();
6459 return OMPTargetTeamsDistributeDirective::Create(
6460 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6461}
6462
Kelvin Li80e8f562016-12-29 22:16:30 +00006463StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6464 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6465 SourceLocation EndLoc,
6466 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6467 if (!AStmt)
6468 return StmtError();
6469
6470 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6471 // 1.2.2 OpenMP Language Terminology
6472 // Structured block - An executable statement with a single entry at the
6473 // top and a single exit at the bottom.
6474 // The point of exit cannot be a branch out of the structured block.
6475 // longjmp() and throw() must not violate the entry/exit criteria.
6476 CS->getCapturedDecl()->setNothrow();
6477
6478 OMPLoopDirective::HelperExprs B;
6479 // In presence of clause 'collapse' with number of loops, it will
6480 // define the nested loops number.
6481 auto NestedLoopCount = CheckOpenMPLoop(
6482 OMPD_target_teams_distribute_parallel_for,
6483 getCollapseNumberExpr(Clauses),
6484 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6485 VarsWithImplicitDSA, B);
6486 if (NestedLoopCount == 0)
6487 return StmtError();
6488
6489 assert((CurContext->isDependentContext() || B.builtAll()) &&
6490 "omp target teams distribute parallel for loop exprs were not built");
6491
6492 if (!CurContext->isDependentContext()) {
6493 // Finalize the clauses that need pre-built expressions for CodeGen.
6494 for (auto C : Clauses) {
6495 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6496 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6497 B.NumIterations, *this, CurScope,
6498 DSAStack))
6499 return StmtError();
6500 }
6501 }
6502
6503 getCurFunction()->setHasBranchProtectedScope();
6504 return OMPTargetTeamsDistributeParallelForDirective::Create(
6505 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6506}
6507
Kelvin Li1851df52017-01-03 05:23:48 +00006508StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6509 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6510 SourceLocation EndLoc,
6511 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6512 if (!AStmt)
6513 return StmtError();
6514
6515 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6516 // 1.2.2 OpenMP Language Terminology
6517 // Structured block - An executable statement with a single entry at the
6518 // top and a single exit at the bottom.
6519 // The point of exit cannot be a branch out of the structured block.
6520 // longjmp() and throw() must not violate the entry/exit criteria.
6521 CS->getCapturedDecl()->setNothrow();
6522
6523 OMPLoopDirective::HelperExprs B;
6524 // In presence of clause 'collapse' with number of loops, it will
6525 // define the nested loops number.
6526 auto NestedLoopCount = CheckOpenMPLoop(
6527 OMPD_target_teams_distribute_parallel_for_simd,
6528 getCollapseNumberExpr(Clauses),
6529 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6530 VarsWithImplicitDSA, B);
6531 if (NestedLoopCount == 0)
6532 return StmtError();
6533
6534 assert((CurContext->isDependentContext() || B.builtAll()) &&
6535 "omp target teams distribute parallel for simd loop exprs were not "
6536 "built");
6537
6538 if (!CurContext->isDependentContext()) {
6539 // Finalize the clauses that need pre-built expressions for CodeGen.
6540 for (auto C : Clauses) {
6541 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6542 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6543 B.NumIterations, *this, CurScope,
6544 DSAStack))
6545 return StmtError();
6546 }
6547 }
6548
6549 getCurFunction()->setHasBranchProtectedScope();
6550 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6551 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6552}
6553
Kelvin Lida681182017-01-10 18:08:18 +00006554StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6555 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6556 SourceLocation EndLoc,
6557 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6558 if (!AStmt)
6559 return StmtError();
6560
6561 auto *CS = cast<CapturedStmt>(AStmt);
6562 // 1.2.2 OpenMP Language Terminology
6563 // Structured block - An executable statement with a single entry at the
6564 // top and a single exit at the bottom.
6565 // The point of exit cannot be a branch out of the structured block.
6566 // longjmp() and throw() must not violate the entry/exit criteria.
6567 CS->getCapturedDecl()->setNothrow();
6568
6569 OMPLoopDirective::HelperExprs B;
6570 // In presence of clause 'collapse' with number of loops, it will
6571 // define the nested loops number.
6572 auto NestedLoopCount = CheckOpenMPLoop(
6573 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6574 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6575 VarsWithImplicitDSA, B);
6576 if (NestedLoopCount == 0)
6577 return StmtError();
6578
6579 assert((CurContext->isDependentContext() || B.builtAll()) &&
6580 "omp target teams distribute simd loop exprs were not built");
6581
6582 getCurFunction()->setHasBranchProtectedScope();
6583 return OMPTargetTeamsDistributeSimdDirective::Create(
6584 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6585}
6586
Alexey Bataeved09d242014-05-28 05:53:51 +00006587OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006588 SourceLocation StartLoc,
6589 SourceLocation LParenLoc,
6590 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006591 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006592 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006593 case OMPC_final:
6594 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6595 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006596 case OMPC_num_threads:
6597 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6598 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006599 case OMPC_safelen:
6600 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6601 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006602 case OMPC_simdlen:
6603 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6604 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006605 case OMPC_collapse:
6606 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6607 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006608 case OMPC_ordered:
6609 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6610 break;
Michael Wonge710d542015-08-07 16:16:36 +00006611 case OMPC_device:
6612 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6613 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006614 case OMPC_num_teams:
6615 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6616 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006617 case OMPC_thread_limit:
6618 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6619 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006620 case OMPC_priority:
6621 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6622 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006623 case OMPC_grainsize:
6624 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6625 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006626 case OMPC_num_tasks:
6627 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6628 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006629 case OMPC_hint:
6630 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6631 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006632 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006633 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006634 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006635 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006636 case OMPC_private:
6637 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006638 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006639 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006640 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006641 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006642 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006643 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006644 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006645 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006646 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006647 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006648 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006649 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006650 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006651 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006652 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006653 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006654 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006655 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006656 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006657 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006658 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006659 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006660 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006661 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006662 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006663 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006664 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006665 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006666 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006667 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006668 llvm_unreachable("Clause is not allowed.");
6669 }
6670 return Res;
6671}
6672
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006673// An OpenMP directive such as 'target parallel' has two captured regions:
6674// for the 'target' and 'parallel' respectively. This function returns
6675// the region in which to capture expressions associated with a clause.
6676// A return value of OMPD_unknown signifies that the expression should not
6677// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006678static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6679 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6680 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006681 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6682
6683 switch (CKind) {
6684 case OMPC_if:
6685 switch (DKind) {
6686 case OMPD_target_parallel:
6687 // If this clause applies to the nested 'parallel' region, capture within
6688 // the 'target' region, otherwise do not capture.
6689 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6690 CaptureRegion = OMPD_target;
6691 break;
6692 case OMPD_cancel:
6693 case OMPD_parallel:
6694 case OMPD_parallel_sections:
6695 case OMPD_parallel_for:
6696 case OMPD_parallel_for_simd:
6697 case OMPD_target:
6698 case OMPD_target_simd:
6699 case OMPD_target_parallel_for:
6700 case OMPD_target_parallel_for_simd:
6701 case OMPD_target_teams:
6702 case OMPD_target_teams_distribute:
6703 case OMPD_target_teams_distribute_simd:
6704 case OMPD_target_teams_distribute_parallel_for:
6705 case OMPD_target_teams_distribute_parallel_for_simd:
6706 case OMPD_teams_distribute_parallel_for:
6707 case OMPD_teams_distribute_parallel_for_simd:
6708 case OMPD_distribute_parallel_for:
6709 case OMPD_distribute_parallel_for_simd:
6710 case OMPD_task:
6711 case OMPD_taskloop:
6712 case OMPD_taskloop_simd:
6713 case OMPD_target_data:
6714 case OMPD_target_enter_data:
6715 case OMPD_target_exit_data:
6716 case OMPD_target_update:
6717 // Do not capture if-clause expressions.
6718 break;
6719 case OMPD_threadprivate:
6720 case OMPD_taskyield:
6721 case OMPD_barrier:
6722 case OMPD_taskwait:
6723 case OMPD_cancellation_point:
6724 case OMPD_flush:
6725 case OMPD_declare_reduction:
6726 case OMPD_declare_simd:
6727 case OMPD_declare_target:
6728 case OMPD_end_declare_target:
6729 case OMPD_teams:
6730 case OMPD_simd:
6731 case OMPD_for:
6732 case OMPD_for_simd:
6733 case OMPD_sections:
6734 case OMPD_section:
6735 case OMPD_single:
6736 case OMPD_master:
6737 case OMPD_critical:
6738 case OMPD_taskgroup:
6739 case OMPD_distribute:
6740 case OMPD_ordered:
6741 case OMPD_atomic:
6742 case OMPD_distribute_simd:
6743 case OMPD_teams_distribute:
6744 case OMPD_teams_distribute_simd:
6745 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6746 case OMPD_unknown:
6747 llvm_unreachable("Unknown OpenMP directive");
6748 }
6749 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006750 case OMPC_num_threads:
6751 switch (DKind) {
6752 case OMPD_target_parallel:
6753 CaptureRegion = OMPD_target;
6754 break;
6755 case OMPD_cancel:
6756 case OMPD_parallel:
6757 case OMPD_parallel_sections:
6758 case OMPD_parallel_for:
6759 case OMPD_parallel_for_simd:
6760 case OMPD_target:
6761 case OMPD_target_simd:
6762 case OMPD_target_parallel_for:
6763 case OMPD_target_parallel_for_simd:
6764 case OMPD_target_teams:
6765 case OMPD_target_teams_distribute:
6766 case OMPD_target_teams_distribute_simd:
6767 case OMPD_target_teams_distribute_parallel_for:
6768 case OMPD_target_teams_distribute_parallel_for_simd:
6769 case OMPD_teams_distribute_parallel_for:
6770 case OMPD_teams_distribute_parallel_for_simd:
6771 case OMPD_distribute_parallel_for:
6772 case OMPD_distribute_parallel_for_simd:
6773 case OMPD_task:
6774 case OMPD_taskloop:
6775 case OMPD_taskloop_simd:
6776 case OMPD_target_data:
6777 case OMPD_target_enter_data:
6778 case OMPD_target_exit_data:
6779 case OMPD_target_update:
6780 // Do not capture num_threads-clause expressions.
6781 break;
6782 case OMPD_threadprivate:
6783 case OMPD_taskyield:
6784 case OMPD_barrier:
6785 case OMPD_taskwait:
6786 case OMPD_cancellation_point:
6787 case OMPD_flush:
6788 case OMPD_declare_reduction:
6789 case OMPD_declare_simd:
6790 case OMPD_declare_target:
6791 case OMPD_end_declare_target:
6792 case OMPD_teams:
6793 case OMPD_simd:
6794 case OMPD_for:
6795 case OMPD_for_simd:
6796 case OMPD_sections:
6797 case OMPD_section:
6798 case OMPD_single:
6799 case OMPD_master:
6800 case OMPD_critical:
6801 case OMPD_taskgroup:
6802 case OMPD_distribute:
6803 case OMPD_ordered:
6804 case OMPD_atomic:
6805 case OMPD_distribute_simd:
6806 case OMPD_teams_distribute:
6807 case OMPD_teams_distribute_simd:
6808 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6809 case OMPD_unknown:
6810 llvm_unreachable("Unknown OpenMP directive");
6811 }
6812 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00006813 case OMPC_num_teams:
6814 switch (DKind) {
6815 case OMPD_target_teams:
6816 CaptureRegion = OMPD_target;
6817 break;
6818 case OMPD_cancel:
6819 case OMPD_parallel:
6820 case OMPD_parallel_sections:
6821 case OMPD_parallel_for:
6822 case OMPD_parallel_for_simd:
6823 case OMPD_target:
6824 case OMPD_target_simd:
6825 case OMPD_target_parallel:
6826 case OMPD_target_parallel_for:
6827 case OMPD_target_parallel_for_simd:
6828 case OMPD_target_teams_distribute:
6829 case OMPD_target_teams_distribute_simd:
6830 case OMPD_target_teams_distribute_parallel_for:
6831 case OMPD_target_teams_distribute_parallel_for_simd:
6832 case OMPD_teams_distribute_parallel_for:
6833 case OMPD_teams_distribute_parallel_for_simd:
6834 case OMPD_distribute_parallel_for:
6835 case OMPD_distribute_parallel_for_simd:
6836 case OMPD_task:
6837 case OMPD_taskloop:
6838 case OMPD_taskloop_simd:
6839 case OMPD_target_data:
6840 case OMPD_target_enter_data:
6841 case OMPD_target_exit_data:
6842 case OMPD_target_update:
6843 case OMPD_teams:
6844 case OMPD_teams_distribute:
6845 case OMPD_teams_distribute_simd:
6846 // Do not capture num_teams-clause expressions.
6847 break;
6848 case OMPD_threadprivate:
6849 case OMPD_taskyield:
6850 case OMPD_barrier:
6851 case OMPD_taskwait:
6852 case OMPD_cancellation_point:
6853 case OMPD_flush:
6854 case OMPD_declare_reduction:
6855 case OMPD_declare_simd:
6856 case OMPD_declare_target:
6857 case OMPD_end_declare_target:
6858 case OMPD_simd:
6859 case OMPD_for:
6860 case OMPD_for_simd:
6861 case OMPD_sections:
6862 case OMPD_section:
6863 case OMPD_single:
6864 case OMPD_master:
6865 case OMPD_critical:
6866 case OMPD_taskgroup:
6867 case OMPD_distribute:
6868 case OMPD_ordered:
6869 case OMPD_atomic:
6870 case OMPD_distribute_simd:
6871 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
6872 case OMPD_unknown:
6873 llvm_unreachable("Unknown OpenMP directive");
6874 }
6875 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00006876 case OMPC_thread_limit:
6877 switch (DKind) {
6878 case OMPD_target_teams:
6879 CaptureRegion = OMPD_target;
6880 break;
6881 case OMPD_cancel:
6882 case OMPD_parallel:
6883 case OMPD_parallel_sections:
6884 case OMPD_parallel_for:
6885 case OMPD_parallel_for_simd:
6886 case OMPD_target:
6887 case OMPD_target_simd:
6888 case OMPD_target_parallel:
6889 case OMPD_target_parallel_for:
6890 case OMPD_target_parallel_for_simd:
6891 case OMPD_target_teams_distribute:
6892 case OMPD_target_teams_distribute_simd:
6893 case OMPD_target_teams_distribute_parallel_for:
6894 case OMPD_target_teams_distribute_parallel_for_simd:
6895 case OMPD_teams_distribute_parallel_for:
6896 case OMPD_teams_distribute_parallel_for_simd:
6897 case OMPD_distribute_parallel_for:
6898 case OMPD_distribute_parallel_for_simd:
6899 case OMPD_task:
6900 case OMPD_taskloop:
6901 case OMPD_taskloop_simd:
6902 case OMPD_target_data:
6903 case OMPD_target_enter_data:
6904 case OMPD_target_exit_data:
6905 case OMPD_target_update:
6906 case OMPD_teams:
6907 case OMPD_teams_distribute:
6908 case OMPD_teams_distribute_simd:
6909 // Do not capture thread_limit-clause expressions.
6910 break;
6911 case OMPD_threadprivate:
6912 case OMPD_taskyield:
6913 case OMPD_barrier:
6914 case OMPD_taskwait:
6915 case OMPD_cancellation_point:
6916 case OMPD_flush:
6917 case OMPD_declare_reduction:
6918 case OMPD_declare_simd:
6919 case OMPD_declare_target:
6920 case OMPD_end_declare_target:
6921 case OMPD_simd:
6922 case OMPD_for:
6923 case OMPD_for_simd:
6924 case OMPD_sections:
6925 case OMPD_section:
6926 case OMPD_single:
6927 case OMPD_master:
6928 case OMPD_critical:
6929 case OMPD_taskgroup:
6930 case OMPD_distribute:
6931 case OMPD_ordered:
6932 case OMPD_atomic:
6933 case OMPD_distribute_simd:
6934 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
6935 case OMPD_unknown:
6936 llvm_unreachable("Unknown OpenMP directive");
6937 }
6938 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006939 case OMPC_schedule:
6940 case OMPC_dist_schedule:
6941 case OMPC_firstprivate:
6942 case OMPC_lastprivate:
6943 case OMPC_reduction:
6944 case OMPC_linear:
6945 case OMPC_default:
6946 case OMPC_proc_bind:
6947 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006948 case OMPC_safelen:
6949 case OMPC_simdlen:
6950 case OMPC_collapse:
6951 case OMPC_private:
6952 case OMPC_shared:
6953 case OMPC_aligned:
6954 case OMPC_copyin:
6955 case OMPC_copyprivate:
6956 case OMPC_ordered:
6957 case OMPC_nowait:
6958 case OMPC_untied:
6959 case OMPC_mergeable:
6960 case OMPC_threadprivate:
6961 case OMPC_flush:
6962 case OMPC_read:
6963 case OMPC_write:
6964 case OMPC_update:
6965 case OMPC_capture:
6966 case OMPC_seq_cst:
6967 case OMPC_depend:
6968 case OMPC_device:
6969 case OMPC_threads:
6970 case OMPC_simd:
6971 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006972 case OMPC_priority:
6973 case OMPC_grainsize:
6974 case OMPC_nogroup:
6975 case OMPC_num_tasks:
6976 case OMPC_hint:
6977 case OMPC_defaultmap:
6978 case OMPC_unknown:
6979 case OMPC_uniform:
6980 case OMPC_to:
6981 case OMPC_from:
6982 case OMPC_use_device_ptr:
6983 case OMPC_is_device_ptr:
6984 llvm_unreachable("Unexpected OpenMP clause.");
6985 }
6986 return CaptureRegion;
6987}
6988
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006989OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6990 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006991 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006992 SourceLocation NameModifierLoc,
6993 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006994 SourceLocation EndLoc) {
6995 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006996 Stmt *HelperValStmt = nullptr;
6997 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006998 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6999 !Condition->isInstantiationDependent() &&
7000 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007001 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007002 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007003 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007004
Richard Smith03a4aa32016-06-23 19:02:52 +00007005 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007006
7007 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7008 CaptureRegion =
7009 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7010 if (CaptureRegion != OMPD_unknown) {
7011 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7012 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7013 HelperValStmt = buildPreInits(Context, Captures);
7014 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007015 }
7016
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007017 return new (Context)
7018 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7019 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007020}
7021
Alexey Bataev3778b602014-07-17 07:32:53 +00007022OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7023 SourceLocation StartLoc,
7024 SourceLocation LParenLoc,
7025 SourceLocation EndLoc) {
7026 Expr *ValExpr = Condition;
7027 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7028 !Condition->isInstantiationDependent() &&
7029 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007030 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007031 if (Val.isInvalid())
7032 return nullptr;
7033
Richard Smith03a4aa32016-06-23 19:02:52 +00007034 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007035 }
7036
7037 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7038}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007039ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7040 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007041 if (!Op)
7042 return ExprError();
7043
7044 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7045 public:
7046 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007047 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007048 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7049 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007050 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7051 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007052 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7053 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007054 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7055 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007056 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7057 QualType T,
7058 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007059 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7060 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007061 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7062 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007063 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007064 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007065 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007066 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7067 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007068 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7069 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007070 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7071 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007072 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007073 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007074 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007075 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7076 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007077 llvm_unreachable("conversion functions are permitted");
7078 }
7079 } ConvertDiagnoser;
7080 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7081}
7082
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007083static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007084 OpenMPClauseKind CKind,
7085 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007086 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7087 !ValExpr->isInstantiationDependent()) {
7088 SourceLocation Loc = ValExpr->getExprLoc();
7089 ExprResult Value =
7090 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7091 if (Value.isInvalid())
7092 return false;
7093
7094 ValExpr = Value.get();
7095 // The expression must evaluate to a non-negative integer value.
7096 llvm::APSInt Result;
7097 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007098 Result.isSigned() &&
7099 !((!StrictlyPositive && Result.isNonNegative()) ||
7100 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007101 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007102 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7103 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007104 return false;
7105 }
7106 }
7107 return true;
7108}
7109
Alexey Bataev568a8332014-03-06 06:15:19 +00007110OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7111 SourceLocation StartLoc,
7112 SourceLocation LParenLoc,
7113 SourceLocation EndLoc) {
7114 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007115 Stmt *HelperValStmt = nullptr;
7116 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007117
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007118 // OpenMP [2.5, Restrictions]
7119 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007120 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7121 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007122 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007123
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007124 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7125 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7126 if (CaptureRegion != OMPD_unknown) {
7127 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7128 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7129 HelperValStmt = buildPreInits(Context, Captures);
7130 }
7131
7132 return new (Context) OMPNumThreadsClause(
7133 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007134}
7135
Alexey Bataev62c87d22014-03-21 04:51:18 +00007136ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007137 OpenMPClauseKind CKind,
7138 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007139 if (!E)
7140 return ExprError();
7141 if (E->isValueDependent() || E->isTypeDependent() ||
7142 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007143 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007144 llvm::APSInt Result;
7145 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7146 if (ICE.isInvalid())
7147 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007148 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7149 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007150 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007151 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7152 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007153 return ExprError();
7154 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007155 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7156 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7157 << E->getSourceRange();
7158 return ExprError();
7159 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007160 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7161 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007162 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007163 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007164 return ICE;
7165}
7166
7167OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7168 SourceLocation LParenLoc,
7169 SourceLocation EndLoc) {
7170 // OpenMP [2.8.1, simd construct, Description]
7171 // The parameter of the safelen clause must be a constant
7172 // positive integer expression.
7173 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7174 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007175 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007176 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007177 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007178}
7179
Alexey Bataev66b15b52015-08-21 11:14:16 +00007180OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7181 SourceLocation LParenLoc,
7182 SourceLocation EndLoc) {
7183 // OpenMP [2.8.1, simd construct, Description]
7184 // The parameter of the simdlen clause must be a constant
7185 // positive integer expression.
7186 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7187 if (Simdlen.isInvalid())
7188 return nullptr;
7189 return new (Context)
7190 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7191}
7192
Alexander Musman64d33f12014-06-04 07:53:32 +00007193OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7194 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007195 SourceLocation LParenLoc,
7196 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007197 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007198 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007199 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007200 // The parameter of the collapse clause must be a constant
7201 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007202 ExprResult NumForLoopsResult =
7203 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7204 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007205 return nullptr;
7206 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007207 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007208}
7209
Alexey Bataev10e775f2015-07-30 11:36:16 +00007210OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7211 SourceLocation EndLoc,
7212 SourceLocation LParenLoc,
7213 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007214 // OpenMP [2.7.1, loop construct, Description]
7215 // OpenMP [2.8.1, simd construct, Description]
7216 // OpenMP [2.9.6, distribute construct, Description]
7217 // The parameter of the ordered clause must be a constant
7218 // positive integer expression if any.
7219 if (NumForLoops && LParenLoc.isValid()) {
7220 ExprResult NumForLoopsResult =
7221 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7222 if (NumForLoopsResult.isInvalid())
7223 return nullptr;
7224 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007225 } else
7226 NumForLoops = nullptr;
7227 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007228 return new (Context)
7229 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7230}
7231
Alexey Bataeved09d242014-05-28 05:53:51 +00007232OMPClause *Sema::ActOnOpenMPSimpleClause(
7233 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7234 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007235 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007236 switch (Kind) {
7237 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007238 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007239 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7240 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007241 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007242 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007243 Res = ActOnOpenMPProcBindClause(
7244 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7245 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007246 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007247 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007248 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007249 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007250 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007251 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007252 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007253 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007254 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007255 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007256 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007257 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007258 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007259 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007260 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007261 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007262 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007263 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007264 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007265 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007266 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007267 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007268 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007269 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007270 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007271 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007272 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007273 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007274 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007275 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007276 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007277 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007278 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007279 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007280 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007281 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007282 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007283 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007284 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007285 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007286 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007287 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007288 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007289 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007290 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007291 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007292 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007293 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007294 llvm_unreachable("Clause is not allowed.");
7295 }
7296 return Res;
7297}
7298
Alexey Bataev6402bca2015-12-28 07:25:51 +00007299static std::string
7300getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7301 ArrayRef<unsigned> Exclude = llvm::None) {
7302 std::string Values;
7303 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7304 unsigned Skipped = Exclude.size();
7305 auto S = Exclude.begin(), E = Exclude.end();
7306 for (unsigned i = First; i < Last; ++i) {
7307 if (std::find(S, E, i) != E) {
7308 --Skipped;
7309 continue;
7310 }
7311 Values += "'";
7312 Values += getOpenMPSimpleClauseTypeName(K, i);
7313 Values += "'";
7314 if (i == Bound - Skipped)
7315 Values += " or ";
7316 else if (i != Bound + 1 - Skipped)
7317 Values += ", ";
7318 }
7319 return Values;
7320}
7321
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007322OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7323 SourceLocation KindKwLoc,
7324 SourceLocation StartLoc,
7325 SourceLocation LParenLoc,
7326 SourceLocation EndLoc) {
7327 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007328 static_assert(OMPC_DEFAULT_unknown > 0,
7329 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007330 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007331 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7332 /*Last=*/OMPC_DEFAULT_unknown)
7333 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007334 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007335 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007336 switch (Kind) {
7337 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007338 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007339 break;
7340 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007341 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007342 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007343 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007344 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007345 break;
7346 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007347 return new (Context)
7348 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007349}
7350
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007351OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7352 SourceLocation KindKwLoc,
7353 SourceLocation StartLoc,
7354 SourceLocation LParenLoc,
7355 SourceLocation EndLoc) {
7356 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007357 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007358 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7359 /*Last=*/OMPC_PROC_BIND_unknown)
7360 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007361 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007362 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007363 return new (Context)
7364 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007365}
7366
Alexey Bataev56dafe82014-06-20 07:16:17 +00007367OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007368 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007369 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007370 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007371 SourceLocation EndLoc) {
7372 OMPClause *Res = nullptr;
7373 switch (Kind) {
7374 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007375 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7376 assert(Argument.size() == NumberOfElements &&
7377 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007378 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007379 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7380 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7381 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7382 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7383 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007384 break;
7385 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007386 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7387 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7388 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7389 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007390 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007391 case OMPC_dist_schedule:
7392 Res = ActOnOpenMPDistScheduleClause(
7393 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7394 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7395 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007396 case OMPC_defaultmap:
7397 enum { Modifier, DefaultmapKind };
7398 Res = ActOnOpenMPDefaultmapClause(
7399 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7400 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007401 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7402 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007403 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007404 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007405 case OMPC_num_threads:
7406 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007407 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007408 case OMPC_collapse:
7409 case OMPC_default:
7410 case OMPC_proc_bind:
7411 case OMPC_private:
7412 case OMPC_firstprivate:
7413 case OMPC_lastprivate:
7414 case OMPC_shared:
7415 case OMPC_reduction:
7416 case OMPC_linear:
7417 case OMPC_aligned:
7418 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007419 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007420 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007421 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007422 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007423 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007424 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007425 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007426 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007427 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007428 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007429 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007430 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007431 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007432 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007433 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007434 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007435 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007436 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007437 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007438 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007439 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007440 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007441 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007442 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007443 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007444 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007445 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007446 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007447 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007448 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007449 llvm_unreachable("Clause is not allowed.");
7450 }
7451 return Res;
7452}
7453
Alexey Bataev6402bca2015-12-28 07:25:51 +00007454static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7455 OpenMPScheduleClauseModifier M2,
7456 SourceLocation M1Loc, SourceLocation M2Loc) {
7457 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7458 SmallVector<unsigned, 2> Excluded;
7459 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7460 Excluded.push_back(M2);
7461 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7462 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7463 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7464 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7465 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7466 << getListOfPossibleValues(OMPC_schedule,
7467 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7468 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7469 Excluded)
7470 << getOpenMPClauseName(OMPC_schedule);
7471 return true;
7472 }
7473 return false;
7474}
7475
Alexey Bataev56dafe82014-06-20 07:16:17 +00007476OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007477 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007478 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007479 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7480 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7481 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7482 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7483 return nullptr;
7484 // OpenMP, 2.7.1, Loop Construct, Restrictions
7485 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7486 // but not both.
7487 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7488 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7489 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7490 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7491 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7492 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7493 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7494 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7495 return nullptr;
7496 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007497 if (Kind == OMPC_SCHEDULE_unknown) {
7498 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007499 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7500 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7501 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7502 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7503 Exclude);
7504 } else {
7505 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7506 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007507 }
7508 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7509 << Values << getOpenMPClauseName(OMPC_schedule);
7510 return nullptr;
7511 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007512 // OpenMP, 2.7.1, Loop Construct, Restrictions
7513 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7514 // schedule(guided).
7515 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7516 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7517 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7518 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7519 diag::err_omp_schedule_nonmonotonic_static);
7520 return nullptr;
7521 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007522 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007523 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007524 if (ChunkSize) {
7525 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7526 !ChunkSize->isInstantiationDependent() &&
7527 !ChunkSize->containsUnexpandedParameterPack()) {
7528 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7529 ExprResult Val =
7530 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7531 if (Val.isInvalid())
7532 return nullptr;
7533
7534 ValExpr = Val.get();
7535
7536 // OpenMP [2.7.1, Restrictions]
7537 // chunk_size must be a loop invariant integer expression with a positive
7538 // value.
7539 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007540 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7541 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7542 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007543 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007544 return nullptr;
7545 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007546 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7547 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007548 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7549 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7550 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007551 }
7552 }
7553 }
7554
Alexey Bataev6402bca2015-12-28 07:25:51 +00007555 return new (Context)
7556 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007557 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007558}
7559
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007560OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7561 SourceLocation StartLoc,
7562 SourceLocation EndLoc) {
7563 OMPClause *Res = nullptr;
7564 switch (Kind) {
7565 case OMPC_ordered:
7566 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7567 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007568 case OMPC_nowait:
7569 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7570 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007571 case OMPC_untied:
7572 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7573 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007574 case OMPC_mergeable:
7575 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7576 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007577 case OMPC_read:
7578 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7579 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007580 case OMPC_write:
7581 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7582 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007583 case OMPC_update:
7584 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7585 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007586 case OMPC_capture:
7587 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7588 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007589 case OMPC_seq_cst:
7590 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7591 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007592 case OMPC_threads:
7593 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7594 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007595 case OMPC_simd:
7596 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7597 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007598 case OMPC_nogroup:
7599 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7600 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007601 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007602 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007603 case OMPC_num_threads:
7604 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007605 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007606 case OMPC_collapse:
7607 case OMPC_schedule:
7608 case OMPC_private:
7609 case OMPC_firstprivate:
7610 case OMPC_lastprivate:
7611 case OMPC_shared:
7612 case OMPC_reduction:
7613 case OMPC_linear:
7614 case OMPC_aligned:
7615 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007616 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007617 case OMPC_default:
7618 case OMPC_proc_bind:
7619 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007620 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007621 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007622 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007623 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007624 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007625 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007626 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007627 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007628 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007629 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007630 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007631 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007632 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007633 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007634 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007635 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007636 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007637 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007638 llvm_unreachable("Clause is not allowed.");
7639 }
7640 return Res;
7641}
7642
Alexey Bataev236070f2014-06-20 11:19:47 +00007643OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7644 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007645 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007646 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7647}
7648
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007649OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7650 SourceLocation EndLoc) {
7651 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7652}
7653
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007654OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7655 SourceLocation EndLoc) {
7656 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7657}
7658
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007659OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7660 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007661 return new (Context) OMPReadClause(StartLoc, EndLoc);
7662}
7663
Alexey Bataevdea47612014-07-23 07:46:59 +00007664OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7665 SourceLocation EndLoc) {
7666 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7667}
7668
Alexey Bataev67a4f222014-07-23 10:25:33 +00007669OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7670 SourceLocation EndLoc) {
7671 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7672}
7673
Alexey Bataev459dec02014-07-24 06:46:57 +00007674OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7675 SourceLocation EndLoc) {
7676 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7677}
7678
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007679OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7680 SourceLocation EndLoc) {
7681 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7682}
7683
Alexey Bataev346265e2015-09-25 10:37:12 +00007684OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7685 SourceLocation EndLoc) {
7686 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7687}
7688
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007689OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7690 SourceLocation EndLoc) {
7691 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7692}
7693
Alexey Bataevb825de12015-12-07 10:51:44 +00007694OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7695 SourceLocation EndLoc) {
7696 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7697}
7698
Alexey Bataevc5e02582014-06-16 07:08:35 +00007699OMPClause *Sema::ActOnOpenMPVarListClause(
7700 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7701 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7702 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007703 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007704 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7705 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7706 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007707 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007708 switch (Kind) {
7709 case OMPC_private:
7710 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7711 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007712 case OMPC_firstprivate:
7713 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7714 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007715 case OMPC_lastprivate:
7716 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7717 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007718 case OMPC_shared:
7719 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7720 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007721 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007722 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7723 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007724 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007725 case OMPC_linear:
7726 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007727 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007728 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007729 case OMPC_aligned:
7730 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7731 ColonLoc, EndLoc);
7732 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007733 case OMPC_copyin:
7734 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7735 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007736 case OMPC_copyprivate:
7737 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7738 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007739 case OMPC_flush:
7740 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7741 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007742 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007743 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007744 StartLoc, LParenLoc, EndLoc);
7745 break;
7746 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007747 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7748 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7749 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007750 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007751 case OMPC_to:
7752 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7753 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007754 case OMPC_from:
7755 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7756 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007757 case OMPC_use_device_ptr:
7758 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7759 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007760 case OMPC_is_device_ptr:
7761 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7762 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007763 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007764 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007765 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007766 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007767 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007768 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007769 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007770 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007771 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007772 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007773 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007774 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007775 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007776 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007777 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007778 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007779 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007780 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007781 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007782 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007783 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007784 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007785 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007786 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007787 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007788 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007789 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007790 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007791 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007792 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007793 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007794 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007795 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007796 llvm_unreachable("Clause is not allowed.");
7797 }
7798 return Res;
7799}
7800
Alexey Bataev90c228f2016-02-08 09:29:13 +00007801ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007802 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007803 ExprResult Res = BuildDeclRefExpr(
7804 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7805 if (!Res.isUsable())
7806 return ExprError();
7807 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7808 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7809 if (!Res.isUsable())
7810 return ExprError();
7811 }
7812 if (VK != VK_LValue && Res.get()->isGLValue()) {
7813 Res = DefaultLvalueConversion(Res.get());
7814 if (!Res.isUsable())
7815 return ExprError();
7816 }
7817 return Res;
7818}
7819
Alexey Bataev60da77e2016-02-29 05:54:20 +00007820static std::pair<ValueDecl *, bool>
7821getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7822 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007823 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7824 RefExpr->containsUnexpandedParameterPack())
7825 return std::make_pair(nullptr, true);
7826
Alexey Bataevd985eda2016-02-10 11:29:16 +00007827 // OpenMP [3.1, C/C++]
7828 // A list item is a variable name.
7829 // OpenMP [2.9.3.3, Restrictions, p.1]
7830 // A variable that is part of another variable (as an array or
7831 // structure element) cannot appear in a private clause.
7832 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007833 enum {
7834 NoArrayExpr = -1,
7835 ArraySubscript = 0,
7836 OMPArraySection = 1
7837 } IsArrayExpr = NoArrayExpr;
7838 if (AllowArraySection) {
7839 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7840 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7841 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7842 Base = TempASE->getBase()->IgnoreParenImpCasts();
7843 RefExpr = Base;
7844 IsArrayExpr = ArraySubscript;
7845 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7846 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7847 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7848 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7849 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7850 Base = TempASE->getBase()->IgnoreParenImpCasts();
7851 RefExpr = Base;
7852 IsArrayExpr = OMPArraySection;
7853 }
7854 }
7855 ELoc = RefExpr->getExprLoc();
7856 ERange = RefExpr->getSourceRange();
7857 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007858 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7859 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7860 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7861 (S.getCurrentThisType().isNull() || !ME ||
7862 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7863 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007864 if (IsArrayExpr != NoArrayExpr)
7865 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7866 << ERange;
7867 else {
7868 S.Diag(ELoc,
7869 AllowArraySection
7870 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7871 : diag::err_omp_expected_var_name_member_expr)
7872 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7873 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007874 return std::make_pair(nullptr, false);
7875 }
7876 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7877}
7878
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007879OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7880 SourceLocation StartLoc,
7881 SourceLocation LParenLoc,
7882 SourceLocation EndLoc) {
7883 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007884 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007885 for (auto &RefExpr : VarList) {
7886 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007887 SourceLocation ELoc;
7888 SourceRange ERange;
7889 Expr *SimpleRefExpr = RefExpr;
7890 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007891 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007892 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007893 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007894 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007895 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007896 ValueDecl *D = Res.first;
7897 if (!D)
7898 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007899
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007900 QualType Type = D->getType();
7901 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007902
7903 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7904 // A variable that appears in a private clause must not have an incomplete
7905 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007906 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007907 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007908 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007909
Alexey Bataev758e55e2013-09-06 18:03:48 +00007910 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7911 // in a Construct]
7912 // Variables with the predetermined data-sharing attributes may not be
7913 // listed in data-sharing attributes clauses, except for the cases
7914 // listed below. For these exceptions only, listing a predetermined
7915 // variable in a data-sharing attribute clause is allowed and overrides
7916 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007917 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007918 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007919 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7920 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007921 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007922 continue;
7923 }
7924
Kelvin Libf594a52016-12-17 05:48:59 +00007925 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007926 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007927 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007928 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007929 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7930 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007931 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007932 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007933 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007934 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007935 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007936 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007937 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007938 continue;
7939 }
7940
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007941 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7942 // A list item cannot appear in both a map clause and a data-sharing
7943 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007944 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007945 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007946 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007947 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007948 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007949 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007950 CurrDir == OMPD_target_parallel_for_simd ||
7951 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007952 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007953 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007954 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007955 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7956 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7957 ConflictKind = WhereFoundClauseKind;
7958 return true;
7959 })) {
7960 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007961 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007962 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007963 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007964 ReportOriginalDSA(*this, DSAStack, D, DVar);
7965 continue;
7966 }
7967 }
7968
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007969 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7970 // A variable of class type (or array thereof) that appears in a private
7971 // clause requires an accessible, unambiguous default constructor for the
7972 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007973 // Generate helper private variable and initialize it with the default
7974 // value. The address of the original variable is replaced by the address of
7975 // the new private variable in CodeGen. This new variable is not added to
7976 // IdResolver, so the code in the OpenMP region uses original variable for
7977 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007978 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007979 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7980 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00007981 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007982 if (VDPrivate->isInvalidDecl())
7983 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007984 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007985 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007986
Alexey Bataev90c228f2016-02-08 09:29:13 +00007987 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007988 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007989 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007990 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007991 Vars.push_back((VD || CurContext->isDependentContext())
7992 ? RefExpr->IgnoreParens()
7993 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007994 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007995 }
7996
Alexey Bataeved09d242014-05-28 05:53:51 +00007997 if (Vars.empty())
7998 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007999
Alexey Bataev03b340a2014-10-21 03:16:40 +00008000 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8001 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008002}
8003
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008004namespace {
8005class DiagsUninitializedSeveretyRAII {
8006private:
8007 DiagnosticsEngine &Diags;
8008 SourceLocation SavedLoc;
8009 bool IsIgnored;
8010
8011public:
8012 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8013 bool IsIgnored)
8014 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8015 if (!IsIgnored) {
8016 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8017 /*Map*/ diag::Severity::Ignored, Loc);
8018 }
8019 }
8020 ~DiagsUninitializedSeveretyRAII() {
8021 if (!IsIgnored)
8022 Diags.popMappings(SavedLoc);
8023 }
8024};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008025}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008026
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008027OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8028 SourceLocation StartLoc,
8029 SourceLocation LParenLoc,
8030 SourceLocation EndLoc) {
8031 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008032 SmallVector<Expr *, 8> PrivateCopies;
8033 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008034 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008035 bool IsImplicitClause =
8036 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8037 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8038
Alexey Bataeved09d242014-05-28 05:53:51 +00008039 for (auto &RefExpr : VarList) {
8040 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008041 SourceLocation ELoc;
8042 SourceRange ERange;
8043 Expr *SimpleRefExpr = RefExpr;
8044 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008045 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008046 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008047 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008048 PrivateCopies.push_back(nullptr);
8049 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008050 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008051 ValueDecl *D = Res.first;
8052 if (!D)
8053 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008054
Alexey Bataev60da77e2016-02-29 05:54:20 +00008055 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008056 QualType Type = D->getType();
8057 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008058
8059 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8060 // A variable that appears in a private clause must not have an incomplete
8061 // type or a reference type.
8062 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008063 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008064 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008065 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008066
8067 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8068 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008069 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008070 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008071 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008072
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008073 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008074 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008075 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008076 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008077 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008078 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008079 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8080 // A list item that specifies a given variable may not appear in more
8081 // than one clause on the same directive, except that a variable may be
8082 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008083 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00008084 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008085 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008086 << getOpenMPClauseName(DVar.CKind)
8087 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008088 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008089 continue;
8090 }
8091
8092 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8093 // in a Construct]
8094 // Variables with the predetermined data-sharing attributes may not be
8095 // listed in data-sharing attributes clauses, except for the cases
8096 // listed below. For these exceptions only, listing a predetermined
8097 // variable in a data-sharing attribute clause is allowed and overrides
8098 // the variable's predetermined data-sharing attributes.
8099 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8100 // in a Construct, C/C++, p.2]
8101 // Variables with const-qualified type having no mutable member may be
8102 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008103 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008104 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8105 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008106 << getOpenMPClauseName(DVar.CKind)
8107 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008108 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008109 continue;
8110 }
8111
Alexey Bataevf29276e2014-06-18 04:14:57 +00008112 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008113 // OpenMP [2.9.3.4, Restrictions, p.2]
8114 // A list item that is private within a parallel region must not appear
8115 // in a firstprivate clause on a worksharing construct if any of the
8116 // worksharing regions arising from the worksharing construct ever bind
8117 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008118 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008119 !isOpenMPParallelDirective(CurrDir) &&
8120 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008121 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008122 if (DVar.CKind != OMPC_shared &&
8123 (isOpenMPParallelDirective(DVar.DKind) ||
8124 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008125 Diag(ELoc, diag::err_omp_required_access)
8126 << getOpenMPClauseName(OMPC_firstprivate)
8127 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008128 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008129 continue;
8130 }
8131 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008132 // OpenMP [2.9.3.4, Restrictions, p.3]
8133 // A list item that appears in a reduction clause of a parallel construct
8134 // must not appear in a firstprivate clause on a worksharing or task
8135 // construct if any of the worksharing or task regions arising from the
8136 // worksharing or task construct ever bind to any of the parallel regions
8137 // arising from the parallel construct.
8138 // OpenMP [2.9.3.4, Restrictions, p.4]
8139 // A list item that appears in a reduction clause in worksharing
8140 // construct must not appear in a firstprivate clause in a task construct
8141 // encountered during execution of any of the worksharing regions arising
8142 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008143 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008144 DVar = DSAStack->hasInnermostDSA(
8145 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8146 [](OpenMPDirectiveKind K) -> bool {
8147 return isOpenMPParallelDirective(K) ||
8148 isOpenMPWorksharingDirective(K);
8149 },
8150 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008151 if (DVar.CKind == OMPC_reduction &&
8152 (isOpenMPParallelDirective(DVar.DKind) ||
8153 isOpenMPWorksharingDirective(DVar.DKind))) {
8154 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8155 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008156 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008157 continue;
8158 }
8159 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008160
8161 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8162 // A list item that is private within a teams region must not appear in a
8163 // firstprivate clause on a distribute construct if any of the distribute
8164 // regions arising from the distribute construct ever bind to any of the
8165 // teams regions arising from the teams construct.
8166 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8167 // A list item that appears in a reduction clause of a teams construct
8168 // must not appear in a firstprivate clause on a distribute construct if
8169 // any of the distribute regions arising from the distribute construct
8170 // ever bind to any of the teams regions arising from the teams construct.
8171 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8172 // A list item may appear in a firstprivate or lastprivate clause but not
8173 // both.
8174 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008175 DVar = DSAStack->hasInnermostDSA(
8176 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8177 [](OpenMPDirectiveKind K) -> bool {
8178 return isOpenMPTeamsDirective(K);
8179 },
8180 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008181 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8182 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008183 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008184 continue;
8185 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008186 DVar = DSAStack->hasInnermostDSA(
8187 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8188 [](OpenMPDirectiveKind K) -> bool {
8189 return isOpenMPTeamsDirective(K);
8190 },
8191 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008192 if (DVar.CKind == OMPC_reduction &&
8193 isOpenMPTeamsDirective(DVar.DKind)) {
8194 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008195 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008196 continue;
8197 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008198 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008199 if (DVar.CKind == OMPC_lastprivate) {
8200 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008201 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008202 continue;
8203 }
8204 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008205 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8206 // A list item cannot appear in both a map clause and a data-sharing
8207 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008208 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008209 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008210 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008211 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008212 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008213 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008214 CurrDir == OMPD_target_parallel_for_simd ||
8215 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008216 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008217 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008218 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008219 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8220 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8221 ConflictKind = WhereFoundClauseKind;
8222 return true;
8223 })) {
8224 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008225 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008226 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008227 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8228 ReportOriginalDSA(*this, DSAStack, D, DVar);
8229 continue;
8230 }
8231 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008232 }
8233
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008234 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008235 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008236 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008237 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8238 << getOpenMPClauseName(OMPC_firstprivate) << Type
8239 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8240 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008241 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008242 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008243 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008244 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008245 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008246 continue;
8247 }
8248
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008249 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008250 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8251 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008252 // Generate helper private variable and initialize it with the value of the
8253 // original variable. The address of the original variable is replaced by
8254 // the address of the new private variable in the CodeGen. This new variable
8255 // is not added to IdResolver, so the code in the OpenMP region uses
8256 // original variable for proper diagnostics and variable capturing.
8257 Expr *VDInitRefExpr = nullptr;
8258 // For arrays generate initializer for single element and replace it by the
8259 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008260 if (Type->isArrayType()) {
8261 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008262 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008263 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008264 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008265 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008266 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008267 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008268 InitializedEntity Entity =
8269 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008270 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8271
8272 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8273 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8274 if (Result.isInvalid())
8275 VDPrivate->setInvalidDecl();
8276 else
8277 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008278 // Remove temp variable declaration.
8279 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008280 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008281 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8282 ".firstprivate.temp");
8283 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8284 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008285 AddInitializerToDecl(VDPrivate,
8286 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008287 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008288 }
8289 if (VDPrivate->isInvalidDecl()) {
8290 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008291 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008292 diag::note_omp_task_predetermined_firstprivate_here);
8293 }
8294 continue;
8295 }
8296 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008297 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008298 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8299 RefExpr->getExprLoc());
8300 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008301 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008302 if (TopDVar.CKind == OMPC_lastprivate)
8303 Ref = TopDVar.PrivateCopy;
8304 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008305 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008306 if (!IsOpenMPCapturedDecl(D))
8307 ExprCaptures.push_back(Ref->getDecl());
8308 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008309 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008310 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008311 Vars.push_back((VD || CurContext->isDependentContext())
8312 ? RefExpr->IgnoreParens()
8313 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008314 PrivateCopies.push_back(VDPrivateRefExpr);
8315 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008316 }
8317
Alexey Bataeved09d242014-05-28 05:53:51 +00008318 if (Vars.empty())
8319 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008320
8321 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008322 Vars, PrivateCopies, Inits,
8323 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008324}
8325
Alexander Musman1bb328c2014-06-04 13:06:39 +00008326OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8327 SourceLocation StartLoc,
8328 SourceLocation LParenLoc,
8329 SourceLocation EndLoc) {
8330 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008331 SmallVector<Expr *, 8> SrcExprs;
8332 SmallVector<Expr *, 8> DstExprs;
8333 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008334 SmallVector<Decl *, 4> ExprCaptures;
8335 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008336 for (auto &RefExpr : VarList) {
8337 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008338 SourceLocation ELoc;
8339 SourceRange ERange;
8340 Expr *SimpleRefExpr = RefExpr;
8341 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008342 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008343 // It will be analyzed later.
8344 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008345 SrcExprs.push_back(nullptr);
8346 DstExprs.push_back(nullptr);
8347 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008348 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008349 ValueDecl *D = Res.first;
8350 if (!D)
8351 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008352
Alexey Bataev74caaf22016-02-20 04:09:36 +00008353 QualType Type = D->getType();
8354 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008355
8356 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8357 // A variable that appears in a lastprivate clause must not have an
8358 // incomplete type or a reference type.
8359 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008360 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008361 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008362 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008363
8364 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8365 // in a Construct]
8366 // Variables with the predetermined data-sharing attributes may not be
8367 // listed in data-sharing attributes clauses, except for the cases
8368 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008369 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008370 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8371 DVar.CKind != OMPC_firstprivate &&
8372 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8373 Diag(ELoc, diag::err_omp_wrong_dsa)
8374 << getOpenMPClauseName(DVar.CKind)
8375 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008376 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008377 continue;
8378 }
8379
Alexey Bataevf29276e2014-06-18 04:14:57 +00008380 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8381 // OpenMP [2.14.3.5, Restrictions, p.2]
8382 // A list item that is private within a parallel region, or that appears in
8383 // the reduction clause of a parallel construct, must not appear in a
8384 // lastprivate clause on a worksharing construct if any of the corresponding
8385 // worksharing regions ever binds to any of the corresponding parallel
8386 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008387 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008388 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008389 !isOpenMPParallelDirective(CurrDir) &&
8390 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008391 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008392 if (DVar.CKind != OMPC_shared) {
8393 Diag(ELoc, diag::err_omp_required_access)
8394 << getOpenMPClauseName(OMPC_lastprivate)
8395 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008396 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008397 continue;
8398 }
8399 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008400
8401 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8402 // A list item may appear in a firstprivate or lastprivate clause but not
8403 // both.
8404 if (CurrDir == OMPD_distribute) {
8405 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8406 if (DVar.CKind == OMPC_firstprivate) {
8407 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8408 ReportOriginalDSA(*this, DSAStack, D, DVar);
8409 continue;
8410 }
8411 }
8412
Alexander Musman1bb328c2014-06-04 13:06:39 +00008413 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008414 // A variable of class type (or array thereof) that appears in a
8415 // lastprivate clause requires an accessible, unambiguous default
8416 // constructor for the class type, unless the list item is also specified
8417 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008418 // A variable of class type (or array thereof) that appears in a
8419 // lastprivate clause requires an accessible, unambiguous copy assignment
8420 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008421 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008422 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008423 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008424 D->hasAttrs() ? &D->getAttrs() : nullptr);
8425 auto *PseudoSrcExpr =
8426 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008427 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008428 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008429 D->hasAttrs() ? &D->getAttrs() : nullptr);
8430 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008431 // For arrays generate assignment operation for single element and replace
8432 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008433 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008434 PseudoDstExpr, PseudoSrcExpr);
8435 if (AssignmentOp.isInvalid())
8436 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008437 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008438 /*DiscardedValue=*/true);
8439 if (AssignmentOp.isInvalid())
8440 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008441
Alexey Bataev74caaf22016-02-20 04:09:36 +00008442 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008443 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008444 if (TopDVar.CKind == OMPC_firstprivate)
8445 Ref = TopDVar.PrivateCopy;
8446 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008447 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008448 if (!IsOpenMPCapturedDecl(D))
8449 ExprCaptures.push_back(Ref->getDecl());
8450 }
8451 if (TopDVar.CKind == OMPC_firstprivate ||
8452 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008453 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008454 ExprResult RefRes = DefaultLvalueConversion(Ref);
8455 if (!RefRes.isUsable())
8456 continue;
8457 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008458 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8459 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008460 if (!PostUpdateRes.isUsable())
8461 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008462 ExprPostUpdates.push_back(
8463 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008464 }
8465 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008466 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008467 Vars.push_back((VD || CurContext->isDependentContext())
8468 ? RefExpr->IgnoreParens()
8469 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008470 SrcExprs.push_back(PseudoSrcExpr);
8471 DstExprs.push_back(PseudoDstExpr);
8472 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008473 }
8474
8475 if (Vars.empty())
8476 return nullptr;
8477
8478 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008479 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008480 buildPreInits(Context, ExprCaptures),
8481 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008482}
8483
Alexey Bataev758e55e2013-09-06 18:03:48 +00008484OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8485 SourceLocation StartLoc,
8486 SourceLocation LParenLoc,
8487 SourceLocation EndLoc) {
8488 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008489 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008490 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008491 SourceLocation ELoc;
8492 SourceRange ERange;
8493 Expr *SimpleRefExpr = RefExpr;
8494 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008495 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008496 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008497 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008498 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008499 ValueDecl *D = Res.first;
8500 if (!D)
8501 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008502
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008503 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008504 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8505 // in a Construct]
8506 // Variables with the predetermined data-sharing attributes may not be
8507 // listed in data-sharing attributes clauses, except for the cases
8508 // listed below. For these exceptions only, listing a predetermined
8509 // variable in a data-sharing attribute clause is allowed and overrides
8510 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008511 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008512 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8513 DVar.RefExpr) {
8514 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8515 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008516 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008517 continue;
8518 }
8519
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008520 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008521 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008522 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008523 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008524 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8525 ? RefExpr->IgnoreParens()
8526 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008527 }
8528
Alexey Bataeved09d242014-05-28 05:53:51 +00008529 if (Vars.empty())
8530 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008531
8532 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8533}
8534
Alexey Bataevc5e02582014-06-16 07:08:35 +00008535namespace {
8536class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8537 DSAStackTy *Stack;
8538
8539public:
8540 bool VisitDeclRefExpr(DeclRefExpr *E) {
8541 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008542 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008543 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8544 return false;
8545 if (DVar.CKind != OMPC_unknown)
8546 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008547 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8548 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8549 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008550 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008551 return true;
8552 return false;
8553 }
8554 return false;
8555 }
8556 bool VisitStmt(Stmt *S) {
8557 for (auto Child : S->children()) {
8558 if (Child && Visit(Child))
8559 return true;
8560 }
8561 return false;
8562 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008563 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008564};
Alexey Bataev23b69422014-06-18 07:08:49 +00008565} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008566
Alexey Bataev60da77e2016-02-29 05:54:20 +00008567namespace {
8568// Transform MemberExpression for specified FieldDecl of current class to
8569// DeclRefExpr to specified OMPCapturedExprDecl.
8570class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8571 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8572 ValueDecl *Field;
8573 DeclRefExpr *CapturedExpr;
8574
8575public:
8576 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8577 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8578
8579 ExprResult TransformMemberExpr(MemberExpr *E) {
8580 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8581 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008582 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008583 return CapturedExpr;
8584 }
8585 return BaseTransform::TransformMemberExpr(E);
8586 }
8587 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8588};
8589} // namespace
8590
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008591template <typename T>
8592static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8593 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8594 for (auto &Set : Lookups) {
8595 for (auto *D : Set) {
8596 if (auto Res = Gen(cast<ValueDecl>(D)))
8597 return Res;
8598 }
8599 }
8600 return T();
8601}
8602
8603static ExprResult
8604buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8605 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8606 const DeclarationNameInfo &ReductionId, QualType Ty,
8607 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8608 if (ReductionIdScopeSpec.isInvalid())
8609 return ExprError();
8610 SmallVector<UnresolvedSet<8>, 4> Lookups;
8611 if (S) {
8612 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8613 Lookup.suppressDiagnostics();
8614 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8615 auto *D = Lookup.getRepresentativeDecl();
8616 do {
8617 S = S->getParent();
8618 } while (S && !S->isDeclScope(D));
8619 if (S)
8620 S = S->getParent();
8621 Lookups.push_back(UnresolvedSet<8>());
8622 Lookups.back().append(Lookup.begin(), Lookup.end());
8623 Lookup.clear();
8624 }
8625 } else if (auto *ULE =
8626 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8627 Lookups.push_back(UnresolvedSet<8>());
8628 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008629 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008630 if (D == PrevD)
8631 Lookups.push_back(UnresolvedSet<8>());
8632 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8633 Lookups.back().addDecl(DRD);
8634 PrevD = D;
8635 }
8636 }
8637 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8638 Ty->containsUnexpandedParameterPack() ||
8639 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8640 return !D->isInvalidDecl() &&
8641 (D->getType()->isDependentType() ||
8642 D->getType()->isInstantiationDependentType() ||
8643 D->getType()->containsUnexpandedParameterPack());
8644 })) {
8645 UnresolvedSet<8> ResSet;
8646 for (auto &Set : Lookups) {
8647 ResSet.append(Set.begin(), Set.end());
8648 // The last item marks the end of all declarations at the specified scope.
8649 ResSet.addDecl(Set[Set.size() - 1]);
8650 }
8651 return UnresolvedLookupExpr::Create(
8652 SemaRef.Context, /*NamingClass=*/nullptr,
8653 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8654 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8655 }
8656 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8657 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8658 if (!D->isInvalidDecl() &&
8659 SemaRef.Context.hasSameType(D->getType(), Ty))
8660 return D;
8661 return nullptr;
8662 }))
8663 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8664 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8665 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8666 if (!D->isInvalidDecl() &&
8667 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8668 !Ty.isMoreQualifiedThan(D->getType()))
8669 return D;
8670 return nullptr;
8671 })) {
8672 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8673 /*DetectVirtual=*/false);
8674 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8675 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8676 VD->getType().getUnqualifiedType()))) {
8677 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8678 /*DiagID=*/0) !=
8679 Sema::AR_inaccessible) {
8680 SemaRef.BuildBasePathArray(Paths, BasePath);
8681 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8682 }
8683 }
8684 }
8685 }
8686 if (ReductionIdScopeSpec.isSet()) {
8687 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8688 return ExprError();
8689 }
8690 return ExprEmpty();
8691}
8692
Alexey Bataevc5e02582014-06-16 07:08:35 +00008693OMPClause *Sema::ActOnOpenMPReductionClause(
8694 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8695 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008696 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8697 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008698 auto DN = ReductionId.getName();
8699 auto OOK = DN.getCXXOverloadedOperator();
8700 BinaryOperatorKind BOK = BO_Comma;
8701
8702 // OpenMP [2.14.3.6, reduction clause]
8703 // C
8704 // reduction-identifier is either an identifier or one of the following
8705 // operators: +, -, *, &, |, ^, && and ||
8706 // C++
8707 // reduction-identifier is either an id-expression or one of the following
8708 // operators: +, -, *, &, |, ^, && and ||
8709 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8710 switch (OOK) {
8711 case OO_Plus:
8712 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008713 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008714 break;
8715 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008716 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008717 break;
8718 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008719 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008720 break;
8721 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008722 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008723 break;
8724 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008725 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008726 break;
8727 case OO_AmpAmp:
8728 BOK = BO_LAnd;
8729 break;
8730 case OO_PipePipe:
8731 BOK = BO_LOr;
8732 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008733 case OO_New:
8734 case OO_Delete:
8735 case OO_Array_New:
8736 case OO_Array_Delete:
8737 case OO_Slash:
8738 case OO_Percent:
8739 case OO_Tilde:
8740 case OO_Exclaim:
8741 case OO_Equal:
8742 case OO_Less:
8743 case OO_Greater:
8744 case OO_LessEqual:
8745 case OO_GreaterEqual:
8746 case OO_PlusEqual:
8747 case OO_MinusEqual:
8748 case OO_StarEqual:
8749 case OO_SlashEqual:
8750 case OO_PercentEqual:
8751 case OO_CaretEqual:
8752 case OO_AmpEqual:
8753 case OO_PipeEqual:
8754 case OO_LessLess:
8755 case OO_GreaterGreater:
8756 case OO_LessLessEqual:
8757 case OO_GreaterGreaterEqual:
8758 case OO_EqualEqual:
8759 case OO_ExclaimEqual:
8760 case OO_PlusPlus:
8761 case OO_MinusMinus:
8762 case OO_Comma:
8763 case OO_ArrowStar:
8764 case OO_Arrow:
8765 case OO_Call:
8766 case OO_Subscript:
8767 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008768 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008769 case NUM_OVERLOADED_OPERATORS:
8770 llvm_unreachable("Unexpected reduction identifier");
8771 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008772 if (auto II = DN.getAsIdentifierInfo()) {
8773 if (II->isStr("max"))
8774 BOK = BO_GT;
8775 else if (II->isStr("min"))
8776 BOK = BO_LT;
8777 }
8778 break;
8779 }
8780 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008781 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008782 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008783 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008784
8785 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008786 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008787 SmallVector<Expr *, 8> LHSs;
8788 SmallVector<Expr *, 8> RHSs;
8789 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008790 SmallVector<Decl *, 4> ExprCaptures;
8791 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008792 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8793 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008794 for (auto RefExpr : VarList) {
8795 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008796 // OpenMP [2.1, C/C++]
8797 // A list item is a variable or array section, subject to the restrictions
8798 // specified in Section 2.4 on page 42 and in each of the sections
8799 // describing clauses and directives for which a list appears.
8800 // OpenMP [2.14.3.3, Restrictions, p.1]
8801 // A variable that is part of another variable (as an array or
8802 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008803 if (!FirstIter && IR != ER)
8804 ++IR;
8805 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008806 SourceLocation ELoc;
8807 SourceRange ERange;
8808 Expr *SimpleRefExpr = RefExpr;
8809 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8810 /*AllowArraySection=*/true);
8811 if (Res.second) {
8812 // It will be analyzed later.
8813 Vars.push_back(RefExpr);
8814 Privates.push_back(nullptr);
8815 LHSs.push_back(nullptr);
8816 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008817 // Try to find 'declare reduction' corresponding construct before using
8818 // builtin/overloaded operators.
8819 QualType Type = Context.DependentTy;
8820 CXXCastPath BasePath;
8821 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8822 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8823 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8824 if (CurContext->isDependentContext() &&
8825 (DeclareReductionRef.isUnset() ||
8826 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8827 ReductionOps.push_back(DeclareReductionRef.get());
8828 else
8829 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008830 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008831 ValueDecl *D = Res.first;
8832 if (!D)
8833 continue;
8834
Alexey Bataeva1764212015-09-30 09:22:36 +00008835 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008836 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8837 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8838 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008839 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008840 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008841 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8842 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8843 Type = ATy->getElementType();
8844 else
8845 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008846 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008847 } else
8848 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8849 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008850
Alexey Bataevc5e02582014-06-16 07:08:35 +00008851 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8852 // A variable that appears in a private clause must not have an incomplete
8853 // type or a reference type.
8854 if (RequireCompleteType(ELoc, Type,
8855 diag::err_omp_reduction_incomplete_type))
8856 continue;
8857 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008858 // A list item that appears in a reduction clause must not be
8859 // const-qualified.
8860 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008861 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008862 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008863 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008864 bool IsDecl = !VD ||
8865 VD->isThisDeclarationADefinition(Context) ==
8866 VarDecl::DeclarationOnly;
8867 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008868 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008869 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008870 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008871 continue;
8872 }
8873 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8874 // If a list-item is a reference type then it must bind to the same object
8875 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008876 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008877 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008878 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008879 DSARefChecker Check(DSAStack);
8880 if (Check.Visit(VDDef->getInit())) {
8881 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8882 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8883 continue;
8884 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008885 }
8886 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008887
Alexey Bataevc5e02582014-06-16 07:08:35 +00008888 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8889 // in a Construct]
8890 // Variables with the predetermined data-sharing attributes may not be
8891 // listed in data-sharing attributes clauses, except for the cases
8892 // listed below. For these exceptions only, listing a predetermined
8893 // variable in a data-sharing attribute clause is allowed and overrides
8894 // the variable's predetermined data-sharing attributes.
8895 // OpenMP [2.14.3.6, Restrictions, p.3]
8896 // Any number of reduction clauses can be specified on the directive,
8897 // but a list item can appear only once in the reduction clauses for that
8898 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008899 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008900 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008901 if (DVar.CKind == OMPC_reduction) {
8902 Diag(ELoc, diag::err_omp_once_referenced)
8903 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008904 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008905 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008906 } else if (DVar.CKind != OMPC_unknown) {
8907 Diag(ELoc, diag::err_omp_wrong_dsa)
8908 << getOpenMPClauseName(DVar.CKind)
8909 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008910 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008911 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008912 }
8913
8914 // OpenMP [2.14.3.6, Restrictions, p.1]
8915 // A list item that appears in a reduction clause of a worksharing
8916 // construct must be shared in the parallel regions to which any of the
8917 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008918 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8919 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008920 !isOpenMPParallelDirective(CurrDir) &&
8921 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008922 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008923 if (DVar.CKind != OMPC_shared) {
8924 Diag(ELoc, diag::err_omp_required_access)
8925 << getOpenMPClauseName(OMPC_reduction)
8926 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008927 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008928 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008929 }
8930 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008931
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008932 // Try to find 'declare reduction' corresponding construct before using
8933 // builtin/overloaded operators.
8934 CXXCastPath BasePath;
8935 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8936 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8937 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8938 if (DeclareReductionRef.isInvalid())
8939 continue;
8940 if (CurContext->isDependentContext() &&
8941 (DeclareReductionRef.isUnset() ||
8942 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8943 Vars.push_back(RefExpr);
8944 Privates.push_back(nullptr);
8945 LHSs.push_back(nullptr);
8946 RHSs.push_back(nullptr);
8947 ReductionOps.push_back(DeclareReductionRef.get());
8948 continue;
8949 }
8950 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8951 // Not allowed reduction identifier is found.
8952 Diag(ReductionId.getLocStart(),
8953 diag::err_omp_unknown_reduction_identifier)
8954 << Type << ReductionIdRange;
8955 continue;
8956 }
8957
8958 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8959 // The type of a list item that appears in a reduction clause must be valid
8960 // for the reduction-identifier. For a max or min reduction in C, the type
8961 // of the list item must be an allowed arithmetic data type: char, int,
8962 // float, double, or _Bool, possibly modified with long, short, signed, or
8963 // unsigned. For a max or min reduction in C++, the type of the list item
8964 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8965 // double, or bool, possibly modified with long, short, signed, or unsigned.
8966 if (DeclareReductionRef.isUnset()) {
8967 if ((BOK == BO_GT || BOK == BO_LT) &&
8968 !(Type->isScalarType() ||
8969 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8970 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8971 << getLangOpts().CPlusPlus;
8972 if (!ASE && !OASE) {
8973 bool IsDecl = !VD ||
8974 VD->isThisDeclarationADefinition(Context) ==
8975 VarDecl::DeclarationOnly;
8976 Diag(D->getLocation(),
8977 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8978 << D;
8979 }
8980 continue;
8981 }
8982 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8983 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8984 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8985 if (!ASE && !OASE) {
8986 bool IsDecl = !VD ||
8987 VD->isThisDeclarationADefinition(Context) ==
8988 VarDecl::DeclarationOnly;
8989 Diag(D->getLocation(),
8990 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8991 << D;
8992 }
8993 continue;
8994 }
8995 }
8996
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008997 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008998 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008999 D->hasAttrs() ? &D->getAttrs() : nullptr);
9000 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9001 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009002 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009003 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009004 (!ASE &&
9005 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009006 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009007 // Create pseudo array type for private copy. The size for this array will
9008 // be generated during codegen.
9009 // For array subscripts or single variables Private Ty is the same as Type
9010 // (type of the variable or single array element).
9011 PrivateTy = Context.getVariableArrayType(
9012 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9013 Context.getSizeType(), VK_RValue),
9014 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009015 } else if (!ASE && !OASE &&
9016 Context.getAsArrayType(D->getType().getNonReferenceType()))
9017 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009018 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009019 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9020 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009021 // Add initializer for private variable.
9022 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009023 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9024 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9025 if (DeclareReductionRef.isUsable()) {
9026 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9027 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9028 if (DRD->getInitializer()) {
9029 Init = DRDRef;
9030 RHSVD->setInit(DRDRef);
9031 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009032 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009033 } else {
9034 switch (BOK) {
9035 case BO_Add:
9036 case BO_Xor:
9037 case BO_Or:
9038 case BO_LOr:
9039 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9040 if (Type->isScalarType() || Type->isAnyComplexType())
9041 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9042 break;
9043 case BO_Mul:
9044 case BO_LAnd:
9045 if (Type->isScalarType() || Type->isAnyComplexType()) {
9046 // '*' and '&&' reduction ops - initializer is '1'.
9047 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009048 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009049 break;
9050 case BO_And: {
9051 // '&' reduction op - initializer is '~0'.
9052 QualType OrigType = Type;
9053 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9054 Type = ComplexTy->getElementType();
9055 if (Type->isRealFloatingType()) {
9056 llvm::APFloat InitValue =
9057 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9058 /*isIEEE=*/true);
9059 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9060 Type, ELoc);
9061 } else if (Type->isScalarType()) {
9062 auto Size = Context.getTypeSize(Type);
9063 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9064 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9065 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9066 }
9067 if (Init && OrigType->isAnyComplexType()) {
9068 // Init = 0xFFFF + 0xFFFFi;
9069 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9070 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9071 }
9072 Type = OrigType;
9073 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009074 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009075 case BO_LT:
9076 case BO_GT: {
9077 // 'min' reduction op - initializer is 'Largest representable number in
9078 // the reduction list item type'.
9079 // 'max' reduction op - initializer is 'Least representable number in
9080 // the reduction list item type'.
9081 if (Type->isIntegerType() || Type->isPointerType()) {
9082 bool IsSigned = Type->hasSignedIntegerRepresentation();
9083 auto Size = Context.getTypeSize(Type);
9084 QualType IntTy =
9085 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9086 llvm::APInt InitValue =
9087 (BOK != BO_LT)
9088 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9089 : llvm::APInt::getMinValue(Size)
9090 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9091 : llvm::APInt::getMaxValue(Size);
9092 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9093 if (Type->isPointerType()) {
9094 // Cast to pointer type.
9095 auto CastExpr = BuildCStyleCastExpr(
9096 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9097 SourceLocation(), Init);
9098 if (CastExpr.isInvalid())
9099 continue;
9100 Init = CastExpr.get();
9101 }
9102 } else if (Type->isRealFloatingType()) {
9103 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9104 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9105 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9106 Type, ELoc);
9107 }
9108 break;
9109 }
9110 case BO_PtrMemD:
9111 case BO_PtrMemI:
9112 case BO_MulAssign:
9113 case BO_Div:
9114 case BO_Rem:
9115 case BO_Sub:
9116 case BO_Shl:
9117 case BO_Shr:
9118 case BO_LE:
9119 case BO_GE:
9120 case BO_EQ:
9121 case BO_NE:
9122 case BO_AndAssign:
9123 case BO_XorAssign:
9124 case BO_OrAssign:
9125 case BO_Assign:
9126 case BO_AddAssign:
9127 case BO_SubAssign:
9128 case BO_DivAssign:
9129 case BO_RemAssign:
9130 case BO_ShlAssign:
9131 case BO_ShrAssign:
9132 case BO_Comma:
9133 llvm_unreachable("Unexpected reduction operation");
9134 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009135 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009136 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009137 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009138 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009139 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009140 if (RHSVD->isInvalidDecl())
9141 continue;
9142 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009143 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9144 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009145 bool IsDecl =
9146 !VD ||
9147 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9148 Diag(D->getLocation(),
9149 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9150 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009151 continue;
9152 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009153 // Store initializer for single element in private copy. Will be used during
9154 // codegen.
9155 PrivateVD->setInit(RHSVD->getInit());
9156 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009157 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009158 ExprResult ReductionOp;
9159 if (DeclareReductionRef.isUsable()) {
9160 QualType RedTy = DeclareReductionRef.get()->getType();
9161 QualType PtrRedTy = Context.getPointerType(RedTy);
9162 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9163 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9164 if (!BasePath.empty()) {
9165 LHS = DefaultLvalueConversion(LHS.get());
9166 RHS = DefaultLvalueConversion(RHS.get());
9167 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9168 CK_UncheckedDerivedToBase, LHS.get(),
9169 &BasePath, LHS.get()->getValueKind());
9170 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9171 CK_UncheckedDerivedToBase, RHS.get(),
9172 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009173 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009174 FunctionProtoType::ExtProtoInfo EPI;
9175 QualType Params[] = {PtrRedTy, PtrRedTy};
9176 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9177 auto *OVE = new (Context) OpaqueValueExpr(
9178 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9179 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9180 Expr *Args[] = {LHS.get(), RHS.get()};
9181 ReductionOp = new (Context)
9182 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9183 } else {
9184 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9185 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9186 if (ReductionOp.isUsable()) {
9187 if (BOK != BO_LT && BOK != BO_GT) {
9188 ReductionOp =
9189 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9190 BO_Assign, LHSDRE, ReductionOp.get());
9191 } else {
9192 auto *ConditionalOp = new (Context) ConditionalOperator(
9193 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9194 RHSDRE, Type, VK_LValue, OK_Ordinary);
9195 ReductionOp =
9196 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9197 BO_Assign, LHSDRE, ConditionalOp);
9198 }
9199 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9200 }
9201 if (ReductionOp.isInvalid())
9202 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009203 }
9204
Alexey Bataev60da77e2016-02-29 05:54:20 +00009205 DeclRefExpr *Ref = nullptr;
9206 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009207 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009208 if (ASE || OASE) {
9209 TransformExprToCaptures RebuildToCapture(*this, D);
9210 VarsExpr =
9211 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9212 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009213 } else {
9214 VarsExpr = Ref =
9215 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009216 }
9217 if (!IsOpenMPCapturedDecl(D)) {
9218 ExprCaptures.push_back(Ref->getDecl());
9219 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9220 ExprResult RefRes = DefaultLvalueConversion(Ref);
9221 if (!RefRes.isUsable())
9222 continue;
9223 ExprResult PostUpdateRes =
9224 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9225 SimpleRefExpr, RefRes.get());
9226 if (!PostUpdateRes.isUsable())
9227 continue;
9228 ExprPostUpdates.push_back(
9229 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009230 }
9231 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009232 }
9233 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9234 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009235 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009236 LHSs.push_back(LHSDRE);
9237 RHSs.push_back(RHSDRE);
9238 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009239 }
9240
9241 if (Vars.empty())
9242 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009243
Alexey Bataevc5e02582014-06-16 07:08:35 +00009244 return OMPReductionClause::Create(
9245 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009246 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009247 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9248 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009249}
9250
Alexey Bataevecba70f2016-04-12 11:02:11 +00009251bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9252 SourceLocation LinLoc) {
9253 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9254 LinKind == OMPC_LINEAR_unknown) {
9255 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9256 return true;
9257 }
9258 return false;
9259}
9260
9261bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9262 OpenMPLinearClauseKind LinKind,
9263 QualType Type) {
9264 auto *VD = dyn_cast_or_null<VarDecl>(D);
9265 // A variable must not have an incomplete type or a reference type.
9266 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9267 return true;
9268 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9269 !Type->isReferenceType()) {
9270 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9271 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9272 return true;
9273 }
9274 Type = Type.getNonReferenceType();
9275
9276 // A list item must not be const-qualified.
9277 if (Type.isConstant(Context)) {
9278 Diag(ELoc, diag::err_omp_const_variable)
9279 << getOpenMPClauseName(OMPC_linear);
9280 if (D) {
9281 bool IsDecl =
9282 !VD ||
9283 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9284 Diag(D->getLocation(),
9285 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9286 << D;
9287 }
9288 return true;
9289 }
9290
9291 // A list item must be of integral or pointer type.
9292 Type = Type.getUnqualifiedType().getCanonicalType();
9293 const auto *Ty = Type.getTypePtrOrNull();
9294 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9295 !Ty->isPointerType())) {
9296 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9297 if (D) {
9298 bool IsDecl =
9299 !VD ||
9300 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9301 Diag(D->getLocation(),
9302 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9303 << D;
9304 }
9305 return true;
9306 }
9307 return false;
9308}
9309
Alexey Bataev182227b2015-08-20 10:54:39 +00009310OMPClause *Sema::ActOnOpenMPLinearClause(
9311 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9312 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9313 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009314 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009315 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009316 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009317 SmallVector<Decl *, 4> ExprCaptures;
9318 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009319 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009320 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009321 for (auto &RefExpr : VarList) {
9322 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009323 SourceLocation ELoc;
9324 SourceRange ERange;
9325 Expr *SimpleRefExpr = RefExpr;
9326 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9327 /*AllowArraySection=*/false);
9328 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009329 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009330 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009331 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009332 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009333 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009334 ValueDecl *D = Res.first;
9335 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009336 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009337
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009338 QualType Type = D->getType();
9339 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009340
9341 // OpenMP [2.14.3.7, linear clause]
9342 // A list-item cannot appear in more than one linear clause.
9343 // A list-item that appears in a linear clause cannot appear in any
9344 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009345 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009346 if (DVar.RefExpr) {
9347 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9348 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009349 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009350 continue;
9351 }
9352
Alexey Bataevecba70f2016-04-12 11:02:11 +00009353 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009354 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009355 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009356
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009357 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009358 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9359 D->hasAttrs() ? &D->getAttrs() : nullptr);
9360 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009361 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009362 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009363 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009364 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009365 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009366 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9367 if (!IsOpenMPCapturedDecl(D)) {
9368 ExprCaptures.push_back(Ref->getDecl());
9369 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9370 ExprResult RefRes = DefaultLvalueConversion(Ref);
9371 if (!RefRes.isUsable())
9372 continue;
9373 ExprResult PostUpdateRes =
9374 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9375 SimpleRefExpr, RefRes.get());
9376 if (!PostUpdateRes.isUsable())
9377 continue;
9378 ExprPostUpdates.push_back(
9379 IgnoredValueConversions(PostUpdateRes.get()).get());
9380 }
9381 }
9382 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009383 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009384 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009385 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009386 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009387 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009388 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009389 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9390
9391 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009392 Vars.push_back((VD || CurContext->isDependentContext())
9393 ? RefExpr->IgnoreParens()
9394 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009395 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009396 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009397 }
9398
9399 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009400 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009401
9402 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009403 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009404 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9405 !Step->isInstantiationDependent() &&
9406 !Step->containsUnexpandedParameterPack()) {
9407 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009408 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009409 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009410 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009411 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009412
Alexander Musman3276a272015-03-21 10:12:56 +00009413 // Build var to save the step value.
9414 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009415 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009416 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009417 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009418 ExprResult CalcStep =
9419 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009420 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009421
Alexander Musman8dba6642014-04-22 13:09:42 +00009422 // Warn about zero linear step (it would be probably better specified as
9423 // making corresponding variables 'const').
9424 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009425 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9426 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009427 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9428 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009429 if (!IsConstant && CalcStep.isUsable()) {
9430 // Calculate the step beforehand instead of doing this on each iteration.
9431 // (This is not used if the number of iterations may be kfold-ed).
9432 CalcStepExpr = CalcStep.get();
9433 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009434 }
9435
Alexey Bataev182227b2015-08-20 10:54:39 +00009436 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9437 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009438 StepExpr, CalcStepExpr,
9439 buildPreInits(Context, ExprCaptures),
9440 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009441}
9442
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009443static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9444 Expr *NumIterations, Sema &SemaRef,
9445 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009446 // Walk the vars and build update/final expressions for the CodeGen.
9447 SmallVector<Expr *, 8> Updates;
9448 SmallVector<Expr *, 8> Finals;
9449 Expr *Step = Clause.getStep();
9450 Expr *CalcStep = Clause.getCalcStep();
9451 // OpenMP [2.14.3.7, linear clause]
9452 // If linear-step is not specified it is assumed to be 1.
9453 if (Step == nullptr)
9454 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009455 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009456 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009457 }
Alexander Musman3276a272015-03-21 10:12:56 +00009458 bool HasErrors = false;
9459 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009460 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009461 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009462 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009463 SourceLocation ELoc;
9464 SourceRange ERange;
9465 Expr *SimpleRefExpr = RefExpr;
9466 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9467 /*AllowArraySection=*/false);
9468 ValueDecl *D = Res.first;
9469 if (Res.second || !D) {
9470 Updates.push_back(nullptr);
9471 Finals.push_back(nullptr);
9472 HasErrors = true;
9473 continue;
9474 }
9475 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9476 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9477 ->getMemberDecl();
9478 }
9479 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009480 Expr *InitExpr = *CurInit;
9481
9482 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009483 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009484 Expr *CapturedRef;
9485 if (LinKind == OMPC_LINEAR_uval)
9486 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9487 else
9488 CapturedRef =
9489 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9490 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9491 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009492
9493 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009494 ExprResult Update;
9495 if (!Info.first) {
9496 Update =
9497 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9498 InitExpr, IV, Step, /* Subtract */ false);
9499 } else
9500 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009501 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9502 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009503
9504 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009505 ExprResult Final;
9506 if (!Info.first) {
9507 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9508 InitExpr, NumIterations, Step,
9509 /* Subtract */ false);
9510 } else
9511 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009512 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9513 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009514
Alexander Musman3276a272015-03-21 10:12:56 +00009515 if (!Update.isUsable() || !Final.isUsable()) {
9516 Updates.push_back(nullptr);
9517 Finals.push_back(nullptr);
9518 HasErrors = true;
9519 } else {
9520 Updates.push_back(Update.get());
9521 Finals.push_back(Final.get());
9522 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009523 ++CurInit;
9524 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009525 }
9526 Clause.setUpdates(Updates);
9527 Clause.setFinals(Finals);
9528 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009529}
9530
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009531OMPClause *Sema::ActOnOpenMPAlignedClause(
9532 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9533 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9534
9535 SmallVector<Expr *, 8> Vars;
9536 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009537 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9538 SourceLocation ELoc;
9539 SourceRange ERange;
9540 Expr *SimpleRefExpr = RefExpr;
9541 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9542 /*AllowArraySection=*/false);
9543 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009544 // It will be analyzed later.
9545 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009546 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009547 ValueDecl *D = Res.first;
9548 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009549 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009550
Alexey Bataev1efd1662016-03-29 10:59:56 +00009551 QualType QType = D->getType();
9552 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009553
9554 // OpenMP [2.8.1, simd construct, Restrictions]
9555 // The type of list items appearing in the aligned clause must be
9556 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009557 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009558 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009559 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009560 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009561 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009562 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009563 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009564 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009565 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009566 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009567 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009568 continue;
9569 }
9570
9571 // OpenMP [2.8.1, simd construct, Restrictions]
9572 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009573 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009574 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009575 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9576 << getOpenMPClauseName(OMPC_aligned);
9577 continue;
9578 }
9579
Alexey Bataev1efd1662016-03-29 10:59:56 +00009580 DeclRefExpr *Ref = nullptr;
9581 if (!VD && IsOpenMPCapturedDecl(D))
9582 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9583 Vars.push_back(DefaultFunctionArrayConversion(
9584 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9585 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009586 }
9587
9588 // OpenMP [2.8.1, simd construct, Description]
9589 // The parameter of the aligned clause, alignment, must be a constant
9590 // positive integer expression.
9591 // If no optional parameter is specified, implementation-defined default
9592 // alignments for SIMD instructions on the target platforms are assumed.
9593 if (Alignment != nullptr) {
9594 ExprResult AlignResult =
9595 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9596 if (AlignResult.isInvalid())
9597 return nullptr;
9598 Alignment = AlignResult.get();
9599 }
9600 if (Vars.empty())
9601 return nullptr;
9602
9603 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9604 EndLoc, Vars, Alignment);
9605}
9606
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009607OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9608 SourceLocation StartLoc,
9609 SourceLocation LParenLoc,
9610 SourceLocation EndLoc) {
9611 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009612 SmallVector<Expr *, 8> SrcExprs;
9613 SmallVector<Expr *, 8> DstExprs;
9614 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009615 for (auto &RefExpr : VarList) {
9616 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9617 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009618 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009619 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009620 SrcExprs.push_back(nullptr);
9621 DstExprs.push_back(nullptr);
9622 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009623 continue;
9624 }
9625
Alexey Bataeved09d242014-05-28 05:53:51 +00009626 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009627 // OpenMP [2.1, C/C++]
9628 // A list item is a variable name.
9629 // OpenMP [2.14.4.1, Restrictions, p.1]
9630 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009631 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009632 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009633 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9634 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009635 continue;
9636 }
9637
9638 Decl *D = DE->getDecl();
9639 VarDecl *VD = cast<VarDecl>(D);
9640
9641 QualType Type = VD->getType();
9642 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9643 // It will be analyzed later.
9644 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009645 SrcExprs.push_back(nullptr);
9646 DstExprs.push_back(nullptr);
9647 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009648 continue;
9649 }
9650
9651 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9652 // A list item that appears in a copyin clause must be threadprivate.
9653 if (!DSAStack->isThreadPrivate(VD)) {
9654 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009655 << getOpenMPClauseName(OMPC_copyin)
9656 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009657 continue;
9658 }
9659
9660 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9661 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009662 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009663 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009664 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009665 auto *SrcVD =
9666 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9667 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009668 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009669 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9670 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009671 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9672 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009673 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009674 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009675 // For arrays generate assignment operation for single element and replace
9676 // it by the original array element in CodeGen.
9677 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9678 PseudoDstExpr, PseudoSrcExpr);
9679 if (AssignmentOp.isInvalid())
9680 continue;
9681 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9682 /*DiscardedValue=*/true);
9683 if (AssignmentOp.isInvalid())
9684 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009685
9686 DSAStack->addDSA(VD, DE, OMPC_copyin);
9687 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009688 SrcExprs.push_back(PseudoSrcExpr);
9689 DstExprs.push_back(PseudoDstExpr);
9690 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009691 }
9692
Alexey Bataeved09d242014-05-28 05:53:51 +00009693 if (Vars.empty())
9694 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009695
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009696 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9697 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009698}
9699
Alexey Bataevbae9a792014-06-27 10:37:06 +00009700OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9701 SourceLocation StartLoc,
9702 SourceLocation LParenLoc,
9703 SourceLocation EndLoc) {
9704 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009705 SmallVector<Expr *, 8> SrcExprs;
9706 SmallVector<Expr *, 8> DstExprs;
9707 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009708 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009709 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9710 SourceLocation ELoc;
9711 SourceRange ERange;
9712 Expr *SimpleRefExpr = RefExpr;
9713 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9714 /*AllowArraySection=*/false);
9715 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009716 // It will be analyzed later.
9717 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009718 SrcExprs.push_back(nullptr);
9719 DstExprs.push_back(nullptr);
9720 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009721 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009722 ValueDecl *D = Res.first;
9723 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009724 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009725
Alexey Bataeve122da12016-03-17 10:50:17 +00009726 QualType Type = D->getType();
9727 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009728
9729 // OpenMP [2.14.4.2, Restrictions, p.2]
9730 // A list item that appears in a copyprivate clause may not appear in a
9731 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009732 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9733 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009734 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9735 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009736 Diag(ELoc, diag::err_omp_wrong_dsa)
9737 << getOpenMPClauseName(DVar.CKind)
9738 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009739 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009740 continue;
9741 }
9742
9743 // OpenMP [2.11.4.2, Restrictions, p.1]
9744 // All list items that appear in a copyprivate clause must be either
9745 // threadprivate or private in the enclosing context.
9746 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009747 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009748 if (DVar.CKind == OMPC_shared) {
9749 Diag(ELoc, diag::err_omp_required_access)
9750 << getOpenMPClauseName(OMPC_copyprivate)
9751 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009752 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009753 continue;
9754 }
9755 }
9756 }
9757
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009758 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009759 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009760 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009761 << getOpenMPClauseName(OMPC_copyprivate) << Type
9762 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009763 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009764 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009765 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009766 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009767 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009768 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009769 continue;
9770 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009771
Alexey Bataevbae9a792014-06-27 10:37:06 +00009772 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9773 // A variable of class type (or array thereof) that appears in a
9774 // copyin clause requires an accessible, unambiguous copy assignment
9775 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009776 Type = Context.getBaseElementType(Type.getNonReferenceType())
9777 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009778 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009779 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9780 D->hasAttrs() ? &D->getAttrs() : nullptr);
9781 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009782 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009783 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9784 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009785 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009786 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009787 PseudoDstExpr, PseudoSrcExpr);
9788 if (AssignmentOp.isInvalid())
9789 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009790 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009791 /*DiscardedValue=*/true);
9792 if (AssignmentOp.isInvalid())
9793 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009794
9795 // No need to mark vars as copyprivate, they are already threadprivate or
9796 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009797 assert(VD || IsOpenMPCapturedDecl(D));
9798 Vars.push_back(
9799 VD ? RefExpr->IgnoreParens()
9800 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009801 SrcExprs.push_back(PseudoSrcExpr);
9802 DstExprs.push_back(PseudoDstExpr);
9803 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009804 }
9805
9806 if (Vars.empty())
9807 return nullptr;
9808
Alexey Bataeva63048e2015-03-23 06:18:07 +00009809 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9810 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009811}
9812
Alexey Bataev6125da92014-07-21 11:26:11 +00009813OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9814 SourceLocation StartLoc,
9815 SourceLocation LParenLoc,
9816 SourceLocation EndLoc) {
9817 if (VarList.empty())
9818 return nullptr;
9819
9820 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9821}
Alexey Bataevdea47612014-07-23 07:46:59 +00009822
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009823OMPClause *
9824Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9825 SourceLocation DepLoc, SourceLocation ColonLoc,
9826 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9827 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009828 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009829 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009830 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009831 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009832 return nullptr;
9833 }
9834 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009835 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9836 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009837 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009838 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009839 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9840 /*Last=*/OMPC_DEPEND_unknown, Except)
9841 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009842 return nullptr;
9843 }
9844 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009845 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009846 llvm::APSInt DepCounter(/*BitWidth=*/32);
9847 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9848 if (DepKind == OMPC_DEPEND_sink) {
9849 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9850 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9851 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009852 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009853 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009854 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9855 DSAStack->getParentOrderedRegionParam()) {
9856 for (auto &RefExpr : VarList) {
9857 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009858 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009859 // It will be analyzed later.
9860 Vars.push_back(RefExpr);
9861 continue;
9862 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009863
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009864 SourceLocation ELoc = RefExpr->getExprLoc();
9865 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9866 if (DepKind == OMPC_DEPEND_sink) {
9867 if (DepCounter >= TotalDepCount) {
9868 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9869 continue;
9870 }
9871 ++DepCounter;
9872 // OpenMP [2.13.9, Summary]
9873 // depend(dependence-type : vec), where dependence-type is:
9874 // 'sink' and where vec is the iteration vector, which has the form:
9875 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9876 // where n is the value specified by the ordered clause in the loop
9877 // directive, xi denotes the loop iteration variable of the i-th nested
9878 // loop associated with the loop directive, and di is a constant
9879 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009880 if (CurContext->isDependentContext()) {
9881 // It will be analyzed later.
9882 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009883 continue;
9884 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009885 SimpleExpr = SimpleExpr->IgnoreImplicit();
9886 OverloadedOperatorKind OOK = OO_None;
9887 SourceLocation OOLoc;
9888 Expr *LHS = SimpleExpr;
9889 Expr *RHS = nullptr;
9890 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9891 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9892 OOLoc = BO->getOperatorLoc();
9893 LHS = BO->getLHS()->IgnoreParenImpCasts();
9894 RHS = BO->getRHS()->IgnoreParenImpCasts();
9895 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9896 OOK = OCE->getOperator();
9897 OOLoc = OCE->getOperatorLoc();
9898 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9899 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9900 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9901 OOK = MCE->getMethodDecl()
9902 ->getNameInfo()
9903 .getName()
9904 .getCXXOverloadedOperator();
9905 OOLoc = MCE->getCallee()->getExprLoc();
9906 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9907 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9908 }
9909 SourceLocation ELoc;
9910 SourceRange ERange;
9911 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9912 /*AllowArraySection=*/false);
9913 if (Res.second) {
9914 // It will be analyzed later.
9915 Vars.push_back(RefExpr);
9916 }
9917 ValueDecl *D = Res.first;
9918 if (!D)
9919 continue;
9920
9921 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9922 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9923 continue;
9924 }
9925 if (RHS) {
9926 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9927 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9928 if (RHSRes.isInvalid())
9929 continue;
9930 }
9931 if (!CurContext->isDependentContext() &&
9932 DSAStack->getParentOrderedRegionParam() &&
9933 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9934 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9935 << DSAStack->getParentLoopControlVariable(
9936 DepCounter.getZExtValue());
9937 continue;
9938 }
9939 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009940 } else {
9941 // OpenMP [2.11.1.1, Restrictions, p.3]
9942 // A variable that is part of another variable (such as a field of a
9943 // structure) but is not an array element or an array section cannot
9944 // appear in a depend clause.
9945 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9946 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9947 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9948 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9949 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009950 (ASE &&
9951 !ASE->getBase()
9952 ->getType()
9953 .getNonReferenceType()
9954 ->isPointerType() &&
9955 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009956 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9957 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009958 continue;
9959 }
9960 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009961 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9962 }
9963
9964 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9965 TotalDepCount > VarList.size() &&
9966 DSAStack->getParentOrderedRegionParam()) {
9967 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9968 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9969 }
9970 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9971 Vars.empty())
9972 return nullptr;
9973 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009974 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9975 DepKind, DepLoc, ColonLoc, Vars);
9976 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9977 DSAStack->addDoacrossDependClause(C, OpsOffs);
9978 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009979}
Michael Wonge710d542015-08-07 16:16:36 +00009980
9981OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9982 SourceLocation LParenLoc,
9983 SourceLocation EndLoc) {
9984 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009985
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009986 // OpenMP [2.9.1, Restrictions]
9987 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009988 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9989 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009990 return nullptr;
9991
Michael Wonge710d542015-08-07 16:16:36 +00009992 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9993}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009994
9995static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9996 DSAStackTy *Stack, CXXRecordDecl *RD) {
9997 if (!RD || RD->isInvalidDecl())
9998 return true;
9999
10000 auto QTy = SemaRef.Context.getRecordType(RD);
10001 if (RD->isDynamicClass()) {
10002 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10003 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10004 return false;
10005 }
10006 auto *DC = RD;
10007 bool IsCorrect = true;
10008 for (auto *I : DC->decls()) {
10009 if (I) {
10010 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10011 if (MD->isStatic()) {
10012 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10013 SemaRef.Diag(MD->getLocation(),
10014 diag::note_omp_static_member_in_target);
10015 IsCorrect = false;
10016 }
10017 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10018 if (VD->isStaticDataMember()) {
10019 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10020 SemaRef.Diag(VD->getLocation(),
10021 diag::note_omp_static_member_in_target);
10022 IsCorrect = false;
10023 }
10024 }
10025 }
10026 }
10027
10028 for (auto &I : RD->bases()) {
10029 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10030 I.getType()->getAsCXXRecordDecl()))
10031 IsCorrect = false;
10032 }
10033 return IsCorrect;
10034}
10035
10036static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10037 DSAStackTy *Stack, QualType QTy) {
10038 NamedDecl *ND;
10039 if (QTy->isIncompleteType(&ND)) {
10040 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10041 return false;
10042 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010043 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010044 return false;
10045 }
10046 return true;
10047}
10048
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010049/// \brief Return true if it can be proven that the provided array expression
10050/// (array section or array subscript) does NOT specify the whole size of the
10051/// array whose base type is \a BaseQTy.
10052static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10053 const Expr *E,
10054 QualType BaseQTy) {
10055 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10056
10057 // If this is an array subscript, it refers to the whole size if the size of
10058 // the dimension is constant and equals 1. Also, an array section assumes the
10059 // format of an array subscript if no colon is used.
10060 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10061 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10062 return ATy->getSize().getSExtValue() != 1;
10063 // Size can't be evaluated statically.
10064 return false;
10065 }
10066
10067 assert(OASE && "Expecting array section if not an array subscript.");
10068 auto *LowerBound = OASE->getLowerBound();
10069 auto *Length = OASE->getLength();
10070
10071 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010072 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010073 if (LowerBound) {
10074 llvm::APSInt ConstLowerBound;
10075 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10076 return false; // Can't get the integer value as a constant.
10077 if (ConstLowerBound.getSExtValue())
10078 return true;
10079 }
10080
10081 // If we don't have a length we covering the whole dimension.
10082 if (!Length)
10083 return false;
10084
10085 // If the base is a pointer, we don't have a way to get the size of the
10086 // pointee.
10087 if (BaseQTy->isPointerType())
10088 return false;
10089
10090 // We can only check if the length is the same as the size of the dimension
10091 // if we have a constant array.
10092 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10093 if (!CATy)
10094 return false;
10095
10096 llvm::APSInt ConstLength;
10097 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10098 return false; // Can't get the integer value as a constant.
10099
10100 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10101}
10102
10103// Return true if it can be proven that the provided array expression (array
10104// section or array subscript) does NOT specify a single element of the array
10105// whose base type is \a BaseQTy.
10106static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010107 const Expr *E,
10108 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010109 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10110
10111 // An array subscript always refer to a single element. Also, an array section
10112 // assumes the format of an array subscript if no colon is used.
10113 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10114 return false;
10115
10116 assert(OASE && "Expecting array section if not an array subscript.");
10117 auto *Length = OASE->getLength();
10118
10119 // If we don't have a length we have to check if the array has unitary size
10120 // for this dimension. Also, we should always expect a length if the base type
10121 // is pointer.
10122 if (!Length) {
10123 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10124 return ATy->getSize().getSExtValue() != 1;
10125 // We cannot assume anything.
10126 return false;
10127 }
10128
10129 // Check if the length evaluates to 1.
10130 llvm::APSInt ConstLength;
10131 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10132 return false; // Can't get the integer value as a constant.
10133
10134 return ConstLength.getSExtValue() != 1;
10135}
10136
Samuel Antao661c0902016-05-26 17:39:58 +000010137// Return the expression of the base of the mappable expression or null if it
10138// cannot be determined and do all the necessary checks to see if the expression
10139// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010140// components of the expression.
10141static Expr *CheckMapClauseExpressionBase(
10142 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010143 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10144 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010145 SourceLocation ELoc = E->getExprLoc();
10146 SourceRange ERange = E->getSourceRange();
10147
10148 // The base of elements of list in a map clause have to be either:
10149 // - a reference to variable or field.
10150 // - a member expression.
10151 // - an array expression.
10152 //
10153 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10154 // reference to 'r'.
10155 //
10156 // If we have:
10157 //
10158 // struct SS {
10159 // Bla S;
10160 // foo() {
10161 // #pragma omp target map (S.Arr[:12]);
10162 // }
10163 // }
10164 //
10165 // We want to retrieve the member expression 'this->S';
10166
10167 Expr *RelevantExpr = nullptr;
10168
Samuel Antao5de996e2016-01-22 20:21:36 +000010169 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10170 // If a list item is an array section, it must specify contiguous storage.
10171 //
10172 // For this restriction it is sufficient that we make sure only references
10173 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010174 // exist except in the rightmost expression (unless they cover the whole
10175 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010176 //
10177 // r.ArrS[3:5].Arr[6:7]
10178 //
10179 // r.ArrS[3:5].x
10180 //
10181 // but these would be valid:
10182 // r.ArrS[3].Arr[6:7]
10183 //
10184 // r.ArrS[3].x
10185
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010186 bool AllowUnitySizeArraySection = true;
10187 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010188
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010189 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010190 E = E->IgnoreParenImpCasts();
10191
10192 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10193 if (!isa<VarDecl>(CurE->getDecl()))
10194 break;
10195
10196 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010197
10198 // If we got a reference to a declaration, we should not expect any array
10199 // section before that.
10200 AllowUnitySizeArraySection = false;
10201 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010202
10203 // Record the component.
10204 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10205 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010206 continue;
10207 }
10208
10209 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10210 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10211
10212 if (isa<CXXThisExpr>(BaseE))
10213 // We found a base expression: this->Val.
10214 RelevantExpr = CurE;
10215 else
10216 E = BaseE;
10217
10218 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10219 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10220 << CurE->getSourceRange();
10221 break;
10222 }
10223
10224 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10225
10226 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10227 // A bit-field cannot appear in a map clause.
10228 //
10229 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010230 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10231 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010232 break;
10233 }
10234
10235 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10236 // If the type of a list item is a reference to a type T then the type
10237 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010238 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010239
10240 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10241 // A list item cannot be a variable that is a member of a structure with
10242 // a union type.
10243 //
10244 if (auto *RT = CurType->getAs<RecordType>())
10245 if (RT->isUnionType()) {
10246 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10247 << CurE->getSourceRange();
10248 break;
10249 }
10250
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010251 // If we got a member expression, we should not expect any array section
10252 // before that:
10253 //
10254 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10255 // If a list item is an element of a structure, only the rightmost symbol
10256 // of the variable reference can be an array section.
10257 //
10258 AllowUnitySizeArraySection = false;
10259 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010260
10261 // Record the component.
10262 CurComponents.push_back(
10263 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010264 continue;
10265 }
10266
10267 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10268 E = CurE->getBase()->IgnoreParenImpCasts();
10269
10270 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10271 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10272 << 0 << CurE->getSourceRange();
10273 break;
10274 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010275
10276 // If we got an array subscript that express the whole dimension we
10277 // can have any array expressions before. If it only expressing part of
10278 // the dimension, we can only have unitary-size array expressions.
10279 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10280 E->getType()))
10281 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010282
10283 // Record the component - we don't have any declaration associated.
10284 CurComponents.push_back(
10285 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010286 continue;
10287 }
10288
10289 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010290 E = CurE->getBase()->IgnoreParenImpCasts();
10291
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010292 auto CurType =
10293 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10294
Samuel Antao5de996e2016-01-22 20:21:36 +000010295 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10296 // If the type of a list item is a reference to a type T then the type
10297 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010298 if (CurType->isReferenceType())
10299 CurType = CurType->getPointeeType();
10300
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010301 bool IsPointer = CurType->isAnyPointerType();
10302
10303 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010304 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10305 << 0 << CurE->getSourceRange();
10306 break;
10307 }
10308
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010309 bool NotWhole =
10310 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10311 bool NotUnity =
10312 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10313
Samuel Antaodab51bb2016-07-18 23:22:11 +000010314 if (AllowWholeSizeArraySection) {
10315 // Any array section is currently allowed. Allowing a whole size array
10316 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010317 //
10318 // If this array section refers to the whole dimension we can still
10319 // accept other array sections before this one, except if the base is a
10320 // pointer. Otherwise, only unitary sections are accepted.
10321 if (NotWhole || IsPointer)
10322 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010323 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010324 // A unity or whole array section is not allowed and that is not
10325 // compatible with the properties of the current array section.
10326 SemaRef.Diag(
10327 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10328 << CurE->getSourceRange();
10329 break;
10330 }
Samuel Antao90927002016-04-26 14:54:23 +000010331
10332 // Record the component - we don't have any declaration associated.
10333 CurComponents.push_back(
10334 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010335 continue;
10336 }
10337
10338 // If nothing else worked, this is not a valid map clause expression.
10339 SemaRef.Diag(ELoc,
10340 diag::err_omp_expected_named_var_member_or_array_expression)
10341 << ERange;
10342 break;
10343 }
10344
10345 return RelevantExpr;
10346}
10347
10348// Return true if expression E associated with value VD has conflicts with other
10349// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010350static bool CheckMapConflicts(
10351 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10352 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010353 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10354 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010355 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010356 SourceLocation ELoc = E->getExprLoc();
10357 SourceRange ERange = E->getSourceRange();
10358
10359 // In order to easily check the conflicts we need to match each component of
10360 // the expression under test with the components of the expressions that are
10361 // already in the stack.
10362
Samuel Antao5de996e2016-01-22 20:21:36 +000010363 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010364 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010365 "Map clause expression with unexpected base!");
10366
10367 // Variables to help detecting enclosing problems in data environment nests.
10368 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010369 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010370
Samuel Antao90927002016-04-26 14:54:23 +000010371 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10372 VD, CurrentRegionOnly,
10373 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010374 StackComponents,
10375 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010376
Samuel Antao5de996e2016-01-22 20:21:36 +000010377 assert(!StackComponents.empty() &&
10378 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010379 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010380 "Map clause expression with unexpected base!");
10381
Samuel Antao90927002016-04-26 14:54:23 +000010382 // The whole expression in the stack.
10383 auto *RE = StackComponents.front().getAssociatedExpression();
10384
Samuel Antao5de996e2016-01-22 20:21:36 +000010385 // Expressions must start from the same base. Here we detect at which
10386 // point both expressions diverge from each other and see if we can
10387 // detect if the memory referred to both expressions is contiguous and
10388 // do not overlap.
10389 auto CI = CurComponents.rbegin();
10390 auto CE = CurComponents.rend();
10391 auto SI = StackComponents.rbegin();
10392 auto SE = StackComponents.rend();
10393 for (; CI != CE && SI != SE; ++CI, ++SI) {
10394
10395 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10396 // At most one list item can be an array item derived from a given
10397 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010398 if (CurrentRegionOnly &&
10399 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10400 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10401 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10402 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10403 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010404 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010405 << CI->getAssociatedExpression()->getSourceRange();
10406 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10407 diag::note_used_here)
10408 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010409 return true;
10410 }
10411
10412 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010413 if (CI->getAssociatedExpression()->getStmtClass() !=
10414 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010415 break;
10416
10417 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010418 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010419 break;
10420 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010421 // Check if the extra components of the expressions in the enclosing
10422 // data environment are redundant for the current base declaration.
10423 // If they are, the maps completely overlap, which is legal.
10424 for (; SI != SE; ++SI) {
10425 QualType Type;
10426 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010427 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010428 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010429 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10430 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010431 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10432 Type =
10433 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10434 }
10435 if (Type.isNull() || Type->isAnyPointerType() ||
10436 CheckArrayExpressionDoesNotReferToWholeSize(
10437 SemaRef, SI->getAssociatedExpression(), Type))
10438 break;
10439 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010440
10441 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10442 // List items of map clauses in the same construct must not share
10443 // original storage.
10444 //
10445 // If the expressions are exactly the same or one is a subset of the
10446 // other, it means they are sharing storage.
10447 if (CI == CE && SI == SE) {
10448 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010449 if (CKind == OMPC_map)
10450 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10451 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010452 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010453 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10454 << ERange;
10455 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010456 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10457 << RE->getSourceRange();
10458 return true;
10459 } else {
10460 // If we find the same expression in the enclosing data environment,
10461 // that is legal.
10462 IsEnclosedByDataEnvironmentExpr = true;
10463 return false;
10464 }
10465 }
10466
Samuel Antao90927002016-04-26 14:54:23 +000010467 QualType DerivedType =
10468 std::prev(CI)->getAssociatedDeclaration()->getType();
10469 SourceLocation DerivedLoc =
10470 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010471
10472 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10473 // If the type of a list item is a reference to a type T then the type
10474 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010475 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010476
10477 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10478 // A variable for which the type is pointer and an array section
10479 // derived from that variable must not appear as list items of map
10480 // clauses of the same construct.
10481 //
10482 // Also, cover one of the cases in:
10483 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10484 // If any part of the original storage of a list item has corresponding
10485 // storage in the device data environment, all of the original storage
10486 // must have corresponding storage in the device data environment.
10487 //
10488 if (DerivedType->isAnyPointerType()) {
10489 if (CI == CE || SI == SE) {
10490 SemaRef.Diag(
10491 DerivedLoc,
10492 diag::err_omp_pointer_mapped_along_with_derived_section)
10493 << DerivedLoc;
10494 } else {
10495 assert(CI != CE && SI != SE);
10496 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10497 << DerivedLoc;
10498 }
10499 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10500 << RE->getSourceRange();
10501 return true;
10502 }
10503
10504 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10505 // List items of map clauses in the same construct must not share
10506 // original storage.
10507 //
10508 // An expression is a subset of the other.
10509 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010510 if (CKind == OMPC_map)
10511 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10512 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010513 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010514 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10515 << ERange;
10516 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010517 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10518 << RE->getSourceRange();
10519 return true;
10520 }
10521
10522 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010523 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010524 if (!CurrentRegionOnly && SI != SE)
10525 EnclosingExpr = RE;
10526
10527 // The current expression is a subset of the expression in the data
10528 // environment.
10529 IsEnclosedByDataEnvironmentExpr |=
10530 (!CurrentRegionOnly && CI != CE && SI == SE);
10531
10532 return false;
10533 });
10534
10535 if (CurrentRegionOnly)
10536 return FoundError;
10537
10538 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10539 // If any part of the original storage of a list item has corresponding
10540 // storage in the device data environment, all of the original storage must
10541 // have corresponding storage in the device data environment.
10542 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10543 // If a list item is an element of a structure, and a different element of
10544 // the structure has a corresponding list item in the device data environment
10545 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010546 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010547 // data environment prior to the task encountering the construct.
10548 //
10549 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10550 SemaRef.Diag(ELoc,
10551 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10552 << ERange;
10553 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10554 << EnclosingExpr->getSourceRange();
10555 return true;
10556 }
10557
10558 return FoundError;
10559}
10560
Samuel Antao661c0902016-05-26 17:39:58 +000010561namespace {
10562// Utility struct that gathers all the related lists associated with a mappable
10563// expression.
10564struct MappableVarListInfo final {
10565 // The list of expressions.
10566 ArrayRef<Expr *> VarList;
10567 // The list of processed expressions.
10568 SmallVector<Expr *, 16> ProcessedVarList;
10569 // The mappble components for each expression.
10570 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10571 // The base declaration of the variable.
10572 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10573
10574 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10575 // We have a list of components and base declarations for each entry in the
10576 // variable list.
10577 VarComponents.reserve(VarList.size());
10578 VarBaseDeclarations.reserve(VarList.size());
10579 }
10580};
10581}
10582
10583// Check the validity of the provided variable list for the provided clause kind
10584// \a CKind. In the check process the valid expressions, and mappable expression
10585// components and variables are extracted and used to fill \a Vars,
10586// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10587// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10588static void
10589checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10590 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10591 SourceLocation StartLoc,
10592 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10593 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010594 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10595 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010596 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010597
Samuel Antao90927002016-04-26 14:54:23 +000010598 // Keep track of the mappable components and base declarations in this clause.
10599 // Each entry in the list is going to have a list of components associated. We
10600 // record each set of the components so that we can build the clause later on.
10601 // In the end we should have the same amount of declarations and component
10602 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010603
Samuel Antao661c0902016-05-26 17:39:58 +000010604 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010605 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010606 SourceLocation ELoc = RE->getExprLoc();
10607
Kelvin Li0bff7af2015-11-23 05:32:03 +000010608 auto *VE = RE->IgnoreParenLValueCasts();
10609
10610 if (VE->isValueDependent() || VE->isTypeDependent() ||
10611 VE->isInstantiationDependent() ||
10612 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010613 // We can only analyze this information once the missing information is
10614 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010615 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010616 continue;
10617 }
10618
10619 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010620
Samuel Antao5de996e2016-01-22 20:21:36 +000010621 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010622 SemaRef.Diag(ELoc,
10623 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010624 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010625 continue;
10626 }
10627
Samuel Antao90927002016-04-26 14:54:23 +000010628 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10629 ValueDecl *CurDeclaration = nullptr;
10630
10631 // Obtain the array or member expression bases if required. Also, fill the
10632 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010633 auto *BE =
10634 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010635 if (!BE)
10636 continue;
10637
Samuel Antao90927002016-04-26 14:54:23 +000010638 assert(!CurComponents.empty() &&
10639 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010640
Samuel Antao90927002016-04-26 14:54:23 +000010641 // For the following checks, we rely on the base declaration which is
10642 // expected to be associated with the last component. The declaration is
10643 // expected to be a variable or a field (if 'this' is being mapped).
10644 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10645 assert(CurDeclaration && "Null decl on map clause.");
10646 assert(
10647 CurDeclaration->isCanonicalDecl() &&
10648 "Expecting components to have associated only canonical declarations.");
10649
10650 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10651 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010652
10653 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010654 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010655
10656 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010657 // threadprivate variables cannot appear in a map clause.
10658 // OpenMP 4.5 [2.10.5, target update Construct]
10659 // threadprivate variables cannot appear in a from clause.
10660 if (VD && DSAS->isThreadPrivate(VD)) {
10661 auto DVar = DSAS->getTopDSA(VD, false);
10662 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10663 << getOpenMPClauseName(CKind);
10664 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010665 continue;
10666 }
10667
Samuel Antao5de996e2016-01-22 20:21:36 +000010668 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10669 // A list item cannot appear in both a map clause and a data-sharing
10670 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010671
Samuel Antao5de996e2016-01-22 20:21:36 +000010672 // Check conflicts with other map clause expressions. We check the conflicts
10673 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010674 // environment, because the restrictions are different. We only have to
10675 // check conflicts across regions for the map clauses.
10676 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10677 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010678 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010679 if (CKind == OMPC_map &&
10680 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10681 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010682 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010683
Samuel Antao661c0902016-05-26 17:39:58 +000010684 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010685 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10686 // If the type of a list item is a reference to a type T then the type will
10687 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010688 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010689
Samuel Antao661c0902016-05-26 17:39:58 +000010690 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10691 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010692 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010693 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010694 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10695 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010696 continue;
10697
Samuel Antao661c0902016-05-26 17:39:58 +000010698 if (CKind == OMPC_map) {
10699 // target enter data
10700 // OpenMP [2.10.2, Restrictions, p. 99]
10701 // A map-type must be specified in all map clauses and must be either
10702 // to or alloc.
10703 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10704 if (DKind == OMPD_target_enter_data &&
10705 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10706 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10707 << (IsMapTypeImplicit ? 1 : 0)
10708 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10709 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010710 continue;
10711 }
Samuel Antao661c0902016-05-26 17:39:58 +000010712
10713 // target exit_data
10714 // OpenMP [2.10.3, Restrictions, p. 102]
10715 // A map-type must be specified in all map clauses and must be either
10716 // from, release, or delete.
10717 if (DKind == OMPD_target_exit_data &&
10718 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10719 MapType == OMPC_MAP_delete)) {
10720 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10721 << (IsMapTypeImplicit ? 1 : 0)
10722 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10723 << getOpenMPDirectiveName(DKind);
10724 continue;
10725 }
10726
10727 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10728 // A list item cannot appear in both a map clause and a data-sharing
10729 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010730 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010731 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010732 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010733 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10734 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010735 auto DVar = DSAS->getTopDSA(VD, false);
10736 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010737 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010738 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010739 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010740 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10741 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10742 continue;
10743 }
10744 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010745 }
10746
Samuel Antao90927002016-04-26 14:54:23 +000010747 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010748 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010749
10750 // Store the components in the stack so that they can be used to check
10751 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010752 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10753 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010754
10755 // Save the components and declaration to create the clause. For purposes of
10756 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010757 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010758 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10759 MVLI.VarComponents.back().append(CurComponents.begin(),
10760 CurComponents.end());
10761 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10762 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010763 }
Samuel Antao661c0902016-05-26 17:39:58 +000010764}
10765
10766OMPClause *
10767Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10768 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10769 SourceLocation MapLoc, SourceLocation ColonLoc,
10770 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10771 SourceLocation LParenLoc, SourceLocation EndLoc) {
10772 MappableVarListInfo MVLI(VarList);
10773 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10774 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010775
Samuel Antao5de996e2016-01-22 20:21:36 +000010776 // We need to produce a map clause even if we don't have variables so that
10777 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010778 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10779 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10780 MVLI.VarComponents, MapTypeModifier, MapType,
10781 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010782}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010783
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010784QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10785 TypeResult ParsedType) {
10786 assert(ParsedType.isUsable());
10787
10788 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10789 if (ReductionType.isNull())
10790 return QualType();
10791
10792 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10793 // A type name in a declare reduction directive cannot be a function type, an
10794 // array type, a reference type, or a type qualified with const, volatile or
10795 // restrict.
10796 if (ReductionType.hasQualifiers()) {
10797 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10798 return QualType();
10799 }
10800
10801 if (ReductionType->isFunctionType()) {
10802 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10803 return QualType();
10804 }
10805 if (ReductionType->isReferenceType()) {
10806 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10807 return QualType();
10808 }
10809 if (ReductionType->isArrayType()) {
10810 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10811 return QualType();
10812 }
10813 return ReductionType;
10814}
10815
10816Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10817 Scope *S, DeclContext *DC, DeclarationName Name,
10818 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10819 AccessSpecifier AS, Decl *PrevDeclInScope) {
10820 SmallVector<Decl *, 8> Decls;
10821 Decls.reserve(ReductionTypes.size());
10822
10823 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10824 ForRedeclaration);
10825 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10826 // A reduction-identifier may not be re-declared in the current scope for the
10827 // same type or for a type that is compatible according to the base language
10828 // rules.
10829 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10830 OMPDeclareReductionDecl *PrevDRD = nullptr;
10831 bool InCompoundScope = true;
10832 if (S != nullptr) {
10833 // Find previous declaration with the same name not referenced in other
10834 // declarations.
10835 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10836 InCompoundScope =
10837 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10838 LookupName(Lookup, S);
10839 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10840 /*AllowInlineNamespace=*/false);
10841 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10842 auto Filter = Lookup.makeFilter();
10843 while (Filter.hasNext()) {
10844 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10845 if (InCompoundScope) {
10846 auto I = UsedAsPrevious.find(PrevDecl);
10847 if (I == UsedAsPrevious.end())
10848 UsedAsPrevious[PrevDecl] = false;
10849 if (auto *D = PrevDecl->getPrevDeclInScope())
10850 UsedAsPrevious[D] = true;
10851 }
10852 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10853 PrevDecl->getLocation();
10854 }
10855 Filter.done();
10856 if (InCompoundScope) {
10857 for (auto &PrevData : UsedAsPrevious) {
10858 if (!PrevData.second) {
10859 PrevDRD = PrevData.first;
10860 break;
10861 }
10862 }
10863 }
10864 } else if (PrevDeclInScope != nullptr) {
10865 auto *PrevDRDInScope = PrevDRD =
10866 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10867 do {
10868 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10869 PrevDRDInScope->getLocation();
10870 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10871 } while (PrevDRDInScope != nullptr);
10872 }
10873 for (auto &TyData : ReductionTypes) {
10874 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10875 bool Invalid = false;
10876 if (I != PreviousRedeclTypes.end()) {
10877 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10878 << TyData.first;
10879 Diag(I->second, diag::note_previous_definition);
10880 Invalid = true;
10881 }
10882 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10883 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10884 Name, TyData.first, PrevDRD);
10885 DC->addDecl(DRD);
10886 DRD->setAccess(AS);
10887 Decls.push_back(DRD);
10888 if (Invalid)
10889 DRD->setInvalidDecl();
10890 else
10891 PrevDRD = DRD;
10892 }
10893
10894 return DeclGroupPtrTy::make(
10895 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10896}
10897
10898void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10899 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10900
10901 // Enter new function scope.
10902 PushFunctionScope();
10903 getCurFunction()->setHasBranchProtectedScope();
10904 getCurFunction()->setHasOMPDeclareReductionCombiner();
10905
10906 if (S != nullptr)
10907 PushDeclContext(S, DRD);
10908 else
10909 CurContext = DRD;
10910
Faisal Valid143a0c2017-04-01 21:30:49 +000010911 PushExpressionEvaluationContext(
10912 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010913
10914 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010915 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10916 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
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_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010921 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010922 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010923 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10924 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10925 // uses semantics of argument handles by value, but it should be passed by
10926 // reference. C lang does not support references, so pass all parameters as
10927 // pointers.
10928 // Create 'T omp_out;' variable.
10929 auto *OmpOutParm =
10930 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10931 if (S != nullptr) {
10932 PushOnScopeChains(OmpInParm, S);
10933 PushOnScopeChains(OmpOutParm, S);
10934 } else {
10935 DRD->addDecl(OmpInParm);
10936 DRD->addDecl(OmpOutParm);
10937 }
10938}
10939
10940void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10941 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10942 DiscardCleanupsInEvaluationContext();
10943 PopExpressionEvaluationContext();
10944
10945 PopDeclContext();
10946 PopFunctionScopeInfo();
10947
10948 if (Combiner != nullptr)
10949 DRD->setCombiner(Combiner);
10950 else
10951 DRD->setInvalidDecl();
10952}
10953
10954void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10955 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10956
10957 // Enter new function scope.
10958 PushFunctionScope();
10959 getCurFunction()->setHasBranchProtectedScope();
10960
10961 if (S != nullptr)
10962 PushDeclContext(S, DRD);
10963 else
10964 CurContext = DRD;
10965
Faisal Valid143a0c2017-04-01 21:30:49 +000010966 PushExpressionEvaluationContext(
10967 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010968
10969 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010970 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10971 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10972 // uses semantics of argument handles by value, but it should be passed by
10973 // reference. C lang does not support references, so pass all parameters as
10974 // pointers.
10975 // Create 'T omp_priv;' variable.
10976 auto *OmpPrivParm =
10977 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010978 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10979 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10980 // uses semantics of argument handles by value, but it should be passed by
10981 // reference. C lang does not support references, so pass all parameters as
10982 // pointers.
10983 // Create 'T omp_orig;' variable.
10984 auto *OmpOrigParm =
10985 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010986 if (S != nullptr) {
10987 PushOnScopeChains(OmpPrivParm, S);
10988 PushOnScopeChains(OmpOrigParm, S);
10989 } else {
10990 DRD->addDecl(OmpPrivParm);
10991 DRD->addDecl(OmpOrigParm);
10992 }
10993}
10994
10995void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10996 Expr *Initializer) {
10997 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10998 DiscardCleanupsInEvaluationContext();
10999 PopExpressionEvaluationContext();
11000
11001 PopDeclContext();
11002 PopFunctionScopeInfo();
11003
11004 if (Initializer != nullptr)
11005 DRD->setInitializer(Initializer);
11006 else
11007 DRD->setInvalidDecl();
11008}
11009
11010Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11011 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11012 for (auto *D : DeclReductions.get()) {
11013 if (IsValid) {
11014 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11015 if (S != nullptr)
11016 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11017 } else
11018 D->setInvalidDecl();
11019 }
11020 return DeclReductions;
11021}
11022
David Majnemer9d168222016-08-05 17:44:54 +000011023OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011024 SourceLocation StartLoc,
11025 SourceLocation LParenLoc,
11026 SourceLocation EndLoc) {
11027 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011028 Stmt *HelperValStmt = nullptr;
11029 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011030
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011031 // OpenMP [teams Constrcut, Restrictions]
11032 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011033 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11034 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011035 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011036
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011037 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11038 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11039 if (CaptureRegion != OMPD_unknown) {
11040 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11041 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11042 HelperValStmt = buildPreInits(Context, Captures);
11043 }
11044
11045 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11046 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011047}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011048
11049OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11050 SourceLocation StartLoc,
11051 SourceLocation LParenLoc,
11052 SourceLocation EndLoc) {
11053 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011054 Stmt *HelperValStmt = nullptr;
11055 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011056
11057 // OpenMP [teams Constrcut, Restrictions]
11058 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011059 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11060 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011061 return nullptr;
11062
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011063 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11064 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11065 if (CaptureRegion != OMPD_unknown) {
11066 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11067 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11068 HelperValStmt = buildPreInits(Context, Captures);
11069 }
11070
11071 return new (Context) OMPThreadLimitClause(
11072 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011073}
Alexey Bataeva0569352015-12-01 10:17:31 +000011074
11075OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11076 SourceLocation StartLoc,
11077 SourceLocation LParenLoc,
11078 SourceLocation EndLoc) {
11079 Expr *ValExpr = Priority;
11080
11081 // OpenMP [2.9.1, task Constrcut]
11082 // The priority-value is a non-negative numerical scalar expression.
11083 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11084 /*StrictlyPositive=*/false))
11085 return nullptr;
11086
11087 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11088}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011089
11090OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11091 SourceLocation StartLoc,
11092 SourceLocation LParenLoc,
11093 SourceLocation EndLoc) {
11094 Expr *ValExpr = Grainsize;
11095
11096 // OpenMP [2.9.2, taskloop Constrcut]
11097 // The parameter of the grainsize clause must be a positive integer
11098 // expression.
11099 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11100 /*StrictlyPositive=*/true))
11101 return nullptr;
11102
11103 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11104}
Alexey Bataev382967a2015-12-08 12:06:20 +000011105
11106OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11107 SourceLocation StartLoc,
11108 SourceLocation LParenLoc,
11109 SourceLocation EndLoc) {
11110 Expr *ValExpr = NumTasks;
11111
11112 // OpenMP [2.9.2, taskloop Constrcut]
11113 // The parameter of the num_tasks clause must be a positive integer
11114 // expression.
11115 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11116 /*StrictlyPositive=*/true))
11117 return nullptr;
11118
11119 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11120}
11121
Alexey Bataev28c75412015-12-15 08:19:24 +000011122OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11123 SourceLocation LParenLoc,
11124 SourceLocation EndLoc) {
11125 // OpenMP [2.13.2, critical construct, Description]
11126 // ... where hint-expression is an integer constant expression that evaluates
11127 // to a valid lock hint.
11128 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11129 if (HintExpr.isInvalid())
11130 return nullptr;
11131 return new (Context)
11132 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11133}
11134
Carlo Bertollib4adf552016-01-15 18:50:31 +000011135OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11136 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11137 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11138 SourceLocation EndLoc) {
11139 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11140 std::string Values;
11141 Values += "'";
11142 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11143 Values += "'";
11144 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11145 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11146 return nullptr;
11147 }
11148 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011149 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011150 if (ChunkSize) {
11151 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11152 !ChunkSize->isInstantiationDependent() &&
11153 !ChunkSize->containsUnexpandedParameterPack()) {
11154 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11155 ExprResult Val =
11156 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11157 if (Val.isInvalid())
11158 return nullptr;
11159
11160 ValExpr = Val.get();
11161
11162 // OpenMP [2.7.1, Restrictions]
11163 // chunk_size must be a loop invariant integer expression with a positive
11164 // value.
11165 llvm::APSInt Result;
11166 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11167 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11168 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11169 << "dist_schedule" << ChunkSize->getSourceRange();
11170 return nullptr;
11171 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011172 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11173 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011174 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11175 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11176 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011177 }
11178 }
11179 }
11180
11181 return new (Context)
11182 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011183 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011184}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011185
11186OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11187 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11188 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11189 SourceLocation KindLoc, SourceLocation EndLoc) {
11190 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011191 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011192 std::string Value;
11193 SourceLocation Loc;
11194 Value += "'";
11195 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11196 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011197 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011198 Loc = MLoc;
11199 } else {
11200 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011201 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011202 Loc = KindLoc;
11203 }
11204 Value += "'";
11205 Diag(Loc, diag::err_omp_unexpected_clause_value)
11206 << Value << getOpenMPClauseName(OMPC_defaultmap);
11207 return nullptr;
11208 }
11209
11210 return new (Context)
11211 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11212}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011213
11214bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11215 DeclContext *CurLexicalContext = getCurLexicalContext();
11216 if (!CurLexicalContext->isFileContext() &&
11217 !CurLexicalContext->isExternCContext() &&
11218 !CurLexicalContext->isExternCXXContext()) {
11219 Diag(Loc, diag::err_omp_region_not_file_context);
11220 return false;
11221 }
11222 if (IsInOpenMPDeclareTargetContext) {
11223 Diag(Loc, diag::err_omp_enclosed_declare_target);
11224 return false;
11225 }
11226
11227 IsInOpenMPDeclareTargetContext = true;
11228 return true;
11229}
11230
11231void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11232 assert(IsInOpenMPDeclareTargetContext &&
11233 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11234
11235 IsInOpenMPDeclareTargetContext = false;
11236}
11237
David Majnemer9d168222016-08-05 17:44:54 +000011238void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11239 CXXScopeSpec &ScopeSpec,
11240 const DeclarationNameInfo &Id,
11241 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11242 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011243 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11244 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11245
11246 if (Lookup.isAmbiguous())
11247 return;
11248 Lookup.suppressDiagnostics();
11249
11250 if (!Lookup.isSingleResult()) {
11251 if (TypoCorrection Corrected =
11252 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11253 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11254 CTK_ErrorRecovery)) {
11255 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11256 << Id.getName());
11257 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11258 return;
11259 }
11260
11261 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11262 return;
11263 }
11264
11265 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11266 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11267 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11268 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11269
11270 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11271 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11272 ND->addAttr(A);
11273 if (ASTMutationListener *ML = Context.getASTMutationListener())
11274 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11275 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11276 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11277 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11278 << Id.getName();
11279 }
11280 } else
11281 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11282}
11283
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011284static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11285 Sema &SemaRef, Decl *D) {
11286 if (!D)
11287 return;
11288 Decl *LD = nullptr;
11289 if (isa<TagDecl>(D)) {
11290 LD = cast<TagDecl>(D)->getDefinition();
11291 } else if (isa<VarDecl>(D)) {
11292 LD = cast<VarDecl>(D)->getDefinition();
11293
11294 // If this is an implicit variable that is legal and we do not need to do
11295 // anything.
11296 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011297 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11298 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11299 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011300 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011301 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011302 return;
11303 }
11304
11305 } else if (isa<FunctionDecl>(D)) {
11306 const FunctionDecl *FD = nullptr;
11307 if (cast<FunctionDecl>(D)->hasBody(FD))
11308 LD = const_cast<FunctionDecl *>(FD);
11309
11310 // If the definition is associated with the current declaration in the
11311 // target region (it can be e.g. a lambda) that is legal and we do not need
11312 // to do anything else.
11313 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011314 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11315 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11316 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011317 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011318 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011319 return;
11320 }
11321 }
11322 if (!LD)
11323 LD = D;
11324 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11325 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11326 // Outlined declaration is not declared target.
11327 if (LD->isOutOfLine()) {
11328 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11329 SemaRef.Diag(SL, diag::note_used_here) << SR;
11330 } else {
11331 DeclContext *DC = LD->getDeclContext();
11332 while (DC) {
11333 if (isa<FunctionDecl>(DC) &&
11334 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11335 break;
11336 DC = DC->getParent();
11337 }
11338 if (DC)
11339 return;
11340
11341 // Is not declared in target context.
11342 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11343 SemaRef.Diag(SL, diag::note_used_here) << SR;
11344 }
11345 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011346 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11347 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11348 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011349 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011350 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011351 }
11352}
11353
11354static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11355 Sema &SemaRef, DSAStackTy *Stack,
11356 ValueDecl *VD) {
11357 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11358 return true;
11359 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11360 return false;
11361 return true;
11362}
11363
11364void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11365 if (!D || D->isInvalidDecl())
11366 return;
11367 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11368 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11369 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11370 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11371 if (DSAStack->isThreadPrivate(VD)) {
11372 Diag(SL, diag::err_omp_threadprivate_in_target);
11373 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11374 return;
11375 }
11376 }
11377 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11378 // Problem if any with var declared with incomplete type will be reported
11379 // as normal, so no need to check it here.
11380 if ((E || !VD->getType()->isIncompleteType()) &&
11381 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11382 // Mark decl as declared target to prevent further diagnostic.
11383 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011384 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11385 Context, OMPDeclareTargetDeclAttr::MT_To);
11386 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011387 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011388 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011389 }
11390 return;
11391 }
11392 }
11393 if (!E) {
11394 // Checking declaration inside declare target region.
11395 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11396 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011397 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11398 Context, OMPDeclareTargetDeclAttr::MT_To);
11399 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011400 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011401 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011402 }
11403 return;
11404 }
11405 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11406}
Samuel Antao661c0902016-05-26 17:39:58 +000011407
11408OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11409 SourceLocation StartLoc,
11410 SourceLocation LParenLoc,
11411 SourceLocation EndLoc) {
11412 MappableVarListInfo MVLI(VarList);
11413 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11414 if (MVLI.ProcessedVarList.empty())
11415 return nullptr;
11416
11417 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11418 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11419 MVLI.VarComponents);
11420}
Samuel Antaoec172c62016-05-26 17:49:04 +000011421
11422OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11423 SourceLocation StartLoc,
11424 SourceLocation LParenLoc,
11425 SourceLocation EndLoc) {
11426 MappableVarListInfo MVLI(VarList);
11427 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11428 if (MVLI.ProcessedVarList.empty())
11429 return nullptr;
11430
11431 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11432 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11433 MVLI.VarComponents);
11434}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011435
11436OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11437 SourceLocation StartLoc,
11438 SourceLocation LParenLoc,
11439 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011440 MappableVarListInfo MVLI(VarList);
11441 SmallVector<Expr *, 8> PrivateCopies;
11442 SmallVector<Expr *, 8> Inits;
11443
Carlo Bertolli2404b172016-07-13 15:37:16 +000011444 for (auto &RefExpr : VarList) {
11445 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11446 SourceLocation ELoc;
11447 SourceRange ERange;
11448 Expr *SimpleRefExpr = RefExpr;
11449 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11450 if (Res.second) {
11451 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011452 MVLI.ProcessedVarList.push_back(RefExpr);
11453 PrivateCopies.push_back(nullptr);
11454 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011455 }
11456 ValueDecl *D = Res.first;
11457 if (!D)
11458 continue;
11459
11460 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011461 Type = Type.getNonReferenceType().getUnqualifiedType();
11462
11463 auto *VD = dyn_cast<VarDecl>(D);
11464
11465 // Item should be a pointer or reference to pointer.
11466 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011467 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11468 << 0 << RefExpr->getSourceRange();
11469 continue;
11470 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011471
11472 // Build the private variable and the expression that refers to it.
11473 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11474 D->hasAttrs() ? &D->getAttrs() : nullptr);
11475 if (VDPrivate->isInvalidDecl())
11476 continue;
11477
11478 CurContext->addDecl(VDPrivate);
11479 auto VDPrivateRefExpr = buildDeclRefExpr(
11480 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11481
11482 // Add temporary variable to initialize the private copy of the pointer.
11483 auto *VDInit =
11484 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11485 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11486 RefExpr->getExprLoc());
11487 AddInitializerToDecl(VDPrivate,
11488 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011489 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011490
11491 // If required, build a capture to implement the privatization initialized
11492 // with the current list item value.
11493 DeclRefExpr *Ref = nullptr;
11494 if (!VD)
11495 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11496 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11497 PrivateCopies.push_back(VDPrivateRefExpr);
11498 Inits.push_back(VDInitRefExpr);
11499
11500 // We need to add a data sharing attribute for this variable to make sure it
11501 // is correctly captured. A variable that shows up in a use_device_ptr has
11502 // similar properties of a first private variable.
11503 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11504
11505 // Create a mappable component for the list item. List items in this clause
11506 // only need a component.
11507 MVLI.VarBaseDeclarations.push_back(D);
11508 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11509 MVLI.VarComponents.back().push_back(
11510 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011511 }
11512
Samuel Antaocc10b852016-07-28 14:23:26 +000011513 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011514 return nullptr;
11515
Samuel Antaocc10b852016-07-28 14:23:26 +000011516 return OMPUseDevicePtrClause::Create(
11517 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11518 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011519}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011520
11521OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11522 SourceLocation StartLoc,
11523 SourceLocation LParenLoc,
11524 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011525 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011526 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011527 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011528 SourceLocation ELoc;
11529 SourceRange ERange;
11530 Expr *SimpleRefExpr = RefExpr;
11531 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11532 if (Res.second) {
11533 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011534 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011535 }
11536 ValueDecl *D = Res.first;
11537 if (!D)
11538 continue;
11539
11540 QualType Type = D->getType();
11541 // item should be a pointer or array or reference to pointer or array
11542 if (!Type.getNonReferenceType()->isPointerType() &&
11543 !Type.getNonReferenceType()->isArrayType()) {
11544 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11545 << 0 << RefExpr->getSourceRange();
11546 continue;
11547 }
Samuel Antao6890b092016-07-28 14:25:09 +000011548
11549 // Check if the declaration in the clause does not show up in any data
11550 // sharing attribute.
11551 auto DVar = DSAStack->getTopDSA(D, false);
11552 if (isOpenMPPrivate(DVar.CKind)) {
11553 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11554 << getOpenMPClauseName(DVar.CKind)
11555 << getOpenMPClauseName(OMPC_is_device_ptr)
11556 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11557 ReportOriginalDSA(*this, DSAStack, D, DVar);
11558 continue;
11559 }
11560
11561 Expr *ConflictExpr;
11562 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011563 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011564 [&ConflictExpr](
11565 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11566 OpenMPClauseKind) -> bool {
11567 ConflictExpr = R.front().getAssociatedExpression();
11568 return true;
11569 })) {
11570 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11571 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11572 << ConflictExpr->getSourceRange();
11573 continue;
11574 }
11575
11576 // Store the components in the stack so that they can be used to check
11577 // against other clauses later on.
11578 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11579 DSAStack->addMappableExpressionComponents(
11580 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11581
11582 // Record the expression we've just processed.
11583 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11584
11585 // Create a mappable component for the list item. List items in this clause
11586 // only need a component. We use a null declaration to signal fields in
11587 // 'this'.
11588 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11589 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11590 "Unexpected device pointer expression!");
11591 MVLI.VarBaseDeclarations.push_back(
11592 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11593 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11594 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011595 }
11596
Samuel Antao6890b092016-07-28 14:25:09 +000011597 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011598 return nullptr;
11599
Samuel Antao6890b092016-07-28 14:25:09 +000011600 return OMPIsDevicePtrClause::Create(
11601 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11602 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011603}