blob: 5b21f5801252149a733e6d67a62bdb5d9e1f4f9c [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001092 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Kelvin Libf594a52016-12-17 05:48:59 +00001597 case OMPD_teams:
1598 case OMPD_target_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001611 case OMPD_target_parallel: {
1612 Sema::CapturedParamNameType ParamsTarget[] = {
1613 std::make_pair(StringRef(), QualType()) // __context with shared vars
1614 };
1615 // Start a captured region for 'target' with no implicit parameters.
1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1617 ParamsTarget);
1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1619 QualType KmpInt32PtrTy =
1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1621 Sema::CapturedParamNameType ParamsParallel[] = {
1622 std::make_pair(".global_tid.", KmpInt32PtrTy),
1623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1624 std::make_pair(StringRef(), QualType()) // __context with shared vars
1625 };
1626 // Start a captured region for 'parallel'.
1627 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1628 ParamsParallel);
1629 break;
1630 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001631 case OMPD_simd:
1632 case OMPD_for:
1633 case OMPD_for_simd:
1634 case OMPD_sections:
1635 case OMPD_section:
1636 case OMPD_single:
1637 case OMPD_master:
1638 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001639 case OMPD_taskgroup:
1640 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001641 case OMPD_ordered:
1642 case OMPD_atomic:
1643 case OMPD_target_data:
1644 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001645 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001646 case OMPD_target_parallel_for_simd:
1647 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001648 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1650 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001653 break;
1654 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001655 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001656 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001657 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1658 FunctionProtoType::ExtProtoInfo EPI;
1659 EPI.Variadic = true;
1660 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001661 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001662 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001663 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1664 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1665 std::make_pair(".copy_fn.",
1666 Context.getPointerType(CopyFnType).withConst()),
1667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001668 std::make_pair(StringRef(), QualType()) // __context with shared vars
1669 };
1670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1671 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001672 // Mark this captured region as inlined, because we don't use outlined
1673 // function directly.
1674 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1675 AlwaysInlineAttr::CreateImplicit(
1676 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001677 break;
1678 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001679 case OMPD_taskloop:
1680 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001681 QualType KmpInt32Ty =
1682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1683 QualType KmpUInt64Ty =
1684 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1685 QualType KmpInt64Ty =
1686 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1687 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1688 FunctionProtoType::ExtProtoInfo EPI;
1689 EPI.Variadic = true;
1690 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001691 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001692 std::make_pair(".global_tid.", KmpInt32Ty),
1693 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1694 std::make_pair(".privates.",
1695 Context.VoidPtrTy.withConst().withRestrict()),
1696 std::make_pair(
1697 ".copy_fn.",
1698 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1699 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1700 std::make_pair(".lb.", KmpUInt64Ty),
1701 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1702 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001703 std::make_pair(StringRef(), QualType()) // __context with shared vars
1704 };
1705 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1706 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001707 // Mark this captured region as inlined, because we don't use outlined
1708 // function directly.
1709 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1710 AlwaysInlineAttr::CreateImplicit(
1711 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001712 break;
1713 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001714 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001715 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001716 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001717 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001718 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001719 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001720 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001721 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001722 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001723 case OMPD_target_teams_distribute_parallel_for_simd:
1724 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001725 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1726 QualType KmpInt32PtrTy =
1727 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1728 Sema::CapturedParamNameType Params[] = {
1729 std::make_pair(".global_tid.", KmpInt32PtrTy),
1730 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1731 std::make_pair(".previous.lb.", Context.getSizeType()),
1732 std::make_pair(".previous.ub.", Context.getSizeType()),
1733 std::make_pair(StringRef(), QualType()) // __context with shared vars
1734 };
1735 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1736 Params);
1737 break;
1738 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001739 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001740 case OMPD_taskyield:
1741 case OMPD_barrier:
1742 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001743 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001744 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001745 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001746 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001747 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001748 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001749 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001750 case OMPD_declare_target:
1751 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001752 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001753 llvm_unreachable("OpenMP Directive is not allowed");
1754 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001755 llvm_unreachable("Unknown OpenMP directive");
1756 }
1757}
1758
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001759int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1760 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1761 getOpenMPCaptureRegions(CaptureRegions, DKind);
1762 return CaptureRegions.size();
1763}
1764
Alexey Bataev3392d762016-02-16 11:18:12 +00001765static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001766 Expr *CaptureExpr, bool WithInit,
1767 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001768 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001769 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001770 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001771 QualType Ty = Init->getType();
1772 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1773 if (S.getLangOpts().CPlusPlus)
1774 Ty = C.getLValueReferenceType(Ty);
1775 else {
1776 Ty = C.getPointerType(Ty);
1777 ExprResult Res =
1778 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1779 if (!Res.isUsable())
1780 return nullptr;
1781 Init = Res.get();
1782 }
Alexey Bataev61205072016-03-02 04:57:40 +00001783 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001784 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001785 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1786 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001787 if (!WithInit)
1788 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001789 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001790 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001791 return CED;
1792}
1793
Alexey Bataev61205072016-03-02 04:57:40 +00001794static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1795 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001796 OMPCapturedExprDecl *CD;
1797 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1798 CD = cast<OMPCapturedExprDecl>(VD);
1799 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001800 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1801 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001802 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001803 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001804}
1805
Alexey Bataev5a3af132016-03-29 08:58:54 +00001806static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1807 if (!Ref) {
1808 auto *CD =
1809 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1810 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1811 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1812 CaptureExpr->getExprLoc());
1813 }
1814 ExprResult Res = Ref;
1815 if (!S.getLangOpts().CPlusPlus &&
1816 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1817 Ref->getType()->isPointerType())
1818 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1819 if (!Res.isUsable())
1820 return ExprError();
1821 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001822}
1823
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001824namespace {
1825// OpenMP directives parsed in this section are represented as a
1826// CapturedStatement with an associated statement. If a syntax error
1827// is detected during the parsing of the associated statement, the
1828// compiler must abort processing and close the CapturedStatement.
1829//
1830// Combined directives such as 'target parallel' have more than one
1831// nested CapturedStatements. This RAII ensures that we unwind out
1832// of all the nested CapturedStatements when an error is found.
1833class CaptureRegionUnwinderRAII {
1834private:
1835 Sema &S;
1836 bool &ErrorFound;
1837 OpenMPDirectiveKind DKind;
1838
1839public:
1840 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1841 OpenMPDirectiveKind DKind)
1842 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1843 ~CaptureRegionUnwinderRAII() {
1844 if (ErrorFound) {
1845 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1846 while (--ThisCaptureLevel >= 0)
1847 S.ActOnCapturedRegionError();
1848 }
1849 }
1850};
1851} // namespace
1852
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001853StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1854 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001855 bool ErrorFound = false;
1856 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1857 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001858 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001859 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001860 return StmtError();
1861 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001862
1863 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001864 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001865 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001866 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001867 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001868 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001869 Clause->getClauseKind() == OMPC_copyprivate ||
1870 (getLangOpts().OpenMPUseTLS &&
1871 getASTContext().getTargetInfo().isTLSSupported() &&
1872 Clause->getClauseKind() == OMPC_copyin)) {
1873 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001874 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001875 for (auto *VarRef : Clause->children()) {
1876 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001877 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001878 }
1879 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001880 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001881 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001882 // Mark all variables in private list clauses as used in inner region.
1883 // Required for proper codegen of combined directives.
1884 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001885 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001886 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1887 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001888 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1889 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001890 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001891 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1892 if (auto *E = C->getPostUpdateExpr())
1893 MarkDeclarationsReferencedInExpr(E);
1894 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001895 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001896 if (Clause->getClauseKind() == OMPC_schedule)
1897 SC = cast<OMPScheduleClause>(Clause);
1898 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001899 OC = cast<OMPOrderedClause>(Clause);
1900 else if (Clause->getClauseKind() == OMPC_linear)
1901 LCs.push_back(cast<OMPLinearClause>(Clause));
1902 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001903 // OpenMP, 2.7.1 Loop Construct, Restrictions
1904 // The nonmonotonic modifier cannot be specified if an ordered clause is
1905 // specified.
1906 if (SC &&
1907 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1908 SC->getSecondScheduleModifier() ==
1909 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1910 OC) {
1911 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1912 ? SC->getFirstScheduleModifierLoc()
1913 : SC->getSecondScheduleModifierLoc(),
1914 diag::err_omp_schedule_nonmonotonic_ordered)
1915 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1916 ErrorFound = true;
1917 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001918 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1919 for (auto *C : LCs) {
1920 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1921 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1922 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001923 ErrorFound = true;
1924 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001925 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1926 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1927 OC->getNumForLoops()) {
1928 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1929 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1930 ErrorFound = true;
1931 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001932 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001933 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001934 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001935 StmtResult SR = S;
1936 int ThisCaptureLevel =
1937 getOpenMPCaptureLevels(DSAStack->getCurrentDirective());
1938 while (--ThisCaptureLevel >= 0)
1939 SR = ActOnCapturedRegionEnd(SR.get());
1940 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001941}
1942
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001943static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1944 OpenMPDirectiveKind CurrentRegion,
1945 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001946 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001947 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001948 if (Stack->getCurScope()) {
1949 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001950 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001951 bool NestingProhibited = false;
1952 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001953 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001954 enum {
1955 NoRecommend,
1956 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001957 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001958 ShouldBeInTargetRegion,
1959 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001960 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001961 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001962 // OpenMP [2.16, Nesting of Regions]
1963 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001964 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001965 // An ordered construct with the simd clause is the only OpenMP
1966 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001967 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001968 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1969 // message.
1970 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1971 ? diag::err_omp_prohibited_region_simd
1972 : diag::warn_omp_nesting_simd);
1973 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001974 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001975 if (ParentRegion == OMPD_atomic) {
1976 // OpenMP [2.16, Nesting of Regions]
1977 // OpenMP constructs may not be nested inside an atomic region.
1978 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1979 return true;
1980 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001981 if (CurrentRegion == OMPD_section) {
1982 // OpenMP [2.7.2, sections Construct, Restrictions]
1983 // Orphaned section directives are prohibited. That is, the section
1984 // directives must appear within the sections construct and must not be
1985 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001986 if (ParentRegion != OMPD_sections &&
1987 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001988 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1989 << (ParentRegion != OMPD_unknown)
1990 << getOpenMPDirectiveName(ParentRegion);
1991 return true;
1992 }
1993 return false;
1994 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001995 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001996 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001997 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00001998 if (ParentRegion == OMPD_unknown &&
1999 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002000 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002001 if (CurrentRegion == OMPD_cancellation_point ||
2002 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002003 // OpenMP [2.16, Nesting of Regions]
2004 // A cancellation point construct for which construct-type-clause is
2005 // taskgroup must be nested inside a task construct. A cancellation
2006 // point construct for which construct-type-clause is not taskgroup must
2007 // be closely nested inside an OpenMP construct that matches the type
2008 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002009 // A cancel construct for which construct-type-clause is taskgroup must be
2010 // nested inside a task construct. A cancel construct for which
2011 // construct-type-clause is not taskgroup must be closely nested inside an
2012 // OpenMP construct that matches the type specified in
2013 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002014 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002015 !((CancelRegion == OMPD_parallel &&
2016 (ParentRegion == OMPD_parallel ||
2017 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002018 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002019 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2020 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002021 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2022 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002023 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2024 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002025 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002026 // OpenMP [2.16, Nesting of Regions]
2027 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002028 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002029 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002030 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002031 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2032 // OpenMP [2.16, Nesting of Regions]
2033 // A critical region may not be nested (closely or otherwise) inside a
2034 // critical region with the same name. Note that this restriction is not
2035 // sufficient to prevent deadlock.
2036 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002037 bool DeadLock = Stack->hasDirective(
2038 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2039 const DeclarationNameInfo &DNI,
2040 SourceLocation Loc) -> bool {
2041 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2042 PreviousCriticalLoc = Loc;
2043 return true;
2044 } else
2045 return false;
2046 },
2047 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002048 if (DeadLock) {
2049 SemaRef.Diag(StartLoc,
2050 diag::err_omp_prohibited_region_critical_same_name)
2051 << CurrentName.getName();
2052 if (PreviousCriticalLoc.isValid())
2053 SemaRef.Diag(PreviousCriticalLoc,
2054 diag::note_omp_previous_critical_region);
2055 return true;
2056 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002057 } else if (CurrentRegion == OMPD_barrier) {
2058 // OpenMP [2.16, Nesting of Regions]
2059 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002060 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002061 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2062 isOpenMPTaskingDirective(ParentRegion) ||
2063 ParentRegion == OMPD_master ||
2064 ParentRegion == OMPD_critical ||
2065 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002066 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002067 !isOpenMPParallelDirective(CurrentRegion) &&
2068 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002069 // OpenMP [2.16, Nesting of Regions]
2070 // A worksharing region may not be closely nested inside a worksharing,
2071 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002072 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2073 isOpenMPTaskingDirective(ParentRegion) ||
2074 ParentRegion == OMPD_master ||
2075 ParentRegion == OMPD_critical ||
2076 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002077 Recommend = ShouldBeInParallelRegion;
2078 } else if (CurrentRegion == OMPD_ordered) {
2079 // OpenMP [2.16, Nesting of Regions]
2080 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002081 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002082 // An ordered region must be closely nested inside a loop region (or
2083 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002084 // OpenMP [2.8.1,simd Construct, Restrictions]
2085 // An ordered construct with the simd clause is the only OpenMP construct
2086 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002087 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002088 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002089 !(isOpenMPSimdDirective(ParentRegion) ||
2090 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002091 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002092 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002093 // OpenMP [2.16, Nesting of Regions]
2094 // If specified, a teams construct must be contained within a target
2095 // construct.
2096 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002097 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002098 Recommend = ShouldBeInTargetRegion;
2099 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2100 }
Kelvin Libf594a52016-12-17 05:48:59 +00002101 if (!NestingProhibited &&
2102 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2103 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2104 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002105 // OpenMP [2.16, Nesting of Regions]
2106 // distribute, parallel, parallel sections, parallel workshare, and the
2107 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2108 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002109 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2110 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002111 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002112 }
David Majnemer9d168222016-08-05 17:44:54 +00002113 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002114 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002115 // OpenMP 4.5 [2.17 Nesting of Regions]
2116 // The region associated with the distribute construct must be strictly
2117 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002118 NestingProhibited =
2119 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002120 Recommend = ShouldBeInTeamsRegion;
2121 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002122 if (!NestingProhibited &&
2123 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2124 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2125 // OpenMP 4.5 [2.17 Nesting of Regions]
2126 // If a target, target update, target data, target enter data, or
2127 // target exit data construct is encountered during execution of a
2128 // target region, the behavior is unspecified.
2129 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002130 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2131 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002132 if (isOpenMPTargetExecutionDirective(K)) {
2133 OffendingRegion = K;
2134 return true;
2135 } else
2136 return false;
2137 },
2138 false /* don't skip top directive */);
2139 CloseNesting = false;
2140 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002141 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002142 if (OrphanSeen) {
2143 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2144 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2145 } else {
2146 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2147 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2148 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2149 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002150 return true;
2151 }
2152 }
2153 return false;
2154}
2155
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002156static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2157 ArrayRef<OMPClause *> Clauses,
2158 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2159 bool ErrorFound = false;
2160 unsigned NamedModifiersNumber = 0;
2161 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2162 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002163 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002164 for (const auto *C : Clauses) {
2165 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2166 // At most one if clause without a directive-name-modifier can appear on
2167 // the directive.
2168 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2169 if (FoundNameModifiers[CurNM]) {
2170 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2171 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2172 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2173 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002174 } else if (CurNM != OMPD_unknown) {
2175 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002176 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002177 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002178 FoundNameModifiers[CurNM] = IC;
2179 if (CurNM == OMPD_unknown)
2180 continue;
2181 // Check if the specified name modifier is allowed for the current
2182 // directive.
2183 // At most one if clause with the particular directive-name-modifier can
2184 // appear on the directive.
2185 bool MatchFound = false;
2186 for (auto NM : AllowedNameModifiers) {
2187 if (CurNM == NM) {
2188 MatchFound = true;
2189 break;
2190 }
2191 }
2192 if (!MatchFound) {
2193 S.Diag(IC->getNameModifierLoc(),
2194 diag::err_omp_wrong_if_directive_name_modifier)
2195 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2196 ErrorFound = true;
2197 }
2198 }
2199 }
2200 // If any if clause on the directive includes a directive-name-modifier then
2201 // all if clauses on the directive must include a directive-name-modifier.
2202 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2203 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2204 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2205 diag::err_omp_no_more_if_clause);
2206 } else {
2207 std::string Values;
2208 std::string Sep(", ");
2209 unsigned AllowedCnt = 0;
2210 unsigned TotalAllowedNum =
2211 AllowedNameModifiers.size() - NamedModifiersNumber;
2212 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2213 ++Cnt) {
2214 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2215 if (!FoundNameModifiers[NM]) {
2216 Values += "'";
2217 Values += getOpenMPDirectiveName(NM);
2218 Values += "'";
2219 if (AllowedCnt + 2 == TotalAllowedNum)
2220 Values += " or ";
2221 else if (AllowedCnt + 1 != TotalAllowedNum)
2222 Values += Sep;
2223 ++AllowedCnt;
2224 }
2225 }
2226 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2227 diag::err_omp_unnamed_if_clause)
2228 << (TotalAllowedNum > 1) << Values;
2229 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002230 for (auto Loc : NameModifierLoc) {
2231 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2232 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002233 ErrorFound = true;
2234 }
2235 return ErrorFound;
2236}
2237
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002238StmtResult Sema::ActOnOpenMPExecutableDirective(
2239 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2240 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2241 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002242 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002243 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2244 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002245 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002246
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002247 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002248 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002249 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002250 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002251 if (AStmt) {
2252 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2253
2254 // Check default data sharing attributes for referenced variables.
2255 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2256 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2257 if (DSAChecker.isErrorFound())
2258 return StmtError();
2259 // Generate list of implicitly defined firstprivate variables.
2260 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002261
2262 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2263 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2264 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2265 SourceLocation(), SourceLocation())) {
2266 ClausesWithImplicit.push_back(Implicit);
2267 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2268 DSAChecker.getImplicitFirstprivate().size();
2269 } else
2270 ErrorFound = true;
2271 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002272 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002273
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002274 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002275 switch (Kind) {
2276 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002277 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2278 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002279 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002280 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002281 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002282 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2283 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002284 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002285 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002286 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2287 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002288 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002289 case OMPD_for_simd:
2290 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2291 EndLoc, VarsWithInheritedDSA);
2292 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002293 case OMPD_sections:
2294 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2295 EndLoc);
2296 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002297 case OMPD_section:
2298 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002299 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002300 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2301 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002302 case OMPD_single:
2303 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2304 EndLoc);
2305 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002306 case OMPD_master:
2307 assert(ClausesWithImplicit.empty() &&
2308 "No clauses are allowed for 'omp master' directive");
2309 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2310 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002311 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002312 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2313 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002314 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002315 case OMPD_parallel_for:
2316 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2317 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002318 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002319 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002320 case OMPD_parallel_for_simd:
2321 Res = ActOnOpenMPParallelForSimdDirective(
2322 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002323 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002324 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002325 case OMPD_parallel_sections:
2326 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2327 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002328 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002329 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002330 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002331 Res =
2332 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002333 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002334 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002335 case OMPD_taskyield:
2336 assert(ClausesWithImplicit.empty() &&
2337 "No clauses are allowed for 'omp taskyield' directive");
2338 assert(AStmt == nullptr &&
2339 "No associated statement allowed for 'omp taskyield' directive");
2340 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2341 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002342 case OMPD_barrier:
2343 assert(ClausesWithImplicit.empty() &&
2344 "No clauses are allowed for 'omp barrier' directive");
2345 assert(AStmt == nullptr &&
2346 "No associated statement allowed for 'omp barrier' directive");
2347 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2348 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002349 case OMPD_taskwait:
2350 assert(ClausesWithImplicit.empty() &&
2351 "No clauses are allowed for 'omp taskwait' directive");
2352 assert(AStmt == nullptr &&
2353 "No associated statement allowed for 'omp taskwait' directive");
2354 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2355 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002356 case OMPD_taskgroup:
2357 assert(ClausesWithImplicit.empty() &&
2358 "No clauses are allowed for 'omp taskgroup' directive");
2359 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2360 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002361 case OMPD_flush:
2362 assert(AStmt == nullptr &&
2363 "No associated statement allowed for 'omp flush' directive");
2364 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2365 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002366 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002367 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2368 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002369 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002370 case OMPD_atomic:
2371 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2372 EndLoc);
2373 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002374 case OMPD_teams:
2375 Res =
2376 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2377 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002378 case OMPD_target:
2379 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2380 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002381 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002382 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002383 case OMPD_target_parallel:
2384 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2385 StartLoc, EndLoc);
2386 AllowedNameModifiers.push_back(OMPD_target);
2387 AllowedNameModifiers.push_back(OMPD_parallel);
2388 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002389 case OMPD_target_parallel_for:
2390 Res = ActOnOpenMPTargetParallelForDirective(
2391 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2392 AllowedNameModifiers.push_back(OMPD_target);
2393 AllowedNameModifiers.push_back(OMPD_parallel);
2394 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002395 case OMPD_cancellation_point:
2396 assert(ClausesWithImplicit.empty() &&
2397 "No clauses are allowed for 'omp cancellation point' directive");
2398 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2399 "cancellation point' directive");
2400 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2401 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002402 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002403 assert(AStmt == nullptr &&
2404 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002405 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2406 CancelRegion);
2407 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002408 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002409 case OMPD_target_data:
2410 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2411 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002412 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002413 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002414 case OMPD_target_enter_data:
2415 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2416 EndLoc);
2417 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2418 break;
Samuel Antao72590762016-01-19 20:04:50 +00002419 case OMPD_target_exit_data:
2420 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2421 EndLoc);
2422 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2423 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002424 case OMPD_taskloop:
2425 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2426 EndLoc, VarsWithInheritedDSA);
2427 AllowedNameModifiers.push_back(OMPD_taskloop);
2428 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002429 case OMPD_taskloop_simd:
2430 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2431 EndLoc, VarsWithInheritedDSA);
2432 AllowedNameModifiers.push_back(OMPD_taskloop);
2433 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002434 case OMPD_distribute:
2435 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2436 EndLoc, VarsWithInheritedDSA);
2437 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002438 case OMPD_target_update:
2439 assert(!AStmt && "Statement is not allowed for target update");
2440 Res =
2441 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2442 AllowedNameModifiers.push_back(OMPD_target_update);
2443 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002444 case OMPD_distribute_parallel_for:
2445 Res = ActOnOpenMPDistributeParallelForDirective(
2446 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_parallel);
2448 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002449 case OMPD_distribute_parallel_for_simd:
2450 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2451 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2452 AllowedNameModifiers.push_back(OMPD_parallel);
2453 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002454 case OMPD_distribute_simd:
2455 Res = ActOnOpenMPDistributeSimdDirective(
2456 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2457 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002458 case OMPD_target_parallel_for_simd:
2459 Res = ActOnOpenMPTargetParallelForSimdDirective(
2460 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2461 AllowedNameModifiers.push_back(OMPD_target);
2462 AllowedNameModifiers.push_back(OMPD_parallel);
2463 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002464 case OMPD_target_simd:
2465 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2466 EndLoc, VarsWithInheritedDSA);
2467 AllowedNameModifiers.push_back(OMPD_target);
2468 break;
Kelvin Li02532872016-08-05 14:37:37 +00002469 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002470 Res = ActOnOpenMPTeamsDistributeDirective(
2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002472 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002473 case OMPD_teams_distribute_simd:
2474 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2475 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2476 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002477 case OMPD_teams_distribute_parallel_for_simd:
2478 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2479 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2480 AllowedNameModifiers.push_back(OMPD_parallel);
2481 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002482 case OMPD_teams_distribute_parallel_for:
2483 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2484 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2485 AllowedNameModifiers.push_back(OMPD_parallel);
2486 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002487 case OMPD_target_teams:
2488 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2489 EndLoc);
2490 AllowedNameModifiers.push_back(OMPD_target);
2491 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002492 case OMPD_target_teams_distribute:
2493 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2494 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2495 AllowedNameModifiers.push_back(OMPD_target);
2496 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002497 case OMPD_target_teams_distribute_parallel_for:
2498 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_target);
2501 AllowedNameModifiers.push_back(OMPD_parallel);
2502 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002503 case OMPD_target_teams_distribute_parallel_for_simd:
2504 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2505 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2506 AllowedNameModifiers.push_back(OMPD_target);
2507 AllowedNameModifiers.push_back(OMPD_parallel);
2508 break;
Kelvin Lida681182017-01-10 18:08:18 +00002509 case OMPD_target_teams_distribute_simd:
2510 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2511 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2512 AllowedNameModifiers.push_back(OMPD_target);
2513 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002514 case OMPD_declare_target:
2515 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002516 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002517 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002518 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002519 llvm_unreachable("OpenMP Directive is not allowed");
2520 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002521 llvm_unreachable("Unknown OpenMP directive");
2522 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002523
Alexey Bataev4acb8592014-07-07 13:01:15 +00002524 for (auto P : VarsWithInheritedDSA) {
2525 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2526 << P.first << P.second->getSourceRange();
2527 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002528 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2529
2530 if (!AllowedNameModifiers.empty())
2531 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2532 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002533
Alexey Bataeved09d242014-05-28 05:53:51 +00002534 if (ErrorFound)
2535 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002536 return Res;
2537}
2538
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002539Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2540 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002541 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002542 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2543 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002544 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002545 assert(Linears.size() == LinModifiers.size());
2546 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002547 if (!DG || DG.get().isNull())
2548 return DeclGroupPtrTy();
2549
2550 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002551 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002552 return DG;
2553 }
2554 auto *ADecl = DG.get().getSingleDecl();
2555 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2556 ADecl = FTD->getTemplatedDecl();
2557
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002558 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2559 if (!FD) {
2560 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002561 return DeclGroupPtrTy();
2562 }
2563
Alexey Bataev2af33e32016-04-07 12:45:37 +00002564 // OpenMP [2.8.2, declare simd construct, Description]
2565 // The parameter of the simdlen clause must be a constant positive integer
2566 // expression.
2567 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002568 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002569 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002570 // OpenMP [2.8.2, declare simd construct, Description]
2571 // The special this pointer can be used as if was one of the arguments to the
2572 // function in any of the linear, aligned, or uniform clauses.
2573 // The uniform clause declares one or more arguments to have an invariant
2574 // value for all concurrent invocations of the function in the execution of a
2575 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002576 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2577 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002578 for (auto *E : Uniforms) {
2579 E = E->IgnoreParenImpCasts();
2580 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2581 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2582 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2583 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002584 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2585 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002586 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002587 }
2588 if (isa<CXXThisExpr>(E)) {
2589 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002590 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002591 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002592 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2593 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002594 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002595 // OpenMP [2.8.2, declare simd construct, Description]
2596 // The aligned clause declares that the object to which each list item points
2597 // is aligned to the number of bytes expressed in the optional parameter of
2598 // the aligned clause.
2599 // The special this pointer can be used as if was one of the arguments to the
2600 // function in any of the linear, aligned, or uniform clauses.
2601 // The type of list items appearing in the aligned clause must be array,
2602 // pointer, reference to array, or reference to pointer.
2603 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2604 Expr *AlignedThis = nullptr;
2605 for (auto *E : Aligneds) {
2606 E = E->IgnoreParenImpCasts();
2607 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2608 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2609 auto *CanonPVD = PVD->getCanonicalDecl();
2610 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2611 FD->getParamDecl(PVD->getFunctionScopeIndex())
2612 ->getCanonicalDecl() == CanonPVD) {
2613 // OpenMP [2.8.1, simd construct, Restrictions]
2614 // A list-item cannot appear in more than one aligned clause.
2615 if (AlignedArgs.count(CanonPVD) > 0) {
2616 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2617 << 1 << E->getSourceRange();
2618 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2619 diag::note_omp_explicit_dsa)
2620 << getOpenMPClauseName(OMPC_aligned);
2621 continue;
2622 }
2623 AlignedArgs[CanonPVD] = E;
2624 QualType QTy = PVD->getType()
2625 .getNonReferenceType()
2626 .getUnqualifiedType()
2627 .getCanonicalType();
2628 const Type *Ty = QTy.getTypePtrOrNull();
2629 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2630 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2631 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2632 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2633 }
2634 continue;
2635 }
2636 }
2637 if (isa<CXXThisExpr>(E)) {
2638 if (AlignedThis) {
2639 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2640 << 2 << E->getSourceRange();
2641 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2642 << getOpenMPClauseName(OMPC_aligned);
2643 }
2644 AlignedThis = E;
2645 continue;
2646 }
2647 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2648 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2649 }
2650 // The optional parameter of the aligned clause, alignment, must be a constant
2651 // positive integer expression. If no optional parameter is specified,
2652 // implementation-defined default alignments for SIMD instructions on the
2653 // target platforms are assumed.
2654 SmallVector<Expr *, 4> NewAligns;
2655 for (auto *E : Alignments) {
2656 ExprResult Align;
2657 if (E)
2658 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2659 NewAligns.push_back(Align.get());
2660 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002661 // OpenMP [2.8.2, declare simd construct, Description]
2662 // The linear clause declares one or more list items to be private to a SIMD
2663 // lane and to have a linear relationship with respect to the iteration space
2664 // of a loop.
2665 // The special this pointer can be used as if was one of the arguments to the
2666 // function in any of the linear, aligned, or uniform clauses.
2667 // When a linear-step expression is specified in a linear clause it must be
2668 // either a constant integer expression or an integer-typed parameter that is
2669 // specified in a uniform clause on the directive.
2670 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2671 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2672 auto MI = LinModifiers.begin();
2673 for (auto *E : Linears) {
2674 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2675 ++MI;
2676 E = E->IgnoreParenImpCasts();
2677 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2678 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2679 auto *CanonPVD = PVD->getCanonicalDecl();
2680 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2681 FD->getParamDecl(PVD->getFunctionScopeIndex())
2682 ->getCanonicalDecl() == CanonPVD) {
2683 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2684 // A list-item cannot appear in more than one linear clause.
2685 if (LinearArgs.count(CanonPVD) > 0) {
2686 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2687 << getOpenMPClauseName(OMPC_linear)
2688 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2689 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2690 diag::note_omp_explicit_dsa)
2691 << getOpenMPClauseName(OMPC_linear);
2692 continue;
2693 }
2694 // Each argument can appear in at most one uniform or linear clause.
2695 if (UniformedArgs.count(CanonPVD) > 0) {
2696 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2697 << getOpenMPClauseName(OMPC_linear)
2698 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2699 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2700 diag::note_omp_explicit_dsa)
2701 << getOpenMPClauseName(OMPC_uniform);
2702 continue;
2703 }
2704 LinearArgs[CanonPVD] = E;
2705 if (E->isValueDependent() || E->isTypeDependent() ||
2706 E->isInstantiationDependent() ||
2707 E->containsUnexpandedParameterPack())
2708 continue;
2709 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2710 PVD->getOriginalType());
2711 continue;
2712 }
2713 }
2714 if (isa<CXXThisExpr>(E)) {
2715 if (UniformedLinearThis) {
2716 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2717 << getOpenMPClauseName(OMPC_linear)
2718 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2719 << E->getSourceRange();
2720 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2721 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2722 : OMPC_linear);
2723 continue;
2724 }
2725 UniformedLinearThis = E;
2726 if (E->isValueDependent() || E->isTypeDependent() ||
2727 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2728 continue;
2729 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2730 E->getType());
2731 continue;
2732 }
2733 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2734 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2735 }
2736 Expr *Step = nullptr;
2737 Expr *NewStep = nullptr;
2738 SmallVector<Expr *, 4> NewSteps;
2739 for (auto *E : Steps) {
2740 // Skip the same step expression, it was checked already.
2741 if (Step == E || !E) {
2742 NewSteps.push_back(E ? NewStep : nullptr);
2743 continue;
2744 }
2745 Step = E;
2746 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2747 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2748 auto *CanonPVD = PVD->getCanonicalDecl();
2749 if (UniformedArgs.count(CanonPVD) == 0) {
2750 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2751 << Step->getSourceRange();
2752 } else if (E->isValueDependent() || E->isTypeDependent() ||
2753 E->isInstantiationDependent() ||
2754 E->containsUnexpandedParameterPack() ||
2755 CanonPVD->getType()->hasIntegerRepresentation())
2756 NewSteps.push_back(Step);
2757 else {
2758 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2759 << Step->getSourceRange();
2760 }
2761 continue;
2762 }
2763 NewStep = Step;
2764 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2765 !Step->isInstantiationDependent() &&
2766 !Step->containsUnexpandedParameterPack()) {
2767 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2768 .get();
2769 if (NewStep)
2770 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2771 }
2772 NewSteps.push_back(NewStep);
2773 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002774 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2775 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002776 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002777 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2778 const_cast<Expr **>(Linears.data()), Linears.size(),
2779 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2780 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002781 ADecl->addAttr(NewAttr);
2782 return ConvertDeclToDeclGroup(ADecl);
2783}
2784
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002785StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2786 Stmt *AStmt,
2787 SourceLocation StartLoc,
2788 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002789 if (!AStmt)
2790 return StmtError();
2791
Alexey Bataev9959db52014-05-06 10:08:46 +00002792 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2793 // 1.2.2 OpenMP Language Terminology
2794 // Structured block - An executable statement with a single entry at the
2795 // top and a single exit at the bottom.
2796 // The point of exit cannot be a branch out of the structured block.
2797 // longjmp() and throw() must not violate the entry/exit criteria.
2798 CS->getCapturedDecl()->setNothrow();
2799
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002800 getCurFunction()->setHasBranchProtectedScope();
2801
Alexey Bataev25e5b442015-09-15 12:52:43 +00002802 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2803 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002804}
2805
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002806namespace {
2807/// \brief Helper class for checking canonical form of the OpenMP loops and
2808/// extracting iteration space of each loop in the loop nest, that will be used
2809/// for IR generation.
2810class OpenMPIterationSpaceChecker {
2811 /// \brief Reference to Sema.
2812 Sema &SemaRef;
2813 /// \brief A location for diagnostics (when there is no some better location).
2814 SourceLocation DefaultLoc;
2815 /// \brief A location for diagnostics (when increment is not compatible).
2816 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002817 /// \brief A source location for referring to loop init later.
2818 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002819 /// \brief A source location for referring to condition later.
2820 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002821 /// \brief A source location for referring to increment later.
2822 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002823 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002824 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002825 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002826 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002827 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002828 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002829 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002830 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002831 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002832 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002833 /// \brief This flag is true when condition is one of:
2834 /// Var < UB
2835 /// Var <= UB
2836 /// UB > Var
2837 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002838 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002839 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002840 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002841 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002842 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002843
2844public:
2845 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002846 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002847 /// \brief Check init-expr for canonical loop form and save loop counter
2848 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002849 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002850 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2851 /// for less/greater and for strict/non-strict comparison.
2852 bool CheckCond(Expr *S);
2853 /// \brief Check incr-expr for canonical loop form and return true if it
2854 /// does not conform, otherwise save loop step (#Step).
2855 bool CheckInc(Expr *S);
2856 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002857 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002858 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002859 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002860 /// \brief Source range of the loop init.
2861 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2862 /// \brief Source range of the loop condition.
2863 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2864 /// \brief Source range of the loop increment.
2865 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2866 /// \brief True if the step should be subtracted.
2867 bool ShouldSubtractStep() const { return SubtractStep; }
2868 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002869 Expr *
2870 BuildNumIterations(Scope *S, const bool LimitedType,
2871 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002872 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002873 Expr *BuildPreCond(Scope *S, Expr *Cond,
2874 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002875 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002876 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2877 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002878 /// \brief Build reference expression to the private counter be used for
2879 /// codegen.
2880 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002881 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002882 Expr *BuildCounterInit() const;
2883 /// \brief Build step of the counter be used for codegen.
2884 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002885 /// \brief Return true if any expression is dependent.
2886 bool Dependent() const;
2887
2888private:
2889 /// \brief Check the right-hand side of an assignment in the increment
2890 /// expression.
2891 bool CheckIncRHS(Expr *RHS);
2892 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002893 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002894 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002895 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002896 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002897 /// \brief Helper to set loop increment.
2898 bool SetStep(Expr *NewStep, bool Subtract);
2899};
2900
2901bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002902 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002903 assert(!LB && !UB && !Step);
2904 return false;
2905 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002906 return LCDecl->getType()->isDependentType() ||
2907 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2908 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002909}
2910
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002911static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002912 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2913 E = ExprTemp->getSubExpr();
2914
2915 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2916 E = MTE->GetTemporaryExpr();
2917
2918 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2919 E = Binder->getSubExpr();
2920
2921 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2922 E = ICE->getSubExprAsWritten();
2923 return E->IgnoreParens();
2924}
2925
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002926bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2927 Expr *NewLCRefExpr,
2928 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002929 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002930 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002931 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002932 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002933 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002934 LCDecl = getCanonicalDecl(NewLCDecl);
2935 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002936 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2937 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002938 if ((Ctor->isCopyOrMoveConstructor() ||
2939 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2940 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002941 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002942 LB = NewLB;
2943 return false;
2944}
2945
2946bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002947 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002948 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002949 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2950 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002951 if (!NewUB)
2952 return true;
2953 UB = NewUB;
2954 TestIsLessOp = LessOp;
2955 TestIsStrictOp = StrictOp;
2956 ConditionSrcRange = SR;
2957 ConditionLoc = SL;
2958 return false;
2959}
2960
2961bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2962 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002963 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002964 if (!NewStep)
2965 return true;
2966 if (!NewStep->isValueDependent()) {
2967 // Check that the step is integer expression.
2968 SourceLocation StepLoc = NewStep->getLocStart();
2969 ExprResult Val =
2970 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2971 if (Val.isInvalid())
2972 return true;
2973 NewStep = Val.get();
2974
2975 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2976 // If test-expr is of form var relational-op b and relational-op is < or
2977 // <= then incr-expr must cause var to increase on each iteration of the
2978 // loop. If test-expr is of form var relational-op b and relational-op is
2979 // > or >= then incr-expr must cause var to decrease on each iteration of
2980 // the loop.
2981 // If test-expr is of form b relational-op var and relational-op is < or
2982 // <= then incr-expr must cause var to decrease on each iteration of the
2983 // loop. If test-expr is of form b relational-op var and relational-op is
2984 // > or >= then incr-expr must cause var to increase on each iteration of
2985 // the loop.
2986 llvm::APSInt Result;
2987 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2988 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2989 bool IsConstNeg =
2990 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002991 bool IsConstPos =
2992 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002993 bool IsConstZero = IsConstant && !Result.getBoolValue();
2994 if (UB && (IsConstZero ||
2995 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002996 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002997 SemaRef.Diag(NewStep->getExprLoc(),
2998 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002999 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003000 SemaRef.Diag(ConditionLoc,
3001 diag::note_omp_loop_cond_requres_compatible_incr)
3002 << TestIsLessOp << ConditionSrcRange;
3003 return true;
3004 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003005 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003006 NewStep =
3007 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3008 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003009 Subtract = !Subtract;
3010 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003011 }
3012
3013 Step = NewStep;
3014 SubtractStep = Subtract;
3015 return false;
3016}
3017
Alexey Bataev9c821032015-04-30 04:23:23 +00003018bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003019 // Check init-expr for canonical loop form and save loop counter
3020 // variable - #Var and its initialization value - #LB.
3021 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3022 // var = lb
3023 // integer-type var = lb
3024 // random-access-iterator-type var = lb
3025 // pointer-type var = lb
3026 //
3027 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003028 if (EmitDiags) {
3029 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3030 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003031 return true;
3032 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003033 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3034 if (!ExprTemp->cleanupsHaveSideEffects())
3035 S = ExprTemp->getSubExpr();
3036
Alexander Musmana5f070a2014-10-01 06:03:56 +00003037 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003038 if (Expr *E = dyn_cast<Expr>(S))
3039 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003040 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003041 if (BO->getOpcode() == BO_Assign) {
3042 auto *LHS = BO->getLHS()->IgnoreParens();
3043 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3044 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3045 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3046 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3047 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3048 }
3049 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3050 if (ME->isArrow() &&
3051 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3052 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3053 }
3054 }
David Majnemer9d168222016-08-05 17:44:54 +00003055 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003056 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003057 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003058 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003059 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003060 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003061 SemaRef.Diag(S->getLocStart(),
3062 diag::ext_omp_loop_not_canonical_init)
3063 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003064 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003065 }
3066 }
3067 }
David Majnemer9d168222016-08-05 17:44:54 +00003068 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003069 if (CE->getOperator() == OO_Equal) {
3070 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003071 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003072 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3073 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3074 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3075 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3076 }
3077 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3078 if (ME->isArrow() &&
3079 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3080 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3081 }
3082 }
3083 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003084
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003085 if (Dependent() || SemaRef.CurContext->isDependentContext())
3086 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003087 if (EmitDiags) {
3088 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3089 << S->getSourceRange();
3090 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 return true;
3092}
3093
Alexey Bataev23b69422014-06-18 07:08:49 +00003094/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003095/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003096static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003097 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003098 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003099 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003100 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3101 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003102 if ((Ctor->isCopyOrMoveConstructor() ||
3103 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3104 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003105 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003106 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3107 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3108 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3109 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3110 return getCanonicalDecl(ME->getMemberDecl());
3111 return getCanonicalDecl(VD);
3112 }
3113 }
3114 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3115 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3116 return getCanonicalDecl(ME->getMemberDecl());
3117 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003118}
3119
3120bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3121 // Check test-expr for canonical form, save upper-bound UB, flags for
3122 // less/greater and for strict/non-strict comparison.
3123 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3124 // var relational-op b
3125 // b relational-op var
3126 //
3127 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003128 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 return true;
3130 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003131 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003132 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003133 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003134 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003135 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003136 return SetUB(BO->getRHS(),
3137 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3138 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3139 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003140 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003141 return SetUB(BO->getLHS(),
3142 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3143 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3144 BO->getSourceRange(), BO->getOperatorLoc());
3145 }
David Majnemer9d168222016-08-05 17:44:54 +00003146 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003147 if (CE->getNumArgs() == 2) {
3148 auto Op = CE->getOperator();
3149 switch (Op) {
3150 case OO_Greater:
3151 case OO_GreaterEqual:
3152 case OO_Less:
3153 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003154 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003155 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3156 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3157 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003158 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003159 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3160 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3161 CE->getOperatorLoc());
3162 break;
3163 default:
3164 break;
3165 }
3166 }
3167 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003168 if (Dependent() || SemaRef.CurContext->isDependentContext())
3169 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003170 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003171 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003172 return true;
3173}
3174
3175bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3176 // RHS of canonical loop form increment can be:
3177 // var + incr
3178 // incr + var
3179 // var - incr
3180 //
3181 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003182 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003183 if (BO->isAdditiveOp()) {
3184 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003185 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003187 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003188 return SetStep(BO->getLHS(), false);
3189 }
David Majnemer9d168222016-08-05 17:44:54 +00003190 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003191 bool IsAdd = CE->getOperator() == OO_Plus;
3192 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003193 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003194 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003195 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003196 return SetStep(CE->getArg(0), false);
3197 }
3198 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003199 if (Dependent() || SemaRef.CurContext->isDependentContext())
3200 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003201 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003202 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003203 return true;
3204}
3205
3206bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3207 // Check incr-expr for canonical loop form and return true if it
3208 // does not conform.
3209 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3210 // ++var
3211 // var++
3212 // --var
3213 // var--
3214 // var += incr
3215 // var -= incr
3216 // var = var + incr
3217 // var = incr + var
3218 // var = var - incr
3219 //
3220 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003221 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003222 return true;
3223 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003224 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3225 if (!ExprTemp->cleanupsHaveSideEffects())
3226 S = ExprTemp->getSubExpr();
3227
Alexander Musmana5f070a2014-10-01 06:03:56 +00003228 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003229 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003230 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003231 if (UO->isIncrementDecrementOp() &&
3232 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003233 return SetStep(SemaRef
3234 .ActOnIntegerConstant(UO->getLocStart(),
3235 (UO->isDecrementOp() ? -1 : 1))
3236 .get(),
3237 false);
3238 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003239 switch (BO->getOpcode()) {
3240 case BO_AddAssign:
3241 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003242 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003243 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3244 break;
3245 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003246 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003247 return CheckIncRHS(BO->getRHS());
3248 break;
3249 default:
3250 break;
3251 }
David Majnemer9d168222016-08-05 17:44:54 +00003252 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003253 switch (CE->getOperator()) {
3254 case OO_PlusPlus:
3255 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003256 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003257 return SetStep(SemaRef
3258 .ActOnIntegerConstant(
3259 CE->getLocStart(),
3260 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3261 .get(),
3262 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003263 break;
3264 case OO_PlusEqual:
3265 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003266 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003267 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3268 break;
3269 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003270 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003271 return CheckIncRHS(CE->getArg(1));
3272 break;
3273 default:
3274 break;
3275 }
3276 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003277 if (Dependent() || SemaRef.CurContext->isDependentContext())
3278 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003279 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003280 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003281 return true;
3282}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003283
Alexey Bataev5a3af132016-03-29 08:58:54 +00003284static ExprResult
3285tryBuildCapture(Sema &SemaRef, Expr *Capture,
3286 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003287 if (SemaRef.CurContext->isDependentContext())
3288 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003289 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3290 return SemaRef.PerformImplicitConversion(
3291 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3292 /*AllowExplicit=*/true);
3293 auto I = Captures.find(Capture);
3294 if (I != Captures.end())
3295 return buildCapture(SemaRef, Capture, I->second);
3296 DeclRefExpr *Ref = nullptr;
3297 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3298 Captures[Capture] = Ref;
3299 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003300}
3301
Alexander Musmana5f070a2014-10-01 06:03:56 +00003302/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003303Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3304 Scope *S, const bool LimitedType,
3305 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003306 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003307 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003308 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003309 SemaRef.getLangOpts().CPlusPlus) {
3310 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003311 auto *UBExpr = TestIsLessOp ? UB : LB;
3312 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003313 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3314 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003315 if (!Upper || !Lower)
3316 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003317
3318 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3319
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003320 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003321 // BuildBinOp already emitted error, this one is to point user to upper
3322 // and lower bound, and to tell what is passed to 'operator-'.
3323 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3324 << Upper->getSourceRange() << Lower->getSourceRange();
3325 return nullptr;
3326 }
3327 }
3328
3329 if (!Diff.isUsable())
3330 return nullptr;
3331
3332 // Upper - Lower [- 1]
3333 if (TestIsStrictOp)
3334 Diff = SemaRef.BuildBinOp(
3335 S, DefaultLoc, BO_Sub, Diff.get(),
3336 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3337 if (!Diff.isUsable())
3338 return nullptr;
3339
3340 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003341 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3342 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003343 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003344 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003345 if (!Diff.isUsable())
3346 return nullptr;
3347
3348 // Parentheses (for dumping/debugging purposes only).
3349 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3350 if (!Diff.isUsable())
3351 return nullptr;
3352
3353 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003354 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003355 if (!Diff.isUsable())
3356 return nullptr;
3357
Alexander Musman174b3ca2014-10-06 11:16:29 +00003358 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003359 QualType Type = Diff.get()->getType();
3360 auto &C = SemaRef.Context;
3361 bool UseVarType = VarType->hasIntegerRepresentation() &&
3362 C.getTypeSize(Type) > C.getTypeSize(VarType);
3363 if (!Type->isIntegerType() || UseVarType) {
3364 unsigned NewSize =
3365 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3366 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3367 : Type->hasSignedIntegerRepresentation();
3368 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003369 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3370 Diff = SemaRef.PerformImplicitConversion(
3371 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3372 if (!Diff.isUsable())
3373 return nullptr;
3374 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003375 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003376 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003377 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3378 if (NewSize != C.getTypeSize(Type)) {
3379 if (NewSize < C.getTypeSize(Type)) {
3380 assert(NewSize == 64 && "incorrect loop var size");
3381 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3382 << InitSrcRange << ConditionSrcRange;
3383 }
3384 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003385 NewSize, Type->hasSignedIntegerRepresentation() ||
3386 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003387 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3388 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3389 Sema::AA_Converting, true);
3390 if (!Diff.isUsable())
3391 return nullptr;
3392 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003393 }
3394 }
3395
Alexander Musmana5f070a2014-10-01 06:03:56 +00003396 return Diff.get();
3397}
3398
Alexey Bataev5a3af132016-03-29 08:58:54 +00003399Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3400 Scope *S, Expr *Cond,
3401 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003402 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3403 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3404 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003405
Alexey Bataev5a3af132016-03-29 08:58:54 +00003406 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3407 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3408 if (!NewLB.isUsable() || !NewUB.isUsable())
3409 return nullptr;
3410
Alexey Bataev62dbb972015-04-22 11:59:37 +00003411 auto CondExpr = SemaRef.BuildBinOp(
3412 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3413 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003414 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003415 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003416 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3417 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003418 CondExpr = SemaRef.PerformImplicitConversion(
3419 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3420 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003421 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003422 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3423 // Otherwise use original loop conditon and evaluate it in runtime.
3424 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3425}
3426
Alexander Musmana5f070a2014-10-01 06:03:56 +00003427/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003428DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003429 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003430 auto *VD = dyn_cast<VarDecl>(LCDecl);
3431 if (!VD) {
3432 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3433 auto *Ref = buildDeclRefExpr(
3434 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003435 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3436 // If the loop control decl is explicitly marked as private, do not mark it
3437 // as captured again.
3438 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3439 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003440 return Ref;
3441 }
3442 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003443 DefaultLoc);
3444}
3445
3446Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003447 if (LCDecl && !LCDecl->isInvalidDecl()) {
3448 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003449 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003450 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3451 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003452 if (PrivateVar->isInvalidDecl())
3453 return nullptr;
3454 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3455 }
3456 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003457}
3458
Samuel Antao4c8035b2016-12-12 18:00:20 +00003459/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003460Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3461
3462/// \brief Build step of the counter be used for codegen.
3463Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3464
3465/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003466struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003467 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003468 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003469 /// \brief This expression calculates the number of iterations in the loop.
3470 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003471 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003472 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003473 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003474 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003475 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003476 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003477 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003478 /// \brief This is step for the #CounterVar used to generate its update:
3479 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003480 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003481 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003482 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003483 /// \brief Source range of the loop init.
3484 SourceRange InitSrcRange;
3485 /// \brief Source range of the loop condition.
3486 SourceRange CondSrcRange;
3487 /// \brief Source range of the loop increment.
3488 SourceRange IncSrcRange;
3489};
3490
Alexey Bataev23b69422014-06-18 07:08:49 +00003491} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003492
Alexey Bataev9c821032015-04-30 04:23:23 +00003493void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3494 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3495 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003496 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3497 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003498 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3499 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003500 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3501 if (auto *D = ISC.GetLoopDecl()) {
3502 auto *VD = dyn_cast<VarDecl>(D);
3503 if (!VD) {
3504 if (auto *Private = IsOpenMPCapturedDecl(D))
3505 VD = Private;
3506 else {
3507 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3508 /*WithInit=*/false);
3509 VD = cast<VarDecl>(Ref->getDecl());
3510 }
3511 }
3512 DSAStack->addLoopControlVariable(D, VD);
3513 }
3514 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003515 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003516 }
3517}
3518
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003519/// \brief Called on a for stmt to check and extract its iteration space
3520/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003521static bool CheckOpenMPIterationSpace(
3522 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3523 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003524 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003525 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003526 LoopIterationSpace &ResultIterSpace,
3527 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003528 // OpenMP [2.6, Canonical Loop Form]
3529 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003530 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003531 if (!For) {
3532 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003533 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3534 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3535 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3536 if (NestedLoopCount > 1) {
3537 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3538 SemaRef.Diag(DSA.getConstructLoc(),
3539 diag::note_omp_collapse_ordered_expr)
3540 << 2 << CollapseLoopCountExpr->getSourceRange()
3541 << OrderedLoopCountExpr->getSourceRange();
3542 else if (CollapseLoopCountExpr)
3543 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3544 diag::note_omp_collapse_ordered_expr)
3545 << 0 << CollapseLoopCountExpr->getSourceRange();
3546 else
3547 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3548 diag::note_omp_collapse_ordered_expr)
3549 << 1 << OrderedLoopCountExpr->getSourceRange();
3550 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003551 return true;
3552 }
3553 assert(For->getBody());
3554
3555 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3556
3557 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003558 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003559 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003560 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003561
3562 bool HasErrors = false;
3563
3564 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003565 if (auto *LCDecl = ISC.GetLoopDecl()) {
3566 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003567
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003568 // OpenMP [2.6, Canonical Loop Form]
3569 // Var is one of the following:
3570 // A variable of signed or unsigned integer type.
3571 // For C++, a variable of a random access iterator type.
3572 // For C, a variable of a pointer type.
3573 auto VarType = LCDecl->getType().getNonReferenceType();
3574 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3575 !VarType->isPointerType() &&
3576 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3577 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3578 << SemaRef.getLangOpts().CPlusPlus;
3579 HasErrors = true;
3580 }
3581
3582 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3583 // a Construct
3584 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3585 // parallel for construct is (are) private.
3586 // The loop iteration variable in the associated for-loop of a simd
3587 // construct with just one associated for-loop is linear with a
3588 // constant-linear-step that is the increment of the associated for-loop.
3589 // Exclude loop var from the list of variables with implicitly defined data
3590 // sharing attributes.
3591 VarsWithImplicitDSA.erase(LCDecl);
3592
3593 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3594 // in a Construct, C/C++].
3595 // The loop iteration variable in the associated for-loop of a simd
3596 // construct with just one associated for-loop may be listed in a linear
3597 // clause with a constant-linear-step that is the increment of the
3598 // associated for-loop.
3599 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3600 // parallel for construct may be listed in a private or lastprivate clause.
3601 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3602 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3603 // declared in the loop and it is predetermined as a private.
3604 auto PredeterminedCKind =
3605 isOpenMPSimdDirective(DKind)
3606 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3607 : OMPC_private;
3608 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3609 DVar.CKind != PredeterminedCKind) ||
3610 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3611 isOpenMPDistributeDirective(DKind)) &&
3612 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3613 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3614 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3615 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3616 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3617 << getOpenMPClauseName(PredeterminedCKind);
3618 if (DVar.RefExpr == nullptr)
3619 DVar.CKind = PredeterminedCKind;
3620 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3621 HasErrors = true;
3622 } else if (LoopDeclRefExpr != nullptr) {
3623 // Make the loop iteration variable private (for worksharing constructs),
3624 // linear (for simd directives with the only one associated loop) or
3625 // lastprivate (for simd directives with several collapsed or ordered
3626 // loops).
3627 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003628 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3629 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003630 /*FromParent=*/false);
3631 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3632 }
3633
3634 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3635
3636 // Check test-expr.
3637 HasErrors |= ISC.CheckCond(For->getCond());
3638
3639 // Check incr-expr.
3640 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003641 }
3642
Alexander Musmana5f070a2014-10-01 06:03:56 +00003643 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003644 return HasErrors;
3645
Alexander Musmana5f070a2014-10-01 06:03:56 +00003646 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003647 ResultIterSpace.PreCond =
3648 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003649 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003650 DSA.getCurScope(),
3651 (isOpenMPWorksharingDirective(DKind) ||
3652 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3653 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003654 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003655 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003656 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3657 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3658 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3659 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3660 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3661 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3662
Alexey Bataev62dbb972015-04-22 11:59:37 +00003663 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3664 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003665 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003666 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003667 ResultIterSpace.CounterInit == nullptr ||
3668 ResultIterSpace.CounterStep == nullptr);
3669
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003670 return HasErrors;
3671}
3672
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003673/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003674static ExprResult
3675BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3676 ExprResult Start,
3677 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003678 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003679 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3680 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003681 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003682 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003683 VarRef.get()->getType())) {
3684 NewStart = SemaRef.PerformImplicitConversion(
3685 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3686 /*AllowExplicit=*/true);
3687 if (!NewStart.isUsable())
3688 return ExprError();
3689 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003690
3691 auto Init =
3692 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3693 return Init;
3694}
3695
Alexander Musmana5f070a2014-10-01 06:03:56 +00003696/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003697static ExprResult
3698BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3699 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3700 ExprResult Step, bool Subtract,
3701 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003702 // Add parentheses (for debugging purposes only).
3703 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3704 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3705 !Step.isUsable())
3706 return ExprError();
3707
Alexey Bataev5a3af132016-03-29 08:58:54 +00003708 ExprResult NewStep = Step;
3709 if (Captures)
3710 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003711 if (NewStep.isInvalid())
3712 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003713 ExprResult Update =
3714 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003715 if (!Update.isUsable())
3716 return ExprError();
3717
Alexey Bataevc0214e02016-02-16 12:13:49 +00003718 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3719 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003720 ExprResult NewStart = Start;
3721 if (Captures)
3722 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003723 if (NewStart.isInvalid())
3724 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003725
Alexey Bataevc0214e02016-02-16 12:13:49 +00003726 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3727 ExprResult SavedUpdate = Update;
3728 ExprResult UpdateVal;
3729 if (VarRef.get()->getType()->isOverloadableType() ||
3730 NewStart.get()->getType()->isOverloadableType() ||
3731 Update.get()->getType()->isOverloadableType()) {
3732 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3733 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3734 Update =
3735 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3736 if (Update.isUsable()) {
3737 UpdateVal =
3738 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3739 VarRef.get(), SavedUpdate.get());
3740 if (UpdateVal.isUsable()) {
3741 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3742 UpdateVal.get());
3743 }
3744 }
3745 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3746 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003747
Alexey Bataevc0214e02016-02-16 12:13:49 +00003748 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3749 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3750 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3751 NewStart.get(), SavedUpdate.get());
3752 if (!Update.isUsable())
3753 return ExprError();
3754
Alexey Bataev11481f52016-02-17 10:29:05 +00003755 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3756 VarRef.get()->getType())) {
3757 Update = SemaRef.PerformImplicitConversion(
3758 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3759 if (!Update.isUsable())
3760 return ExprError();
3761 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003762
3763 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3764 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003765 return Update;
3766}
3767
3768/// \brief Convert integer expression \a E to make it have at least \a Bits
3769/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003770static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003771 if (E == nullptr)
3772 return ExprError();
3773 auto &C = SemaRef.Context;
3774 QualType OldType = E->getType();
3775 unsigned HasBits = C.getTypeSize(OldType);
3776 if (HasBits >= Bits)
3777 return ExprResult(E);
3778 // OK to convert to signed, because new type has more bits than old.
3779 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3780 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3781 true);
3782}
3783
3784/// \brief Check if the given expression \a E is a constant integer that fits
3785/// into \a Bits bits.
3786static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3787 if (E == nullptr)
3788 return false;
3789 llvm::APSInt Result;
3790 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3791 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3792 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003793}
3794
Alexey Bataev5a3af132016-03-29 08:58:54 +00003795/// Build preinits statement for the given declarations.
3796static Stmt *buildPreInits(ASTContext &Context,
3797 SmallVectorImpl<Decl *> &PreInits) {
3798 if (!PreInits.empty()) {
3799 return new (Context) DeclStmt(
3800 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3801 SourceLocation(), SourceLocation());
3802 }
3803 return nullptr;
3804}
3805
3806/// Build preinits statement for the given declarations.
3807static Stmt *buildPreInits(ASTContext &Context,
3808 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3809 if (!Captures.empty()) {
3810 SmallVector<Decl *, 16> PreInits;
3811 for (auto &Pair : Captures)
3812 PreInits.push_back(Pair.second->getDecl());
3813 return buildPreInits(Context, PreInits);
3814 }
3815 return nullptr;
3816}
3817
3818/// Build postupdate expression for the given list of postupdates expressions.
3819static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3820 Expr *PostUpdate = nullptr;
3821 if (!PostUpdates.empty()) {
3822 for (auto *E : PostUpdates) {
3823 Expr *ConvE = S.BuildCStyleCastExpr(
3824 E->getExprLoc(),
3825 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3826 E->getExprLoc(), E)
3827 .get();
3828 PostUpdate = PostUpdate
3829 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3830 PostUpdate, ConvE)
3831 .get()
3832 : ConvE;
3833 }
3834 }
3835 return PostUpdate;
3836}
3837
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003838/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003839/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3840/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003841static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003842CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3843 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3844 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003845 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003846 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003847 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003848 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003849 // Found 'collapse' clause - calculate collapse number.
3850 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003851 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003852 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003853 }
3854 if (OrderedLoopCountExpr) {
3855 // Found 'ordered' clause - calculate collapse number.
3856 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003857 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3858 if (Result.getLimitedValue() < NestedLoopCount) {
3859 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3860 diag::err_omp_wrong_ordered_loop_count)
3861 << OrderedLoopCountExpr->getSourceRange();
3862 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3863 diag::note_collapse_loop_count)
3864 << CollapseLoopCountExpr->getSourceRange();
3865 }
3866 NestedLoopCount = Result.getLimitedValue();
3867 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003868 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003869 // This is helper routine for loop directives (e.g., 'for', 'simd',
3870 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003871 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003872 SmallVector<LoopIterationSpace, 4> IterSpaces;
3873 IterSpaces.resize(NestedLoopCount);
3874 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003875 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003876 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003877 NestedLoopCount, CollapseLoopCountExpr,
3878 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003879 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003880 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003881 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003882 // OpenMP [2.8.1, simd construct, Restrictions]
3883 // All loops associated with the construct must be perfectly nested; that
3884 // is, there must be no intervening code nor any OpenMP directive between
3885 // any two loops.
3886 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003887 }
3888
Alexander Musmana5f070a2014-10-01 06:03:56 +00003889 Built.clear(/* size */ NestedLoopCount);
3890
3891 if (SemaRef.CurContext->isDependentContext())
3892 return NestedLoopCount;
3893
3894 // An example of what is generated for the following code:
3895 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003896 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003897 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003898 // for (k = 0; k < NK; ++k)
3899 // for (j = J0; j < NJ; j+=2) {
3900 // <loop body>
3901 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003902 //
3903 // We generate the code below.
3904 // Note: the loop body may be outlined in CodeGen.
3905 // Note: some counters may be C++ classes, operator- is used to find number of
3906 // iterations and operator+= to calculate counter value.
3907 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3908 // or i64 is currently supported).
3909 //
3910 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3911 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3912 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3913 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3914 // // similar updates for vars in clauses (e.g. 'linear')
3915 // <loop body (using local i and j)>
3916 // }
3917 // i = NI; // assign final values of counters
3918 // j = NJ;
3919 //
3920
3921 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3922 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003923 // Precondition tests if there is at least one iteration (all conditions are
3924 // true).
3925 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003926 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003927 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003928 32 /* Bits */, SemaRef
3929 .PerformImplicitConversion(
3930 N0->IgnoreImpCasts(), N0->getType(),
3931 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003932 .get(),
3933 SemaRef);
3934 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003935 64 /* Bits */, SemaRef
3936 .PerformImplicitConversion(
3937 N0->IgnoreImpCasts(), N0->getType(),
3938 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003939 .get(),
3940 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003941
3942 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3943 return NestedLoopCount;
3944
3945 auto &C = SemaRef.Context;
3946 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3947
3948 Scope *CurScope = DSA.getCurScope();
3949 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003950 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003951 PreCond =
3952 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3953 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003954 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003955 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003956 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003957 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3958 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003959 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003960 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003961 SemaRef
3962 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3963 Sema::AA_Converting,
3964 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003965 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003966 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003967 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003968 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003969 SemaRef
3970 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3971 Sema::AA_Converting,
3972 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003973 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003974 }
3975
3976 // Choose either the 32-bit or 64-bit version.
3977 ExprResult LastIteration = LastIteration64;
3978 if (LastIteration32.isUsable() &&
3979 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3980 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3981 FitsInto(
3982 32 /* Bits */,
3983 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3984 LastIteration64.get(), SemaRef)))
3985 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003986 QualType VType = LastIteration.get()->getType();
3987 QualType RealVType = VType;
3988 QualType StrideVType = VType;
3989 if (isOpenMPTaskLoopDirective(DKind)) {
3990 VType =
3991 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3992 StrideVType =
3993 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3994 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003995
3996 if (!LastIteration.isUsable())
3997 return 0;
3998
3999 // Save the number of iterations.
4000 ExprResult NumIterations = LastIteration;
4001 {
4002 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004003 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4004 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004005 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4006 if (!LastIteration.isUsable())
4007 return 0;
4008 }
4009
4010 // Calculate the last iteration number beforehand instead of doing this on
4011 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4012 llvm::APSInt Result;
4013 bool IsConstant =
4014 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4015 ExprResult CalcLastIteration;
4016 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004017 ExprResult SaveRef =
4018 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004019 LastIteration = SaveRef;
4020
4021 // Prepare SaveRef + 1.
4022 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004023 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004024 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4025 if (!NumIterations.isUsable())
4026 return 0;
4027 }
4028
4029 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4030
David Majnemer9d168222016-08-05 17:44:54 +00004031 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00004032 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004033 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4034 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004035 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004036 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4037 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004038 SemaRef.AddInitializerToDecl(LBDecl,
4039 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4040 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004041
4042 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004043 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4044 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004045 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004046 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004047
4048 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4049 // This will be used to implement clause 'lastprivate'.
4050 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004051 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4052 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004053 SemaRef.AddInitializerToDecl(ILDecl,
4054 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4055 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004056
4057 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004058 VarDecl *STDecl =
4059 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4060 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004061 SemaRef.AddInitializerToDecl(STDecl,
4062 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4063 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004064
4065 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004066 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004067 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4068 UB.get(), LastIteration.get());
4069 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4070 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4071 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4072 CondOp.get());
4073 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004074
4075 // If we have a combined directive that combines 'distribute', 'for' or
4076 // 'simd' we need to be able to access the bounds of the schedule of the
4077 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4078 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4079 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4080 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4081
4082 // We expect to have at least 2 more parameters than the 'parallel'
4083 // directive does - the lower and upper bounds of the previous schedule.
4084 assert(CD->getNumParams() >= 4 &&
4085 "Unexpected number of parameters in loop combined directive");
4086
4087 // Set the proper type for the bounds given what we learned from the
4088 // enclosed loops.
4089 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4090 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4091
4092 // Previous lower and upper bounds are obtained from the region
4093 // parameters.
4094 PrevLB =
4095 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4096 PrevUB =
4097 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4098 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004099 }
4100
4101 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004102 ExprResult IV;
4103 ExprResult Init;
4104 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004105 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4106 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004107 Expr *RHS =
4108 (isOpenMPWorksharingDirective(DKind) ||
4109 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4110 ? LB.get()
4111 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004112 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4113 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004114 }
4115
Alexander Musmanc6388682014-12-15 07:07:06 +00004116 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004117 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004118 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004119 (isOpenMPWorksharingDirective(DKind) ||
4120 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004121 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4122 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4123 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004124
4125 // Loop increment (IV = IV + 1)
4126 SourceLocation IncLoc;
4127 ExprResult Inc =
4128 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4129 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4130 if (!Inc.isUsable())
4131 return 0;
4132 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004133 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4134 if (!Inc.isUsable())
4135 return 0;
4136
4137 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4138 // Used for directives with static scheduling.
4139 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004140 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4141 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004142 // LB + ST
4143 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4144 if (!NextLB.isUsable())
4145 return 0;
4146 // LB = LB + ST
4147 NextLB =
4148 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4149 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4150 if (!NextLB.isUsable())
4151 return 0;
4152 // UB + ST
4153 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4154 if (!NextUB.isUsable())
4155 return 0;
4156 // UB = UB + ST
4157 NextUB =
4158 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4159 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4160 if (!NextUB.isUsable())
4161 return 0;
4162 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004163
4164 // Build updates and final values of the loop counters.
4165 bool HasErrors = false;
4166 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004167 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004168 Built.Updates.resize(NestedLoopCount);
4169 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004170 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004171 {
4172 ExprResult Div;
4173 // Go from inner nested loop to outer.
4174 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4175 LoopIterationSpace &IS = IterSpaces[Cnt];
4176 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4177 // Build: Iter = (IV / Div) % IS.NumIters
4178 // where Div is product of previous iterations' IS.NumIters.
4179 ExprResult Iter;
4180 if (Div.isUsable()) {
4181 Iter =
4182 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4183 } else {
4184 Iter = IV;
4185 assert((Cnt == (int)NestedLoopCount - 1) &&
4186 "unusable div expected on first iteration only");
4187 }
4188
4189 if (Cnt != 0 && Iter.isUsable())
4190 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4191 IS.NumIterations);
4192 if (!Iter.isUsable()) {
4193 HasErrors = true;
4194 break;
4195 }
4196
Alexey Bataev39f915b82015-05-08 10:41:21 +00004197 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004198 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4199 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4200 IS.CounterVar->getExprLoc(),
4201 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004202 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004203 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004204 if (!Init.isUsable()) {
4205 HasErrors = true;
4206 break;
4207 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004208 ExprResult Update = BuildCounterUpdate(
4209 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4210 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004211 if (!Update.isUsable()) {
4212 HasErrors = true;
4213 break;
4214 }
4215
4216 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4217 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004218 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004219 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004220 if (!Final.isUsable()) {
4221 HasErrors = true;
4222 break;
4223 }
4224
4225 // Build Div for the next iteration: Div <- Div * IS.NumIters
4226 if (Cnt != 0) {
4227 if (Div.isUnset())
4228 Div = IS.NumIterations;
4229 else
4230 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4231 IS.NumIterations);
4232
4233 // Add parentheses (for debugging purposes only).
4234 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004235 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004236 if (!Div.isUsable()) {
4237 HasErrors = true;
4238 break;
4239 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004240 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004241 }
4242 if (!Update.isUsable() || !Final.isUsable()) {
4243 HasErrors = true;
4244 break;
4245 }
4246 // Save results
4247 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004248 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004249 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004250 Built.Updates[Cnt] = Update.get();
4251 Built.Finals[Cnt] = Final.get();
4252 }
4253 }
4254
4255 if (HasErrors)
4256 return 0;
4257
4258 // Save results
4259 Built.IterationVarRef = IV.get();
4260 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004261 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004262 Built.CalcLastIteration =
4263 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004264 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004265 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004266 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004267 Built.Init = Init.get();
4268 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004269 Built.LB = LB.get();
4270 Built.UB = UB.get();
4271 Built.IL = IL.get();
4272 Built.ST = ST.get();
4273 Built.EUB = EUB.get();
4274 Built.NLB = NextLB.get();
4275 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004276 Built.PrevLB = PrevLB.get();
4277 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004278
Alexey Bataev8b427062016-05-25 12:36:08 +00004279 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4280 // Fill data for doacross depend clauses.
4281 for (auto Pair : DSA.getDoacrossDependClauses()) {
4282 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4283 Pair.first->setCounterValue(CounterVal);
4284 else {
4285 if (NestedLoopCount != Pair.second.size() ||
4286 NestedLoopCount != LoopMultipliers.size() + 1) {
4287 // Erroneous case - clause has some problems.
4288 Pair.first->setCounterValue(CounterVal);
4289 continue;
4290 }
4291 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4292 auto I = Pair.second.rbegin();
4293 auto IS = IterSpaces.rbegin();
4294 auto ILM = LoopMultipliers.rbegin();
4295 Expr *UpCounterVal = CounterVal;
4296 Expr *Multiplier = nullptr;
4297 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4298 if (I->first) {
4299 assert(IS->CounterStep);
4300 Expr *NormalizedOffset =
4301 SemaRef
4302 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4303 I->first, IS->CounterStep)
4304 .get();
4305 if (Multiplier) {
4306 NormalizedOffset =
4307 SemaRef
4308 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4309 NormalizedOffset, Multiplier)
4310 .get();
4311 }
4312 assert(I->second == OO_Plus || I->second == OO_Minus);
4313 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004314 UpCounterVal = SemaRef
4315 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4316 UpCounterVal, NormalizedOffset)
4317 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004318 }
4319 Multiplier = *ILM;
4320 ++I;
4321 ++IS;
4322 ++ILM;
4323 }
4324 Pair.first->setCounterValue(UpCounterVal);
4325 }
4326 }
4327
Alexey Bataevabfc0692014-06-25 06:52:00 +00004328 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004329}
4330
Alexey Bataev10e775f2015-07-30 11:36:16 +00004331static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004332 auto CollapseClauses =
4333 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4334 if (CollapseClauses.begin() != CollapseClauses.end())
4335 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004336 return nullptr;
4337}
4338
Alexey Bataev10e775f2015-07-30 11:36:16 +00004339static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004340 auto OrderedClauses =
4341 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4342 if (OrderedClauses.begin() != OrderedClauses.end())
4343 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004344 return nullptr;
4345}
4346
Kelvin Lic5609492016-07-15 04:39:07 +00004347static bool checkSimdlenSafelenSpecified(Sema &S,
4348 const ArrayRef<OMPClause *> Clauses) {
4349 OMPSafelenClause *Safelen = nullptr;
4350 OMPSimdlenClause *Simdlen = nullptr;
4351
4352 for (auto *Clause : Clauses) {
4353 if (Clause->getClauseKind() == OMPC_safelen)
4354 Safelen = cast<OMPSafelenClause>(Clause);
4355 else if (Clause->getClauseKind() == OMPC_simdlen)
4356 Simdlen = cast<OMPSimdlenClause>(Clause);
4357 if (Safelen && Simdlen)
4358 break;
4359 }
4360
4361 if (Simdlen && Safelen) {
4362 llvm::APSInt SimdlenRes, SafelenRes;
4363 auto SimdlenLength = Simdlen->getSimdlen();
4364 auto SafelenLength = Safelen->getSafelen();
4365 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4366 SimdlenLength->isInstantiationDependent() ||
4367 SimdlenLength->containsUnexpandedParameterPack())
4368 return false;
4369 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4370 SafelenLength->isInstantiationDependent() ||
4371 SafelenLength->containsUnexpandedParameterPack())
4372 return false;
4373 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4374 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4375 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4376 // If both simdlen and safelen clauses are specified, the value of the
4377 // simdlen parameter must be less than or equal to the value of the safelen
4378 // parameter.
4379 if (SimdlenRes > SafelenRes) {
4380 S.Diag(SimdlenLength->getExprLoc(),
4381 diag::err_omp_wrong_simdlen_safelen_values)
4382 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4383 return true;
4384 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004385 }
4386 return false;
4387}
4388
Alexey Bataev4acb8592014-07-07 13:01:15 +00004389StmtResult Sema::ActOnOpenMPSimdDirective(
4390 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4391 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004392 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004393 if (!AStmt)
4394 return StmtError();
4395
4396 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004397 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004398 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4399 // define the nested loops number.
4400 unsigned NestedLoopCount = CheckOpenMPLoop(
4401 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4402 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004403 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004404 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004405
Alexander Musmana5f070a2014-10-01 06:03:56 +00004406 assert((CurContext->isDependentContext() || B.builtAll()) &&
4407 "omp simd loop exprs were not built");
4408
Alexander Musman3276a272015-03-21 10:12:56 +00004409 if (!CurContext->isDependentContext()) {
4410 // Finalize the clauses that need pre-built expressions for CodeGen.
4411 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004412 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004413 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004414 B.NumIterations, *this, CurScope,
4415 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004416 return StmtError();
4417 }
4418 }
4419
Kelvin Lic5609492016-07-15 04:39:07 +00004420 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004421 return StmtError();
4422
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004423 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004424 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4425 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004426}
4427
Alexey Bataev4acb8592014-07-07 13:01:15 +00004428StmtResult Sema::ActOnOpenMPForDirective(
4429 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4430 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004431 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004432 if (!AStmt)
4433 return StmtError();
4434
4435 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004436 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004437 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4438 // define the nested loops number.
4439 unsigned NestedLoopCount = CheckOpenMPLoop(
4440 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4441 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004442 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004443 return StmtError();
4444
Alexander Musmana5f070a2014-10-01 06:03:56 +00004445 assert((CurContext->isDependentContext() || B.builtAll()) &&
4446 "omp for loop exprs were not built");
4447
Alexey Bataev54acd402015-08-04 11:18:19 +00004448 if (!CurContext->isDependentContext()) {
4449 // Finalize the clauses that need pre-built expressions for CodeGen.
4450 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004451 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004452 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004453 B.NumIterations, *this, CurScope,
4454 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004455 return StmtError();
4456 }
4457 }
4458
Alexey Bataevf29276e2014-06-18 04:14:57 +00004459 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004460 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004461 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004462}
4463
Alexander Musmanf82886e2014-09-18 05:12:34 +00004464StmtResult Sema::ActOnOpenMPForSimdDirective(
4465 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4466 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004467 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004468 if (!AStmt)
4469 return StmtError();
4470
4471 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004472 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004473 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4474 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004475 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004476 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4477 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4478 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004479 if (NestedLoopCount == 0)
4480 return StmtError();
4481
Alexander Musmanc6388682014-12-15 07:07:06 +00004482 assert((CurContext->isDependentContext() || B.builtAll()) &&
4483 "omp for simd loop exprs were not built");
4484
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004485 if (!CurContext->isDependentContext()) {
4486 // Finalize the clauses that need pre-built expressions for CodeGen.
4487 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004488 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004489 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004490 B.NumIterations, *this, CurScope,
4491 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004492 return StmtError();
4493 }
4494 }
4495
Kelvin Lic5609492016-07-15 04:39:07 +00004496 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004497 return StmtError();
4498
Alexander Musmanf82886e2014-09-18 05:12:34 +00004499 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004500 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4501 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004502}
4503
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004504StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4505 Stmt *AStmt,
4506 SourceLocation StartLoc,
4507 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004508 if (!AStmt)
4509 return StmtError();
4510
4511 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004512 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004513 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004514 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004515 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004516 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004517 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004518 return StmtError();
4519 // All associated statements must be '#pragma omp section' except for
4520 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004521 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004522 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4523 if (SectionStmt)
4524 Diag(SectionStmt->getLocStart(),
4525 diag::err_omp_sections_substmt_not_section);
4526 return StmtError();
4527 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004528 cast<OMPSectionDirective>(SectionStmt)
4529 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004530 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004531 } else {
4532 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4533 return StmtError();
4534 }
4535
4536 getCurFunction()->setHasBranchProtectedScope();
4537
Alexey Bataev25e5b442015-09-15 12:52:43 +00004538 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4539 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004540}
4541
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004542StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4543 SourceLocation StartLoc,
4544 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004545 if (!AStmt)
4546 return StmtError();
4547
4548 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004549
4550 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004551 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004552
Alexey Bataev25e5b442015-09-15 12:52:43 +00004553 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4554 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004555}
4556
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004557StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4558 Stmt *AStmt,
4559 SourceLocation StartLoc,
4560 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004561 if (!AStmt)
4562 return StmtError();
4563
4564 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004565
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004566 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004567
Alexey Bataev3255bf32015-01-19 05:20:46 +00004568 // OpenMP [2.7.3, single Construct, Restrictions]
4569 // The copyprivate clause must not be used with the nowait clause.
4570 OMPClause *Nowait = nullptr;
4571 OMPClause *Copyprivate = nullptr;
4572 for (auto *Clause : Clauses) {
4573 if (Clause->getClauseKind() == OMPC_nowait)
4574 Nowait = Clause;
4575 else if (Clause->getClauseKind() == OMPC_copyprivate)
4576 Copyprivate = Clause;
4577 if (Copyprivate && Nowait) {
4578 Diag(Copyprivate->getLocStart(),
4579 diag::err_omp_single_copyprivate_with_nowait);
4580 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4581 return StmtError();
4582 }
4583 }
4584
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004585 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4586}
4587
Alexander Musman80c22892014-07-17 08:54:58 +00004588StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4589 SourceLocation StartLoc,
4590 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004591 if (!AStmt)
4592 return StmtError();
4593
4594 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004595
4596 getCurFunction()->setHasBranchProtectedScope();
4597
4598 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4599}
4600
Alexey Bataev28c75412015-12-15 08:19:24 +00004601StmtResult Sema::ActOnOpenMPCriticalDirective(
4602 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4603 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004604 if (!AStmt)
4605 return StmtError();
4606
4607 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004608
Alexey Bataev28c75412015-12-15 08:19:24 +00004609 bool ErrorFound = false;
4610 llvm::APSInt Hint;
4611 SourceLocation HintLoc;
4612 bool DependentHint = false;
4613 for (auto *C : Clauses) {
4614 if (C->getClauseKind() == OMPC_hint) {
4615 if (!DirName.getName()) {
4616 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4617 ErrorFound = true;
4618 }
4619 Expr *E = cast<OMPHintClause>(C)->getHint();
4620 if (E->isTypeDependent() || E->isValueDependent() ||
4621 E->isInstantiationDependent())
4622 DependentHint = true;
4623 else {
4624 Hint = E->EvaluateKnownConstInt(Context);
4625 HintLoc = C->getLocStart();
4626 }
4627 }
4628 }
4629 if (ErrorFound)
4630 return StmtError();
4631 auto Pair = DSAStack->getCriticalWithHint(DirName);
4632 if (Pair.first && DirName.getName() && !DependentHint) {
4633 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4634 Diag(StartLoc, diag::err_omp_critical_with_hint);
4635 if (HintLoc.isValid()) {
4636 Diag(HintLoc, diag::note_omp_critical_hint_here)
4637 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4638 } else
4639 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4640 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4641 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4642 << 1
4643 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4644 /*Radix=*/10, /*Signed=*/false);
4645 } else
4646 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4647 }
4648 }
4649
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004650 getCurFunction()->setHasBranchProtectedScope();
4651
Alexey Bataev28c75412015-12-15 08:19:24 +00004652 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4653 Clauses, AStmt);
4654 if (!Pair.first && DirName.getName() && !DependentHint)
4655 DSAStack->addCriticalWithHint(Dir, Hint);
4656 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004657}
4658
Alexey Bataev4acb8592014-07-07 13:01:15 +00004659StmtResult Sema::ActOnOpenMPParallelForDirective(
4660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4661 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004662 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004663 if (!AStmt)
4664 return StmtError();
4665
Alexey Bataev4acb8592014-07-07 13:01:15 +00004666 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4667 // 1.2.2 OpenMP Language Terminology
4668 // Structured block - An executable statement with a single entry at the
4669 // top and a single exit at the bottom.
4670 // The point of exit cannot be a branch out of the structured block.
4671 // longjmp() and throw() must not violate the entry/exit criteria.
4672 CS->getCapturedDecl()->setNothrow();
4673
Alexander Musmanc6388682014-12-15 07:07:06 +00004674 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004675 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4676 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004677 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004678 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4679 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4680 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004681 if (NestedLoopCount == 0)
4682 return StmtError();
4683
Alexander Musmana5f070a2014-10-01 06:03:56 +00004684 assert((CurContext->isDependentContext() || B.builtAll()) &&
4685 "omp parallel for loop exprs were not built");
4686
Alexey Bataev54acd402015-08-04 11:18:19 +00004687 if (!CurContext->isDependentContext()) {
4688 // Finalize the clauses that need pre-built expressions for CodeGen.
4689 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004690 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004691 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004692 B.NumIterations, *this, CurScope,
4693 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004694 return StmtError();
4695 }
4696 }
4697
Alexey Bataev4acb8592014-07-07 13:01:15 +00004698 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004699 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004700 NestedLoopCount, Clauses, AStmt, B,
4701 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004702}
4703
Alexander Musmane4e893b2014-09-23 09:33:00 +00004704StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4705 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4706 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004707 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004708 if (!AStmt)
4709 return StmtError();
4710
Alexander Musmane4e893b2014-09-23 09:33:00 +00004711 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4712 // 1.2.2 OpenMP Language Terminology
4713 // Structured block - An executable statement with a single entry at the
4714 // top and a single exit at the bottom.
4715 // The point of exit cannot be a branch out of the structured block.
4716 // longjmp() and throw() must not violate the entry/exit criteria.
4717 CS->getCapturedDecl()->setNothrow();
4718
Alexander Musmanc6388682014-12-15 07:07:06 +00004719 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004720 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4721 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004722 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004723 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4724 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4725 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004726 if (NestedLoopCount == 0)
4727 return StmtError();
4728
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004729 if (!CurContext->isDependentContext()) {
4730 // Finalize the clauses that need pre-built expressions for CodeGen.
4731 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004732 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004733 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004734 B.NumIterations, *this, CurScope,
4735 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004736 return StmtError();
4737 }
4738 }
4739
Kelvin Lic5609492016-07-15 04:39:07 +00004740 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004741 return StmtError();
4742
Alexander Musmane4e893b2014-09-23 09:33:00 +00004743 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004744 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004745 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004746}
4747
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004748StmtResult
4749Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4750 Stmt *AStmt, SourceLocation StartLoc,
4751 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004752 if (!AStmt)
4753 return StmtError();
4754
4755 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004756 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004757 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004758 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004759 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004760 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004761 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004762 return StmtError();
4763 // All associated statements must be '#pragma omp section' except for
4764 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004765 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004766 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4767 if (SectionStmt)
4768 Diag(SectionStmt->getLocStart(),
4769 diag::err_omp_parallel_sections_substmt_not_section);
4770 return StmtError();
4771 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004772 cast<OMPSectionDirective>(SectionStmt)
4773 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004774 }
4775 } else {
4776 Diag(AStmt->getLocStart(),
4777 diag::err_omp_parallel_sections_not_compound_stmt);
4778 return StmtError();
4779 }
4780
4781 getCurFunction()->setHasBranchProtectedScope();
4782
Alexey Bataev25e5b442015-09-15 12:52:43 +00004783 return OMPParallelSectionsDirective::Create(
4784 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004785}
4786
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004787StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4788 Stmt *AStmt, SourceLocation StartLoc,
4789 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004790 if (!AStmt)
4791 return StmtError();
4792
David Majnemer9d168222016-08-05 17:44:54 +00004793 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004794 // 1.2.2 OpenMP Language Terminology
4795 // Structured block - An executable statement with a single entry at the
4796 // top and a single exit at the bottom.
4797 // The point of exit cannot be a branch out of the structured block.
4798 // longjmp() and throw() must not violate the entry/exit criteria.
4799 CS->getCapturedDecl()->setNothrow();
4800
4801 getCurFunction()->setHasBranchProtectedScope();
4802
Alexey Bataev25e5b442015-09-15 12:52:43 +00004803 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4804 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004805}
4806
Alexey Bataev68446b72014-07-18 07:47:19 +00004807StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4808 SourceLocation EndLoc) {
4809 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4810}
4811
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004812StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4813 SourceLocation EndLoc) {
4814 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4815}
4816
Alexey Bataev2df347a2014-07-18 10:17:07 +00004817StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4818 SourceLocation EndLoc) {
4819 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4820}
4821
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004822StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4823 SourceLocation StartLoc,
4824 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004825 if (!AStmt)
4826 return StmtError();
4827
4828 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004829
4830 getCurFunction()->setHasBranchProtectedScope();
4831
4832 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4833}
4834
Alexey Bataev6125da92014-07-21 11:26:11 +00004835StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4836 SourceLocation StartLoc,
4837 SourceLocation EndLoc) {
4838 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4839 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4840}
4841
Alexey Bataev346265e2015-09-25 10:37:12 +00004842StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4843 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004844 SourceLocation StartLoc,
4845 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004846 OMPClause *DependFound = nullptr;
4847 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004848 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004849 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004850 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004851 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004852 for (auto *C : Clauses) {
4853 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4854 DependFound = C;
4855 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4856 if (DependSourceClause) {
4857 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4858 << getOpenMPDirectiveName(OMPD_ordered)
4859 << getOpenMPClauseName(OMPC_depend) << 2;
4860 ErrorFound = true;
4861 } else
4862 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004863 if (DependSinkClause) {
4864 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4865 << 0;
4866 ErrorFound = true;
4867 }
4868 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4869 if (DependSourceClause) {
4870 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4871 << 1;
4872 ErrorFound = true;
4873 }
4874 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004875 }
4876 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004877 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004878 else if (C->getClauseKind() == OMPC_simd)
4879 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004880 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004881 if (!ErrorFound && !SC &&
4882 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004883 // OpenMP [2.8.1,simd Construct, Restrictions]
4884 // An ordered construct with the simd clause is the only OpenMP construct
4885 // that can appear in the simd region.
4886 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004887 ErrorFound = true;
4888 } else if (DependFound && (TC || SC)) {
4889 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4890 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4891 ErrorFound = true;
4892 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4893 Diag(DependFound->getLocStart(),
4894 diag::err_omp_ordered_directive_without_param);
4895 ErrorFound = true;
4896 } else if (TC || Clauses.empty()) {
4897 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4898 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4899 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4900 << (TC != nullptr);
4901 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4902 ErrorFound = true;
4903 }
4904 }
4905 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004906 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004907
4908 if (AStmt) {
4909 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4910
4911 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004912 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004913
4914 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004915}
4916
Alexey Bataev1d160b12015-03-13 12:27:31 +00004917namespace {
4918/// \brief Helper class for checking expression in 'omp atomic [update]'
4919/// construct.
4920class OpenMPAtomicUpdateChecker {
4921 /// \brief Error results for atomic update expressions.
4922 enum ExprAnalysisErrorCode {
4923 /// \brief A statement is not an expression statement.
4924 NotAnExpression,
4925 /// \brief Expression is not builtin binary or unary operation.
4926 NotABinaryOrUnaryExpression,
4927 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4928 NotAnUnaryIncDecExpression,
4929 /// \brief An expression is not of scalar type.
4930 NotAScalarType,
4931 /// \brief A binary operation is not an assignment operation.
4932 NotAnAssignmentOp,
4933 /// \brief RHS part of the binary operation is not a binary expression.
4934 NotABinaryExpression,
4935 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4936 /// expression.
4937 NotABinaryOperator,
4938 /// \brief RHS binary operation does not have reference to the updated LHS
4939 /// part.
4940 NotAnUpdateExpression,
4941 /// \brief No errors is found.
4942 NoError
4943 };
4944 /// \brief Reference to Sema.
4945 Sema &SemaRef;
4946 /// \brief A location for note diagnostics (when error is found).
4947 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004948 /// \brief 'x' lvalue part of the source atomic expression.
4949 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004950 /// \brief 'expr' rvalue part of the source atomic expression.
4951 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004952 /// \brief Helper expression of the form
4953 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4954 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4955 Expr *UpdateExpr;
4956 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4957 /// important for non-associative operations.
4958 bool IsXLHSInRHSPart;
4959 BinaryOperatorKind Op;
4960 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004961 /// \brief true if the source expression is a postfix unary operation, false
4962 /// if it is a prefix unary operation.
4963 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004964
4965public:
4966 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004967 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004968 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004969 /// \brief Check specified statement that it is suitable for 'atomic update'
4970 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004971 /// expression. If DiagId and NoteId == 0, then only check is performed
4972 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004973 /// \param DiagId Diagnostic which should be emitted if error is found.
4974 /// \param NoteId Diagnostic note for the main error message.
4975 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004976 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004977 /// \brief Return the 'x' lvalue part of the source atomic expression.
4978 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004979 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4980 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004981 /// \brief Return the update expression used in calculation of the updated
4982 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4983 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4984 Expr *getUpdateExpr() const { return UpdateExpr; }
4985 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4986 /// false otherwise.
4987 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4988
Alexey Bataevb78ca832015-04-01 03:33:17 +00004989 /// \brief true if the source expression is a postfix unary operation, false
4990 /// if it is a prefix unary operation.
4991 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4992
Alexey Bataev1d160b12015-03-13 12:27:31 +00004993private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004994 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4995 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004996};
4997} // namespace
4998
4999bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5000 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5001 ExprAnalysisErrorCode ErrorFound = NoError;
5002 SourceLocation ErrorLoc, NoteLoc;
5003 SourceRange ErrorRange, NoteRange;
5004 // Allowed constructs are:
5005 // x = x binop expr;
5006 // x = expr binop x;
5007 if (AtomicBinOp->getOpcode() == BO_Assign) {
5008 X = AtomicBinOp->getLHS();
5009 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5010 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5011 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5012 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5013 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005014 Op = AtomicInnerBinOp->getOpcode();
5015 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005016 auto *LHS = AtomicInnerBinOp->getLHS();
5017 auto *RHS = AtomicInnerBinOp->getRHS();
5018 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5019 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5020 /*Canonical=*/true);
5021 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5022 /*Canonical=*/true);
5023 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5024 /*Canonical=*/true);
5025 if (XId == LHSId) {
5026 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005027 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005028 } else if (XId == RHSId) {
5029 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005030 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005031 } else {
5032 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5033 ErrorRange = AtomicInnerBinOp->getSourceRange();
5034 NoteLoc = X->getExprLoc();
5035 NoteRange = X->getSourceRange();
5036 ErrorFound = NotAnUpdateExpression;
5037 }
5038 } else {
5039 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5040 ErrorRange = AtomicInnerBinOp->getSourceRange();
5041 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5042 NoteRange = SourceRange(NoteLoc, NoteLoc);
5043 ErrorFound = NotABinaryOperator;
5044 }
5045 } else {
5046 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5047 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5048 ErrorFound = NotABinaryExpression;
5049 }
5050 } else {
5051 ErrorLoc = AtomicBinOp->getExprLoc();
5052 ErrorRange = AtomicBinOp->getSourceRange();
5053 NoteLoc = AtomicBinOp->getOperatorLoc();
5054 NoteRange = SourceRange(NoteLoc, NoteLoc);
5055 ErrorFound = NotAnAssignmentOp;
5056 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005057 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005058 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5059 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5060 return true;
5061 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005062 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005063 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005064}
5065
5066bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5067 unsigned NoteId) {
5068 ExprAnalysisErrorCode ErrorFound = NoError;
5069 SourceLocation ErrorLoc, NoteLoc;
5070 SourceRange ErrorRange, NoteRange;
5071 // Allowed constructs are:
5072 // x++;
5073 // x--;
5074 // ++x;
5075 // --x;
5076 // x binop= expr;
5077 // x = x binop expr;
5078 // x = expr binop x;
5079 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5080 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5081 if (AtomicBody->getType()->isScalarType() ||
5082 AtomicBody->isInstantiationDependent()) {
5083 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5084 AtomicBody->IgnoreParenImpCasts())) {
5085 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005086 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005087 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005088 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005089 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005090 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005091 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005092 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5093 AtomicBody->IgnoreParenImpCasts())) {
5094 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005095 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005096 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005097 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5098 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005099 // Check for Unary Operation
5100 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005101 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005102 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5103 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005104 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005105 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5106 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005107 } else {
5108 ErrorFound = NotAnUnaryIncDecExpression;
5109 ErrorLoc = AtomicUnaryOp->getExprLoc();
5110 ErrorRange = AtomicUnaryOp->getSourceRange();
5111 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5112 NoteRange = SourceRange(NoteLoc, NoteLoc);
5113 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005114 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005115 ErrorFound = NotABinaryOrUnaryExpression;
5116 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5117 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5118 }
5119 } else {
5120 ErrorFound = NotAScalarType;
5121 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5122 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5123 }
5124 } else {
5125 ErrorFound = NotAnExpression;
5126 NoteLoc = ErrorLoc = S->getLocStart();
5127 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5128 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005129 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005130 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5131 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5132 return true;
5133 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005134 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005135 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005136 // Build an update expression of form 'OpaqueValueExpr(x) binop
5137 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5138 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5139 auto *OVEX = new (SemaRef.getASTContext())
5140 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5141 auto *OVEExpr = new (SemaRef.getASTContext())
5142 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5143 auto Update =
5144 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5145 IsXLHSInRHSPart ? OVEExpr : OVEX);
5146 if (Update.isInvalid())
5147 return true;
5148 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5149 Sema::AA_Casting);
5150 if (Update.isInvalid())
5151 return true;
5152 UpdateExpr = Update.get();
5153 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005154 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005155}
5156
Alexey Bataev0162e452014-07-22 10:10:35 +00005157StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5158 Stmt *AStmt,
5159 SourceLocation StartLoc,
5160 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005161 if (!AStmt)
5162 return StmtError();
5163
David Majnemer9d168222016-08-05 17:44:54 +00005164 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005165 // 1.2.2 OpenMP Language Terminology
5166 // Structured block - An executable statement with a single entry at the
5167 // top and a single exit at the bottom.
5168 // The point of exit cannot be a branch out of the structured block.
5169 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005170 OpenMPClauseKind AtomicKind = OMPC_unknown;
5171 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005172 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005173 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005174 C->getClauseKind() == OMPC_update ||
5175 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005176 if (AtomicKind != OMPC_unknown) {
5177 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5178 << SourceRange(C->getLocStart(), C->getLocEnd());
5179 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5180 << getOpenMPClauseName(AtomicKind);
5181 } else {
5182 AtomicKind = C->getClauseKind();
5183 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005184 }
5185 }
5186 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005187
Alexey Bataev459dec02014-07-24 06:46:57 +00005188 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005189 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5190 Body = EWC->getSubExpr();
5191
Alexey Bataev62cec442014-11-18 10:14:22 +00005192 Expr *X = nullptr;
5193 Expr *V = nullptr;
5194 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005195 Expr *UE = nullptr;
5196 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005197 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005198 // OpenMP [2.12.6, atomic Construct]
5199 // In the next expressions:
5200 // * x and v (as applicable) are both l-value expressions with scalar type.
5201 // * During the execution of an atomic region, multiple syntactic
5202 // occurrences of x must designate the same storage location.
5203 // * Neither of v and expr (as applicable) may access the storage location
5204 // designated by x.
5205 // * Neither of x and expr (as applicable) may access the storage location
5206 // designated by v.
5207 // * expr is an expression with scalar type.
5208 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5209 // * binop, binop=, ++, and -- are not overloaded operators.
5210 // * The expression x binop expr must be numerically equivalent to x binop
5211 // (expr). This requirement is satisfied if the operators in expr have
5212 // precedence greater than binop, or by using parentheses around expr or
5213 // subexpressions of expr.
5214 // * The expression expr binop x must be numerically equivalent to (expr)
5215 // binop x. This requirement is satisfied if the operators in expr have
5216 // precedence equal to or greater than binop, or by using parentheses around
5217 // expr or subexpressions of expr.
5218 // * For forms that allow multiple occurrences of x, the number of times
5219 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005220 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005221 enum {
5222 NotAnExpression,
5223 NotAnAssignmentOp,
5224 NotAScalarType,
5225 NotAnLValue,
5226 NoError
5227 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005228 SourceLocation ErrorLoc, NoteLoc;
5229 SourceRange ErrorRange, NoteRange;
5230 // If clause is read:
5231 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005232 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5233 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005234 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5235 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5236 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5237 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5238 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5239 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5240 if (!X->isLValue() || !V->isLValue()) {
5241 auto NotLValueExpr = X->isLValue() ? V : X;
5242 ErrorFound = NotAnLValue;
5243 ErrorLoc = AtomicBinOp->getExprLoc();
5244 ErrorRange = AtomicBinOp->getSourceRange();
5245 NoteLoc = NotLValueExpr->getExprLoc();
5246 NoteRange = NotLValueExpr->getSourceRange();
5247 }
5248 } else if (!X->isInstantiationDependent() ||
5249 !V->isInstantiationDependent()) {
5250 auto NotScalarExpr =
5251 (X->isInstantiationDependent() || X->getType()->isScalarType())
5252 ? V
5253 : X;
5254 ErrorFound = NotAScalarType;
5255 ErrorLoc = AtomicBinOp->getExprLoc();
5256 ErrorRange = AtomicBinOp->getSourceRange();
5257 NoteLoc = NotScalarExpr->getExprLoc();
5258 NoteRange = NotScalarExpr->getSourceRange();
5259 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005260 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005261 ErrorFound = NotAnAssignmentOp;
5262 ErrorLoc = AtomicBody->getExprLoc();
5263 ErrorRange = AtomicBody->getSourceRange();
5264 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5265 : AtomicBody->getExprLoc();
5266 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5267 : AtomicBody->getSourceRange();
5268 }
5269 } else {
5270 ErrorFound = NotAnExpression;
5271 NoteLoc = ErrorLoc = Body->getLocStart();
5272 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005273 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005274 if (ErrorFound != NoError) {
5275 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5276 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005277 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5278 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005279 return StmtError();
5280 } else if (CurContext->isDependentContext())
5281 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005282 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005283 enum {
5284 NotAnExpression,
5285 NotAnAssignmentOp,
5286 NotAScalarType,
5287 NotAnLValue,
5288 NoError
5289 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005290 SourceLocation ErrorLoc, NoteLoc;
5291 SourceRange ErrorRange, NoteRange;
5292 // If clause is write:
5293 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005294 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5295 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005296 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5297 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005298 X = AtomicBinOp->getLHS();
5299 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005300 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5301 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5302 if (!X->isLValue()) {
5303 ErrorFound = NotAnLValue;
5304 ErrorLoc = AtomicBinOp->getExprLoc();
5305 ErrorRange = AtomicBinOp->getSourceRange();
5306 NoteLoc = X->getExprLoc();
5307 NoteRange = X->getSourceRange();
5308 }
5309 } else if (!X->isInstantiationDependent() ||
5310 !E->isInstantiationDependent()) {
5311 auto NotScalarExpr =
5312 (X->isInstantiationDependent() || X->getType()->isScalarType())
5313 ? E
5314 : X;
5315 ErrorFound = NotAScalarType;
5316 ErrorLoc = AtomicBinOp->getExprLoc();
5317 ErrorRange = AtomicBinOp->getSourceRange();
5318 NoteLoc = NotScalarExpr->getExprLoc();
5319 NoteRange = NotScalarExpr->getSourceRange();
5320 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005321 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005322 ErrorFound = NotAnAssignmentOp;
5323 ErrorLoc = AtomicBody->getExprLoc();
5324 ErrorRange = AtomicBody->getSourceRange();
5325 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5326 : AtomicBody->getExprLoc();
5327 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5328 : AtomicBody->getSourceRange();
5329 }
5330 } else {
5331 ErrorFound = NotAnExpression;
5332 NoteLoc = ErrorLoc = Body->getLocStart();
5333 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005334 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005335 if (ErrorFound != NoError) {
5336 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5337 << ErrorRange;
5338 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5339 << NoteRange;
5340 return StmtError();
5341 } else if (CurContext->isDependentContext())
5342 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005343 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005344 // If clause is update:
5345 // x++;
5346 // x--;
5347 // ++x;
5348 // --x;
5349 // x binop= expr;
5350 // x = x binop expr;
5351 // x = expr binop x;
5352 OpenMPAtomicUpdateChecker Checker(*this);
5353 if (Checker.checkStatement(
5354 Body, (AtomicKind == OMPC_update)
5355 ? diag::err_omp_atomic_update_not_expression_statement
5356 : diag::err_omp_atomic_not_expression_statement,
5357 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005358 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005359 if (!CurContext->isDependentContext()) {
5360 E = Checker.getExpr();
5361 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005362 UE = Checker.getUpdateExpr();
5363 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005364 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005365 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005366 enum {
5367 NotAnAssignmentOp,
5368 NotACompoundStatement,
5369 NotTwoSubstatements,
5370 NotASpecificExpression,
5371 NoError
5372 } ErrorFound = NoError;
5373 SourceLocation ErrorLoc, NoteLoc;
5374 SourceRange ErrorRange, NoteRange;
5375 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5376 // If clause is a capture:
5377 // v = x++;
5378 // v = x--;
5379 // v = ++x;
5380 // v = --x;
5381 // v = x binop= expr;
5382 // v = x = x binop expr;
5383 // v = x = expr binop x;
5384 auto *AtomicBinOp =
5385 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5386 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5387 V = AtomicBinOp->getLHS();
5388 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5389 OpenMPAtomicUpdateChecker Checker(*this);
5390 if (Checker.checkStatement(
5391 Body, diag::err_omp_atomic_capture_not_expression_statement,
5392 diag::note_omp_atomic_update))
5393 return StmtError();
5394 E = Checker.getExpr();
5395 X = Checker.getX();
5396 UE = Checker.getUpdateExpr();
5397 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5398 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005399 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005400 ErrorLoc = AtomicBody->getExprLoc();
5401 ErrorRange = AtomicBody->getSourceRange();
5402 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5403 : AtomicBody->getExprLoc();
5404 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5405 : AtomicBody->getSourceRange();
5406 ErrorFound = NotAnAssignmentOp;
5407 }
5408 if (ErrorFound != NoError) {
5409 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5410 << ErrorRange;
5411 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5412 return StmtError();
5413 } else if (CurContext->isDependentContext()) {
5414 UE = V = E = X = nullptr;
5415 }
5416 } else {
5417 // If clause is a capture:
5418 // { v = x; x = expr; }
5419 // { v = x; x++; }
5420 // { v = x; x--; }
5421 // { v = x; ++x; }
5422 // { v = x; --x; }
5423 // { v = x; x binop= expr; }
5424 // { v = x; x = x binop expr; }
5425 // { v = x; x = expr binop x; }
5426 // { x++; v = x; }
5427 // { x--; v = x; }
5428 // { ++x; v = x; }
5429 // { --x; v = x; }
5430 // { x binop= expr; v = x; }
5431 // { x = x binop expr; v = x; }
5432 // { x = expr binop x; v = x; }
5433 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5434 // Check that this is { expr1; expr2; }
5435 if (CS->size() == 2) {
5436 auto *First = CS->body_front();
5437 auto *Second = CS->body_back();
5438 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5439 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5440 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5441 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5442 // Need to find what subexpression is 'v' and what is 'x'.
5443 OpenMPAtomicUpdateChecker Checker(*this);
5444 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5445 BinaryOperator *BinOp = nullptr;
5446 if (IsUpdateExprFound) {
5447 BinOp = dyn_cast<BinaryOperator>(First);
5448 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5449 }
5450 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5451 // { v = x; x++; }
5452 // { v = x; x--; }
5453 // { v = x; ++x; }
5454 // { v = x; --x; }
5455 // { v = x; x binop= expr; }
5456 // { v = x; x = x binop expr; }
5457 // { v = x; x = expr binop x; }
5458 // Check that the first expression has form v = x.
5459 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5460 llvm::FoldingSetNodeID XId, PossibleXId;
5461 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5462 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5463 IsUpdateExprFound = XId == PossibleXId;
5464 if (IsUpdateExprFound) {
5465 V = BinOp->getLHS();
5466 X = Checker.getX();
5467 E = Checker.getExpr();
5468 UE = Checker.getUpdateExpr();
5469 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005470 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005471 }
5472 }
5473 if (!IsUpdateExprFound) {
5474 IsUpdateExprFound = !Checker.checkStatement(First);
5475 BinOp = nullptr;
5476 if (IsUpdateExprFound) {
5477 BinOp = dyn_cast<BinaryOperator>(Second);
5478 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5479 }
5480 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5481 // { x++; v = x; }
5482 // { x--; v = x; }
5483 // { ++x; v = x; }
5484 // { --x; v = x; }
5485 // { x binop= expr; v = x; }
5486 // { x = x binop expr; v = x; }
5487 // { x = expr binop x; v = x; }
5488 // Check that the second expression has form v = x.
5489 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5490 llvm::FoldingSetNodeID XId, PossibleXId;
5491 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5492 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5493 IsUpdateExprFound = XId == PossibleXId;
5494 if (IsUpdateExprFound) {
5495 V = BinOp->getLHS();
5496 X = Checker.getX();
5497 E = Checker.getExpr();
5498 UE = Checker.getUpdateExpr();
5499 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005500 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005501 }
5502 }
5503 }
5504 if (!IsUpdateExprFound) {
5505 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005506 auto *FirstExpr = dyn_cast<Expr>(First);
5507 auto *SecondExpr = dyn_cast<Expr>(Second);
5508 if (!FirstExpr || !SecondExpr ||
5509 !(FirstExpr->isInstantiationDependent() ||
5510 SecondExpr->isInstantiationDependent())) {
5511 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5512 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005513 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005514 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5515 : First->getLocStart();
5516 NoteRange = ErrorRange = FirstBinOp
5517 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005518 : SourceRange(ErrorLoc, ErrorLoc);
5519 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005520 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5521 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5522 ErrorFound = NotAnAssignmentOp;
5523 NoteLoc = ErrorLoc = SecondBinOp
5524 ? SecondBinOp->getOperatorLoc()
5525 : Second->getLocStart();
5526 NoteRange = ErrorRange =
5527 SecondBinOp ? SecondBinOp->getSourceRange()
5528 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005529 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005530 auto *PossibleXRHSInFirst =
5531 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5532 auto *PossibleXLHSInSecond =
5533 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5534 llvm::FoldingSetNodeID X1Id, X2Id;
5535 PossibleXRHSInFirst->Profile(X1Id, Context,
5536 /*Canonical=*/true);
5537 PossibleXLHSInSecond->Profile(X2Id, Context,
5538 /*Canonical=*/true);
5539 IsUpdateExprFound = X1Id == X2Id;
5540 if (IsUpdateExprFound) {
5541 V = FirstBinOp->getLHS();
5542 X = SecondBinOp->getLHS();
5543 E = SecondBinOp->getRHS();
5544 UE = nullptr;
5545 IsXLHSInRHSPart = false;
5546 IsPostfixUpdate = true;
5547 } else {
5548 ErrorFound = NotASpecificExpression;
5549 ErrorLoc = FirstBinOp->getExprLoc();
5550 ErrorRange = FirstBinOp->getSourceRange();
5551 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5552 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5553 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005554 }
5555 }
5556 }
5557 }
5558 } else {
5559 NoteLoc = ErrorLoc = Body->getLocStart();
5560 NoteRange = ErrorRange =
5561 SourceRange(Body->getLocStart(), Body->getLocStart());
5562 ErrorFound = NotTwoSubstatements;
5563 }
5564 } else {
5565 NoteLoc = ErrorLoc = Body->getLocStart();
5566 NoteRange = ErrorRange =
5567 SourceRange(Body->getLocStart(), Body->getLocStart());
5568 ErrorFound = NotACompoundStatement;
5569 }
5570 if (ErrorFound != NoError) {
5571 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5572 << ErrorRange;
5573 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5574 return StmtError();
5575 } else if (CurContext->isDependentContext()) {
5576 UE = V = E = X = nullptr;
5577 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005578 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005579 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005580
5581 getCurFunction()->setHasBranchProtectedScope();
5582
Alexey Bataev62cec442014-11-18 10:14:22 +00005583 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005584 X, V, E, UE, IsXLHSInRHSPart,
5585 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005586}
5587
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005588StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5589 Stmt *AStmt,
5590 SourceLocation StartLoc,
5591 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005592 if (!AStmt)
5593 return StmtError();
5594
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005595 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5596 // 1.2.2 OpenMP Language Terminology
5597 // Structured block - An executable statement with a single entry at the
5598 // top and a single exit at the bottom.
5599 // The point of exit cannot be a branch out of the structured block.
5600 // longjmp() and throw() must not violate the entry/exit criteria.
5601 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005602
Alexey Bataev13314bf2014-10-09 04:18:56 +00005603 // OpenMP [2.16, Nesting of Regions]
5604 // If specified, a teams construct must be contained within a target
5605 // construct. That target construct must contain no statements or directives
5606 // outside of the teams construct.
5607 if (DSAStack->hasInnerTeamsRegion()) {
5608 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5609 bool OMPTeamsFound = true;
5610 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5611 auto I = CS->body_begin();
5612 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005613 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005614 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5615 OMPTeamsFound = false;
5616 break;
5617 }
5618 ++I;
5619 }
5620 assert(I != CS->body_end() && "Not found statement");
5621 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005622 } else {
5623 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5624 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005625 }
5626 if (!OMPTeamsFound) {
5627 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5628 Diag(DSAStack->getInnerTeamsRegionLoc(),
5629 diag::note_omp_nested_teams_construct_here);
5630 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5631 << isa<OMPExecutableDirective>(S);
5632 return StmtError();
5633 }
5634 }
5635
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005636 getCurFunction()->setHasBranchProtectedScope();
5637
5638 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5639}
5640
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005641StmtResult
5642Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5643 Stmt *AStmt, SourceLocation StartLoc,
5644 SourceLocation EndLoc) {
5645 if (!AStmt)
5646 return StmtError();
5647
5648 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5649 // 1.2.2 OpenMP Language Terminology
5650 // Structured block - An executable statement with a single entry at the
5651 // top and a single exit at the bottom.
5652 // The point of exit cannot be a branch out of the structured block.
5653 // longjmp() and throw() must not violate the entry/exit criteria.
5654 CS->getCapturedDecl()->setNothrow();
5655
5656 getCurFunction()->setHasBranchProtectedScope();
5657
5658 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5659 AStmt);
5660}
5661
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005662StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5663 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5664 SourceLocation EndLoc,
5665 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5666 if (!AStmt)
5667 return StmtError();
5668
5669 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5670 // 1.2.2 OpenMP Language Terminology
5671 // Structured block - An executable statement with a single entry at the
5672 // top and a single exit at the bottom.
5673 // The point of exit cannot be a branch out of the structured block.
5674 // longjmp() and throw() must not violate the entry/exit criteria.
5675 CS->getCapturedDecl()->setNothrow();
5676
5677 OMPLoopDirective::HelperExprs B;
5678 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5679 // define the nested loops number.
5680 unsigned NestedLoopCount =
5681 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5682 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5683 VarsWithImplicitDSA, B);
5684 if (NestedLoopCount == 0)
5685 return StmtError();
5686
5687 assert((CurContext->isDependentContext() || B.builtAll()) &&
5688 "omp target parallel for loop exprs were not built");
5689
5690 if (!CurContext->isDependentContext()) {
5691 // Finalize the clauses that need pre-built expressions for CodeGen.
5692 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005693 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005694 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005695 B.NumIterations, *this, CurScope,
5696 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005697 return StmtError();
5698 }
5699 }
5700
5701 getCurFunction()->setHasBranchProtectedScope();
5702 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5703 NestedLoopCount, Clauses, AStmt,
5704 B, DSAStack->isCancelRegion());
5705}
5706
Samuel Antaodf67fc42016-01-19 19:15:56 +00005707/// \brief Check for existence of a map clause in the list of clauses.
5708static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5709 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5710 I != E; ++I) {
5711 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5712 return true;
5713 }
5714 }
5715
5716 return false;
5717}
5718
Michael Wong65f367f2015-07-21 13:44:28 +00005719StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5720 Stmt *AStmt,
5721 SourceLocation StartLoc,
5722 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005723 if (!AStmt)
5724 return StmtError();
5725
5726 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5727
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005728 // OpenMP [2.10.1, Restrictions, p. 97]
5729 // At least one map clause must appear on the directive.
5730 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005731 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5732 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005733 return StmtError();
5734 }
5735
Michael Wong65f367f2015-07-21 13:44:28 +00005736 getCurFunction()->setHasBranchProtectedScope();
5737
5738 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5739 AStmt);
5740}
5741
Samuel Antaodf67fc42016-01-19 19:15:56 +00005742StmtResult
5743Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5744 SourceLocation StartLoc,
5745 SourceLocation EndLoc) {
5746 // OpenMP [2.10.2, Restrictions, p. 99]
5747 // At least one map clause must appear on the directive.
5748 if (!HasMapClause(Clauses)) {
5749 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5750 << getOpenMPDirectiveName(OMPD_target_enter_data);
5751 return StmtError();
5752 }
5753
5754 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5755 Clauses);
5756}
5757
Samuel Antao72590762016-01-19 20:04:50 +00005758StmtResult
5759Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5760 SourceLocation StartLoc,
5761 SourceLocation EndLoc) {
5762 // OpenMP [2.10.3, Restrictions, p. 102]
5763 // At least one map clause must appear on the directive.
5764 if (!HasMapClause(Clauses)) {
5765 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5766 << getOpenMPDirectiveName(OMPD_target_exit_data);
5767 return StmtError();
5768 }
5769
5770 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5771}
5772
Samuel Antao686c70c2016-05-26 17:30:50 +00005773StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5774 SourceLocation StartLoc,
5775 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005776 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005777 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005778 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005779 seenMotionClause = true;
5780 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005781 if (!seenMotionClause) {
5782 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5783 return StmtError();
5784 }
5785 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5786}
5787
Alexey Bataev13314bf2014-10-09 04:18:56 +00005788StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5789 Stmt *AStmt, SourceLocation StartLoc,
5790 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005791 if (!AStmt)
5792 return StmtError();
5793
Alexey Bataev13314bf2014-10-09 04:18:56 +00005794 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5795 // 1.2.2 OpenMP Language Terminology
5796 // Structured block - An executable statement with a single entry at the
5797 // top and a single exit at the bottom.
5798 // The point of exit cannot be a branch out of the structured block.
5799 // longjmp() and throw() must not violate the entry/exit criteria.
5800 CS->getCapturedDecl()->setNothrow();
5801
5802 getCurFunction()->setHasBranchProtectedScope();
5803
5804 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5805}
5806
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005807StmtResult
5808Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5809 SourceLocation EndLoc,
5810 OpenMPDirectiveKind CancelRegion) {
5811 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5812 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5813 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5814 << getOpenMPDirectiveName(CancelRegion);
5815 return StmtError();
5816 }
5817 if (DSAStack->isParentNowaitRegion()) {
5818 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5819 return StmtError();
5820 }
5821 if (DSAStack->isParentOrderedRegion()) {
5822 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5823 return StmtError();
5824 }
5825 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5826 CancelRegion);
5827}
5828
Alexey Bataev87933c72015-09-18 08:07:34 +00005829StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5830 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005831 SourceLocation EndLoc,
5832 OpenMPDirectiveKind CancelRegion) {
5833 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5834 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5835 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5836 << getOpenMPDirectiveName(CancelRegion);
5837 return StmtError();
5838 }
5839 if (DSAStack->isParentNowaitRegion()) {
5840 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5841 return StmtError();
5842 }
5843 if (DSAStack->isParentOrderedRegion()) {
5844 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5845 return StmtError();
5846 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005847 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005848 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5849 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005850}
5851
Alexey Bataev382967a2015-12-08 12:06:20 +00005852static bool checkGrainsizeNumTasksClauses(Sema &S,
5853 ArrayRef<OMPClause *> Clauses) {
5854 OMPClause *PrevClause = nullptr;
5855 bool ErrorFound = false;
5856 for (auto *C : Clauses) {
5857 if (C->getClauseKind() == OMPC_grainsize ||
5858 C->getClauseKind() == OMPC_num_tasks) {
5859 if (!PrevClause)
5860 PrevClause = C;
5861 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5862 S.Diag(C->getLocStart(),
5863 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5864 << getOpenMPClauseName(C->getClauseKind())
5865 << getOpenMPClauseName(PrevClause->getClauseKind());
5866 S.Diag(PrevClause->getLocStart(),
5867 diag::note_omp_previous_grainsize_num_tasks)
5868 << getOpenMPClauseName(PrevClause->getClauseKind());
5869 ErrorFound = true;
5870 }
5871 }
5872 }
5873 return ErrorFound;
5874}
5875
Alexey Bataev49f6e782015-12-01 04:18:41 +00005876StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5877 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5878 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005879 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005880 if (!AStmt)
5881 return StmtError();
5882
5883 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5884 OMPLoopDirective::HelperExprs B;
5885 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5886 // define the nested loops number.
5887 unsigned NestedLoopCount =
5888 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005889 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005890 VarsWithImplicitDSA, B);
5891 if (NestedLoopCount == 0)
5892 return StmtError();
5893
5894 assert((CurContext->isDependentContext() || B.builtAll()) &&
5895 "omp for loop exprs were not built");
5896
Alexey Bataev382967a2015-12-08 12:06:20 +00005897 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5898 // The grainsize clause and num_tasks clause are mutually exclusive and may
5899 // not appear on the same taskloop directive.
5900 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5901 return StmtError();
5902
Alexey Bataev49f6e782015-12-01 04:18:41 +00005903 getCurFunction()->setHasBranchProtectedScope();
5904 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5905 NestedLoopCount, Clauses, AStmt, B);
5906}
5907
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005908StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5910 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005911 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005912 if (!AStmt)
5913 return StmtError();
5914
5915 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5916 OMPLoopDirective::HelperExprs B;
5917 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5918 // define the nested loops number.
5919 unsigned NestedLoopCount =
5920 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5921 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5922 VarsWithImplicitDSA, B);
5923 if (NestedLoopCount == 0)
5924 return StmtError();
5925
5926 assert((CurContext->isDependentContext() || B.builtAll()) &&
5927 "omp for loop exprs were not built");
5928
Alexey Bataev5a3af132016-03-29 08:58:54 +00005929 if (!CurContext->isDependentContext()) {
5930 // Finalize the clauses that need pre-built expressions for CodeGen.
5931 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005932 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005933 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005934 B.NumIterations, *this, CurScope,
5935 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005936 return StmtError();
5937 }
5938 }
5939
Alexey Bataev382967a2015-12-08 12:06:20 +00005940 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5941 // The grainsize clause and num_tasks clause are mutually exclusive and may
5942 // not appear on the same taskloop directive.
5943 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5944 return StmtError();
5945
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005946 getCurFunction()->setHasBranchProtectedScope();
5947 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5948 NestedLoopCount, Clauses, AStmt, B);
5949}
5950
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005951StmtResult Sema::ActOnOpenMPDistributeDirective(
5952 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5953 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005954 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005955 if (!AStmt)
5956 return StmtError();
5957
5958 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5959 OMPLoopDirective::HelperExprs B;
5960 // In presence of clause 'collapse' with number of loops, it will
5961 // define the nested loops number.
5962 unsigned NestedLoopCount =
5963 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5964 nullptr /*ordered not a clause on distribute*/, AStmt,
5965 *this, *DSAStack, VarsWithImplicitDSA, B);
5966 if (NestedLoopCount == 0)
5967 return StmtError();
5968
5969 assert((CurContext->isDependentContext() || B.builtAll()) &&
5970 "omp for loop exprs were not built");
5971
5972 getCurFunction()->setHasBranchProtectedScope();
5973 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5974 NestedLoopCount, Clauses, AStmt, B);
5975}
5976
Carlo Bertolli9925f152016-06-27 14:55:37 +00005977StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5978 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5979 SourceLocation EndLoc,
5980 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5981 if (!AStmt)
5982 return StmtError();
5983
5984 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5985 // 1.2.2 OpenMP Language Terminology
5986 // Structured block - An executable statement with a single entry at the
5987 // top and a single exit at the bottom.
5988 // The point of exit cannot be a branch out of the structured block.
5989 // longjmp() and throw() must not violate the entry/exit criteria.
5990 CS->getCapturedDecl()->setNothrow();
5991
5992 OMPLoopDirective::HelperExprs B;
5993 // In presence of clause 'collapse' with number of loops, it will
5994 // define the nested loops number.
5995 unsigned NestedLoopCount = CheckOpenMPLoop(
5996 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5997 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5998 VarsWithImplicitDSA, B);
5999 if (NestedLoopCount == 0)
6000 return StmtError();
6001
6002 assert((CurContext->isDependentContext() || B.builtAll()) &&
6003 "omp for loop exprs were not built");
6004
6005 getCurFunction()->setHasBranchProtectedScope();
6006 return OMPDistributeParallelForDirective::Create(
6007 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6008}
6009
Kelvin Li4a39add2016-07-05 05:00:15 +00006010StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6011 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6012 SourceLocation EndLoc,
6013 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6014 if (!AStmt)
6015 return StmtError();
6016
6017 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6018 // 1.2.2 OpenMP Language Terminology
6019 // Structured block - An executable statement with a single entry at the
6020 // top and a single exit at the bottom.
6021 // The point of exit cannot be a branch out of the structured block.
6022 // longjmp() and throw() must not violate the entry/exit criteria.
6023 CS->getCapturedDecl()->setNothrow();
6024
6025 OMPLoopDirective::HelperExprs B;
6026 // In presence of clause 'collapse' with number of loops, it will
6027 // define the nested loops number.
6028 unsigned NestedLoopCount = CheckOpenMPLoop(
6029 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6030 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6031 VarsWithImplicitDSA, B);
6032 if (NestedLoopCount == 0)
6033 return StmtError();
6034
6035 assert((CurContext->isDependentContext() || B.builtAll()) &&
6036 "omp for loop exprs were not built");
6037
Kelvin Lic5609492016-07-15 04:39:07 +00006038 if (checkSimdlenSafelenSpecified(*this, Clauses))
6039 return StmtError();
6040
Kelvin Li4a39add2016-07-05 05:00:15 +00006041 getCurFunction()->setHasBranchProtectedScope();
6042 return OMPDistributeParallelForSimdDirective::Create(
6043 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6044}
6045
Kelvin Li787f3fc2016-07-06 04:45:38 +00006046StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6047 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6048 SourceLocation EndLoc,
6049 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6050 if (!AStmt)
6051 return StmtError();
6052
6053 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6054 // 1.2.2 OpenMP Language Terminology
6055 // Structured block - An executable statement with a single entry at the
6056 // top and a single exit at the bottom.
6057 // The point of exit cannot be a branch out of the structured block.
6058 // longjmp() and throw() must not violate the entry/exit criteria.
6059 CS->getCapturedDecl()->setNothrow();
6060
6061 OMPLoopDirective::HelperExprs B;
6062 // In presence of clause 'collapse' with number of loops, it will
6063 // define the nested loops number.
6064 unsigned NestedLoopCount =
6065 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6066 nullptr /*ordered not a clause on distribute*/, AStmt,
6067 *this, *DSAStack, VarsWithImplicitDSA, B);
6068 if (NestedLoopCount == 0)
6069 return StmtError();
6070
6071 assert((CurContext->isDependentContext() || B.builtAll()) &&
6072 "omp for loop exprs were not built");
6073
Kelvin Lic5609492016-07-15 04:39:07 +00006074 if (checkSimdlenSafelenSpecified(*this, Clauses))
6075 return StmtError();
6076
Kelvin Li787f3fc2016-07-06 04:45:38 +00006077 getCurFunction()->setHasBranchProtectedScope();
6078 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6079 NestedLoopCount, Clauses, AStmt, B);
6080}
6081
Kelvin Lia579b912016-07-14 02:54:56 +00006082StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6083 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6084 SourceLocation EndLoc,
6085 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6086 if (!AStmt)
6087 return StmtError();
6088
6089 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6090 // 1.2.2 OpenMP Language Terminology
6091 // Structured block - An executable statement with a single entry at the
6092 // top and a single exit at the bottom.
6093 // The point of exit cannot be a branch out of the structured block.
6094 // longjmp() and throw() must not violate the entry/exit criteria.
6095 CS->getCapturedDecl()->setNothrow();
6096
6097 OMPLoopDirective::HelperExprs B;
6098 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6099 // define the nested loops number.
6100 unsigned NestedLoopCount = CheckOpenMPLoop(
6101 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6102 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6103 VarsWithImplicitDSA, B);
6104 if (NestedLoopCount == 0)
6105 return StmtError();
6106
6107 assert((CurContext->isDependentContext() || B.builtAll()) &&
6108 "omp target parallel for simd loop exprs were not built");
6109
6110 if (!CurContext->isDependentContext()) {
6111 // Finalize the clauses that need pre-built expressions for CodeGen.
6112 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006113 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006114 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6115 B.NumIterations, *this, CurScope,
6116 DSAStack))
6117 return StmtError();
6118 }
6119 }
Kelvin Lic5609492016-07-15 04:39:07 +00006120 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006121 return StmtError();
6122
6123 getCurFunction()->setHasBranchProtectedScope();
6124 return OMPTargetParallelForSimdDirective::Create(
6125 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6126}
6127
Kelvin Li986330c2016-07-20 22:57:10 +00006128StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6129 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6130 SourceLocation EndLoc,
6131 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6132 if (!AStmt)
6133 return StmtError();
6134
6135 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6136 // 1.2.2 OpenMP Language Terminology
6137 // Structured block - An executable statement with a single entry at the
6138 // top and a single exit at the bottom.
6139 // The point of exit cannot be a branch out of the structured block.
6140 // longjmp() and throw() must not violate the entry/exit criteria.
6141 CS->getCapturedDecl()->setNothrow();
6142
6143 OMPLoopDirective::HelperExprs B;
6144 // In presence of clause 'collapse' with number of loops, it will define the
6145 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006146 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006147 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6148 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6149 VarsWithImplicitDSA, B);
6150 if (NestedLoopCount == 0)
6151 return StmtError();
6152
6153 assert((CurContext->isDependentContext() || B.builtAll()) &&
6154 "omp target simd loop exprs were not built");
6155
6156 if (!CurContext->isDependentContext()) {
6157 // Finalize the clauses that need pre-built expressions for CodeGen.
6158 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006159 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006160 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6161 B.NumIterations, *this, CurScope,
6162 DSAStack))
6163 return StmtError();
6164 }
6165 }
6166
6167 if (checkSimdlenSafelenSpecified(*this, Clauses))
6168 return StmtError();
6169
6170 getCurFunction()->setHasBranchProtectedScope();
6171 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6172 NestedLoopCount, Clauses, AStmt, B);
6173}
6174
Kelvin Li02532872016-08-05 14:37:37 +00006175StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6176 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6177 SourceLocation EndLoc,
6178 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6179 if (!AStmt)
6180 return StmtError();
6181
6182 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6183 // 1.2.2 OpenMP Language Terminology
6184 // Structured block - An executable statement with a single entry at the
6185 // top and a single exit at the bottom.
6186 // The point of exit cannot be a branch out of the structured block.
6187 // longjmp() and throw() must not violate the entry/exit criteria.
6188 CS->getCapturedDecl()->setNothrow();
6189
6190 OMPLoopDirective::HelperExprs B;
6191 // In presence of clause 'collapse' with number of loops, it will
6192 // define the nested loops number.
6193 unsigned NestedLoopCount =
6194 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6195 nullptr /*ordered not a clause on distribute*/, AStmt,
6196 *this, *DSAStack, VarsWithImplicitDSA, B);
6197 if (NestedLoopCount == 0)
6198 return StmtError();
6199
6200 assert((CurContext->isDependentContext() || B.builtAll()) &&
6201 "omp teams distribute loop exprs were not built");
6202
6203 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006204 return OMPTeamsDistributeDirective::Create(
6205 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006206}
6207
Kelvin Li4e325f72016-10-25 12:50:55 +00006208StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6209 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6210 SourceLocation EndLoc,
6211 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6212 if (!AStmt)
6213 return StmtError();
6214
6215 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6216 // 1.2.2 OpenMP Language Terminology
6217 // Structured block - An executable statement with a single entry at the
6218 // top and a single exit at the bottom.
6219 // The point of exit cannot be a branch out of the structured block.
6220 // longjmp() and throw() must not violate the entry/exit criteria.
6221 CS->getCapturedDecl()->setNothrow();
6222
6223 OMPLoopDirective::HelperExprs B;
6224 // In presence of clause 'collapse' with number of loops, it will
6225 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006226 unsigned NestedLoopCount = CheckOpenMPLoop(
6227 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6228 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6229 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006230
6231 if (NestedLoopCount == 0)
6232 return StmtError();
6233
6234 assert((CurContext->isDependentContext() || B.builtAll()) &&
6235 "omp teams distribute simd loop exprs were not built");
6236
6237 if (!CurContext->isDependentContext()) {
6238 // Finalize the clauses that need pre-built expressions for CodeGen.
6239 for (auto C : Clauses) {
6240 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6241 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6242 B.NumIterations, *this, CurScope,
6243 DSAStack))
6244 return StmtError();
6245 }
6246 }
6247
6248 if (checkSimdlenSafelenSpecified(*this, Clauses))
6249 return StmtError();
6250
6251 getCurFunction()->setHasBranchProtectedScope();
6252 return OMPTeamsDistributeSimdDirective::Create(
6253 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6254}
6255
Kelvin Li579e41c2016-11-30 23:51:03 +00006256StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6257 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6258 SourceLocation EndLoc,
6259 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6260 if (!AStmt)
6261 return StmtError();
6262
6263 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6264 // 1.2.2 OpenMP Language Terminology
6265 // Structured block - An executable statement with a single entry at the
6266 // top and a single exit at the bottom.
6267 // The point of exit cannot be a branch out of the structured block.
6268 // longjmp() and throw() must not violate the entry/exit criteria.
6269 CS->getCapturedDecl()->setNothrow();
6270
6271 OMPLoopDirective::HelperExprs B;
6272 // In presence of clause 'collapse' with number of loops, it will
6273 // define the nested loops number.
6274 auto NestedLoopCount = CheckOpenMPLoop(
6275 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6276 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6277 VarsWithImplicitDSA, B);
6278
6279 if (NestedLoopCount == 0)
6280 return StmtError();
6281
6282 assert((CurContext->isDependentContext() || B.builtAll()) &&
6283 "omp for loop exprs were not built");
6284
6285 if (!CurContext->isDependentContext()) {
6286 // Finalize the clauses that need pre-built expressions for CodeGen.
6287 for (auto C : Clauses) {
6288 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6289 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6290 B.NumIterations, *this, CurScope,
6291 DSAStack))
6292 return StmtError();
6293 }
6294 }
6295
6296 if (checkSimdlenSafelenSpecified(*this, Clauses))
6297 return StmtError();
6298
6299 getCurFunction()->setHasBranchProtectedScope();
6300 return OMPTeamsDistributeParallelForSimdDirective::Create(
6301 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6302}
6303
Kelvin Li7ade93f2016-12-09 03:24:30 +00006304StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6305 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6306 SourceLocation EndLoc,
6307 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6308 if (!AStmt)
6309 return StmtError();
6310
6311 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6312 // 1.2.2 OpenMP Language Terminology
6313 // Structured block - An executable statement with a single entry at the
6314 // top and a single exit at the bottom.
6315 // The point of exit cannot be a branch out of the structured block.
6316 // longjmp() and throw() must not violate the entry/exit criteria.
6317 CS->getCapturedDecl()->setNothrow();
6318
6319 OMPLoopDirective::HelperExprs B;
6320 // In presence of clause 'collapse' with number of loops, it will
6321 // define the nested loops number.
6322 unsigned NestedLoopCount = CheckOpenMPLoop(
6323 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6324 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6325 VarsWithImplicitDSA, B);
6326
6327 if (NestedLoopCount == 0)
6328 return StmtError();
6329
6330 assert((CurContext->isDependentContext() || B.builtAll()) &&
6331 "omp for loop exprs were not built");
6332
6333 if (!CurContext->isDependentContext()) {
6334 // Finalize the clauses that need pre-built expressions for CodeGen.
6335 for (auto C : Clauses) {
6336 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6337 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6338 B.NumIterations, *this, CurScope,
6339 DSAStack))
6340 return StmtError();
6341 }
6342 }
6343
6344 getCurFunction()->setHasBranchProtectedScope();
6345 return OMPTeamsDistributeParallelForDirective::Create(
6346 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6347}
6348
Kelvin Libf594a52016-12-17 05:48:59 +00006349StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6350 Stmt *AStmt,
6351 SourceLocation StartLoc,
6352 SourceLocation EndLoc) {
6353 if (!AStmt)
6354 return StmtError();
6355
6356 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6357 // 1.2.2 OpenMP Language Terminology
6358 // Structured block - An executable statement with a single entry at the
6359 // top and a single exit at the bottom.
6360 // The point of exit cannot be a branch out of the structured block.
6361 // longjmp() and throw() must not violate the entry/exit criteria.
6362 CS->getCapturedDecl()->setNothrow();
6363
6364 getCurFunction()->setHasBranchProtectedScope();
6365
6366 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6367 AStmt);
6368}
6369
Kelvin Li83c451e2016-12-25 04:52:54 +00006370StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6371 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6372 SourceLocation EndLoc,
6373 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6374 if (!AStmt)
6375 return StmtError();
6376
6377 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6378 // 1.2.2 OpenMP Language Terminology
6379 // Structured block - An executable statement with a single entry at the
6380 // top and a single exit at the bottom.
6381 // The point of exit cannot be a branch out of the structured block.
6382 // longjmp() and throw() must not violate the entry/exit criteria.
6383 CS->getCapturedDecl()->setNothrow();
6384
6385 OMPLoopDirective::HelperExprs B;
6386 // In presence of clause 'collapse' with number of loops, it will
6387 // define the nested loops number.
6388 auto NestedLoopCount = CheckOpenMPLoop(
6389 OMPD_target_teams_distribute,
6390 getCollapseNumberExpr(Clauses),
6391 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6392 VarsWithImplicitDSA, B);
6393 if (NestedLoopCount == 0)
6394 return StmtError();
6395
6396 assert((CurContext->isDependentContext() || B.builtAll()) &&
6397 "omp target teams distribute loop exprs were not built");
6398
6399 getCurFunction()->setHasBranchProtectedScope();
6400 return OMPTargetTeamsDistributeDirective::Create(
6401 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6402}
6403
Kelvin Li80e8f562016-12-29 22:16:30 +00006404StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6405 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6406 SourceLocation EndLoc,
6407 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6408 if (!AStmt)
6409 return StmtError();
6410
6411 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6412 // 1.2.2 OpenMP Language Terminology
6413 // Structured block - An executable statement with a single entry at the
6414 // top and a single exit at the bottom.
6415 // The point of exit cannot be a branch out of the structured block.
6416 // longjmp() and throw() must not violate the entry/exit criteria.
6417 CS->getCapturedDecl()->setNothrow();
6418
6419 OMPLoopDirective::HelperExprs B;
6420 // In presence of clause 'collapse' with number of loops, it will
6421 // define the nested loops number.
6422 auto NestedLoopCount = CheckOpenMPLoop(
6423 OMPD_target_teams_distribute_parallel_for,
6424 getCollapseNumberExpr(Clauses),
6425 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6426 VarsWithImplicitDSA, B);
6427 if (NestedLoopCount == 0)
6428 return StmtError();
6429
6430 assert((CurContext->isDependentContext() || B.builtAll()) &&
6431 "omp target teams distribute parallel for loop exprs were not built");
6432
6433 if (!CurContext->isDependentContext()) {
6434 // Finalize the clauses that need pre-built expressions for CodeGen.
6435 for (auto C : Clauses) {
6436 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6437 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6438 B.NumIterations, *this, CurScope,
6439 DSAStack))
6440 return StmtError();
6441 }
6442 }
6443
6444 getCurFunction()->setHasBranchProtectedScope();
6445 return OMPTargetTeamsDistributeParallelForDirective::Create(
6446 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6447}
6448
Kelvin Li1851df52017-01-03 05:23:48 +00006449StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6450 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6451 SourceLocation EndLoc,
6452 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6453 if (!AStmt)
6454 return StmtError();
6455
6456 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6457 // 1.2.2 OpenMP Language Terminology
6458 // Structured block - An executable statement with a single entry at the
6459 // top and a single exit at the bottom.
6460 // The point of exit cannot be a branch out of the structured block.
6461 // longjmp() and throw() must not violate the entry/exit criteria.
6462 CS->getCapturedDecl()->setNothrow();
6463
6464 OMPLoopDirective::HelperExprs B;
6465 // In presence of clause 'collapse' with number of loops, it will
6466 // define the nested loops number.
6467 auto NestedLoopCount = CheckOpenMPLoop(
6468 OMPD_target_teams_distribute_parallel_for_simd,
6469 getCollapseNumberExpr(Clauses),
6470 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6471 VarsWithImplicitDSA, B);
6472 if (NestedLoopCount == 0)
6473 return StmtError();
6474
6475 assert((CurContext->isDependentContext() || B.builtAll()) &&
6476 "omp target teams distribute parallel for simd loop exprs were not "
6477 "built");
6478
6479 if (!CurContext->isDependentContext()) {
6480 // Finalize the clauses that need pre-built expressions for CodeGen.
6481 for (auto C : Clauses) {
6482 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6483 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6484 B.NumIterations, *this, CurScope,
6485 DSAStack))
6486 return StmtError();
6487 }
6488 }
6489
6490 getCurFunction()->setHasBranchProtectedScope();
6491 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6492 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6493}
6494
Kelvin Lida681182017-01-10 18:08:18 +00006495StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6496 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6497 SourceLocation EndLoc,
6498 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6499 if (!AStmt)
6500 return StmtError();
6501
6502 auto *CS = cast<CapturedStmt>(AStmt);
6503 // 1.2.2 OpenMP Language Terminology
6504 // Structured block - An executable statement with a single entry at the
6505 // top and a single exit at the bottom.
6506 // The point of exit cannot be a branch out of the structured block.
6507 // longjmp() and throw() must not violate the entry/exit criteria.
6508 CS->getCapturedDecl()->setNothrow();
6509
6510 OMPLoopDirective::HelperExprs B;
6511 // In presence of clause 'collapse' with number of loops, it will
6512 // define the nested loops number.
6513 auto NestedLoopCount = CheckOpenMPLoop(
6514 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6515 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6516 VarsWithImplicitDSA, B);
6517 if (NestedLoopCount == 0)
6518 return StmtError();
6519
6520 assert((CurContext->isDependentContext() || B.builtAll()) &&
6521 "omp target teams distribute simd loop exprs were not built");
6522
6523 getCurFunction()->setHasBranchProtectedScope();
6524 return OMPTargetTeamsDistributeSimdDirective::Create(
6525 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6526}
6527
Alexey Bataeved09d242014-05-28 05:53:51 +00006528OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006529 SourceLocation StartLoc,
6530 SourceLocation LParenLoc,
6531 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006532 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006533 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006534 case OMPC_final:
6535 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6536 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006537 case OMPC_num_threads:
6538 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6539 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006540 case OMPC_safelen:
6541 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6542 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006543 case OMPC_simdlen:
6544 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6545 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006546 case OMPC_collapse:
6547 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6548 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006549 case OMPC_ordered:
6550 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6551 break;
Michael Wonge710d542015-08-07 16:16:36 +00006552 case OMPC_device:
6553 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6554 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006555 case OMPC_num_teams:
6556 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6557 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006558 case OMPC_thread_limit:
6559 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6560 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006561 case OMPC_priority:
6562 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6563 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006564 case OMPC_grainsize:
6565 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6566 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006567 case OMPC_num_tasks:
6568 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6569 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006570 case OMPC_hint:
6571 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6572 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006573 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006574 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006575 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006576 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006577 case OMPC_private:
6578 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006579 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006580 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006581 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006582 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006583 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006584 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006585 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006586 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006587 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006588 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006589 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006590 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006591 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006592 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006593 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006594 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006595 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006596 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006597 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006598 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006599 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006600 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006601 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006602 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006603 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006604 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006605 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006606 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006607 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006608 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006609 llvm_unreachable("Clause is not allowed.");
6610 }
6611 return Res;
6612}
6613
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006614OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6615 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006616 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006617 SourceLocation NameModifierLoc,
6618 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006619 SourceLocation EndLoc) {
6620 Expr *ValExpr = Condition;
6621 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6622 !Condition->isInstantiationDependent() &&
6623 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006624 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006625 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006626 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006627
Richard Smith03a4aa32016-06-23 19:02:52 +00006628 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006629 }
6630
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006631 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6632 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006633}
6634
Alexey Bataev3778b602014-07-17 07:32:53 +00006635OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6636 SourceLocation StartLoc,
6637 SourceLocation LParenLoc,
6638 SourceLocation EndLoc) {
6639 Expr *ValExpr = Condition;
6640 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6641 !Condition->isInstantiationDependent() &&
6642 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006643 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006644 if (Val.isInvalid())
6645 return nullptr;
6646
Richard Smith03a4aa32016-06-23 19:02:52 +00006647 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006648 }
6649
6650 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6651}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006652ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6653 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006654 if (!Op)
6655 return ExprError();
6656
6657 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6658 public:
6659 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006660 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006661 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6662 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006663 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6664 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006665 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6666 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006667 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6668 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006669 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6670 QualType T,
6671 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006672 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6673 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006674 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6675 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006676 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006677 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006678 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006679 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6680 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006681 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6682 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006683 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6684 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006685 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006686 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006687 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006688 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6689 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006690 llvm_unreachable("conversion functions are permitted");
6691 }
6692 } ConvertDiagnoser;
6693 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6694}
6695
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006696static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006697 OpenMPClauseKind CKind,
6698 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006699 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6700 !ValExpr->isInstantiationDependent()) {
6701 SourceLocation Loc = ValExpr->getExprLoc();
6702 ExprResult Value =
6703 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6704 if (Value.isInvalid())
6705 return false;
6706
6707 ValExpr = Value.get();
6708 // The expression must evaluate to a non-negative integer value.
6709 llvm::APSInt Result;
6710 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006711 Result.isSigned() &&
6712 !((!StrictlyPositive && Result.isNonNegative()) ||
6713 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006714 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006715 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6716 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006717 return false;
6718 }
6719 }
6720 return true;
6721}
6722
Alexey Bataev568a8332014-03-06 06:15:19 +00006723OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6724 SourceLocation StartLoc,
6725 SourceLocation LParenLoc,
6726 SourceLocation EndLoc) {
6727 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006728
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006729 // OpenMP [2.5, Restrictions]
6730 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006731 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6732 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006733 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006734
Alexey Bataeved09d242014-05-28 05:53:51 +00006735 return new (Context)
6736 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006737}
6738
Alexey Bataev62c87d22014-03-21 04:51:18 +00006739ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006740 OpenMPClauseKind CKind,
6741 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006742 if (!E)
6743 return ExprError();
6744 if (E->isValueDependent() || E->isTypeDependent() ||
6745 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006746 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006747 llvm::APSInt Result;
6748 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6749 if (ICE.isInvalid())
6750 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006751 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6752 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006753 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006754 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6755 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006756 return ExprError();
6757 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006758 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6759 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6760 << E->getSourceRange();
6761 return ExprError();
6762 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006763 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6764 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006765 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006766 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006767 return ICE;
6768}
6769
6770OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6771 SourceLocation LParenLoc,
6772 SourceLocation EndLoc) {
6773 // OpenMP [2.8.1, simd construct, Description]
6774 // The parameter of the safelen clause must be a constant
6775 // positive integer expression.
6776 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6777 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006778 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006779 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006780 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006781}
6782
Alexey Bataev66b15b52015-08-21 11:14:16 +00006783OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6784 SourceLocation LParenLoc,
6785 SourceLocation EndLoc) {
6786 // OpenMP [2.8.1, simd construct, Description]
6787 // The parameter of the simdlen clause must be a constant
6788 // positive integer expression.
6789 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6790 if (Simdlen.isInvalid())
6791 return nullptr;
6792 return new (Context)
6793 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6794}
6795
Alexander Musman64d33f12014-06-04 07:53:32 +00006796OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6797 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006798 SourceLocation LParenLoc,
6799 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006800 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006801 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006802 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006803 // The parameter of the collapse clause must be a constant
6804 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006805 ExprResult NumForLoopsResult =
6806 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6807 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006808 return nullptr;
6809 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006810 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006811}
6812
Alexey Bataev10e775f2015-07-30 11:36:16 +00006813OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6814 SourceLocation EndLoc,
6815 SourceLocation LParenLoc,
6816 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006817 // OpenMP [2.7.1, loop construct, Description]
6818 // OpenMP [2.8.1, simd construct, Description]
6819 // OpenMP [2.9.6, distribute construct, Description]
6820 // The parameter of the ordered clause must be a constant
6821 // positive integer expression if any.
6822 if (NumForLoops && LParenLoc.isValid()) {
6823 ExprResult NumForLoopsResult =
6824 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6825 if (NumForLoopsResult.isInvalid())
6826 return nullptr;
6827 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006828 } else
6829 NumForLoops = nullptr;
6830 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006831 return new (Context)
6832 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6833}
6834
Alexey Bataeved09d242014-05-28 05:53:51 +00006835OMPClause *Sema::ActOnOpenMPSimpleClause(
6836 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6837 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006838 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006839 switch (Kind) {
6840 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006841 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006842 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6843 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006844 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006845 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006846 Res = ActOnOpenMPProcBindClause(
6847 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6848 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006849 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006850 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006851 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006852 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006853 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006854 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006855 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006856 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006857 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006858 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006859 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006860 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006861 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006862 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006863 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006864 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006865 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006866 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006867 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006868 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006869 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006870 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006871 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006872 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006873 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006874 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006875 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006876 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006877 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006878 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006879 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006880 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006881 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006882 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006883 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006884 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006885 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006886 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006887 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006888 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006889 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006890 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006891 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006892 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006893 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006894 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006895 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006896 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006897 llvm_unreachable("Clause is not allowed.");
6898 }
6899 return Res;
6900}
6901
Alexey Bataev6402bca2015-12-28 07:25:51 +00006902static std::string
6903getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6904 ArrayRef<unsigned> Exclude = llvm::None) {
6905 std::string Values;
6906 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6907 unsigned Skipped = Exclude.size();
6908 auto S = Exclude.begin(), E = Exclude.end();
6909 for (unsigned i = First; i < Last; ++i) {
6910 if (std::find(S, E, i) != E) {
6911 --Skipped;
6912 continue;
6913 }
6914 Values += "'";
6915 Values += getOpenMPSimpleClauseTypeName(K, i);
6916 Values += "'";
6917 if (i == Bound - Skipped)
6918 Values += " or ";
6919 else if (i != Bound + 1 - Skipped)
6920 Values += ", ";
6921 }
6922 return Values;
6923}
6924
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006925OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6926 SourceLocation KindKwLoc,
6927 SourceLocation StartLoc,
6928 SourceLocation LParenLoc,
6929 SourceLocation EndLoc) {
6930 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006931 static_assert(OMPC_DEFAULT_unknown > 0,
6932 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006933 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006934 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6935 /*Last=*/OMPC_DEFAULT_unknown)
6936 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006937 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006938 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006939 switch (Kind) {
6940 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006941 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006942 break;
6943 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006944 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006945 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006946 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006947 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006948 break;
6949 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006950 return new (Context)
6951 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006952}
6953
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006954OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6955 SourceLocation KindKwLoc,
6956 SourceLocation StartLoc,
6957 SourceLocation LParenLoc,
6958 SourceLocation EndLoc) {
6959 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006960 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006961 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6962 /*Last=*/OMPC_PROC_BIND_unknown)
6963 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006964 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006965 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006966 return new (Context)
6967 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006968}
6969
Alexey Bataev56dafe82014-06-20 07:16:17 +00006970OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006971 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006972 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006973 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006974 SourceLocation EndLoc) {
6975 OMPClause *Res = nullptr;
6976 switch (Kind) {
6977 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006978 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6979 assert(Argument.size() == NumberOfElements &&
6980 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006981 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006982 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6983 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6984 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6985 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6986 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006987 break;
6988 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006989 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6990 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6991 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6992 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006993 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006994 case OMPC_dist_schedule:
6995 Res = ActOnOpenMPDistScheduleClause(
6996 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6997 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6998 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006999 case OMPC_defaultmap:
7000 enum { Modifier, DefaultmapKind };
7001 Res = ActOnOpenMPDefaultmapClause(
7002 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7003 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007004 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7005 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007006 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007007 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007008 case OMPC_num_threads:
7009 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007010 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007011 case OMPC_collapse:
7012 case OMPC_default:
7013 case OMPC_proc_bind:
7014 case OMPC_private:
7015 case OMPC_firstprivate:
7016 case OMPC_lastprivate:
7017 case OMPC_shared:
7018 case OMPC_reduction:
7019 case OMPC_linear:
7020 case OMPC_aligned:
7021 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007022 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007023 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007024 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007025 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007026 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007027 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007028 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007029 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007030 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007031 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007032 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007033 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007034 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007035 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007036 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007037 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007038 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007039 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007040 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007041 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007042 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007043 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007044 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007045 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007046 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007047 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007048 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007049 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007050 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007051 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007052 llvm_unreachable("Clause is not allowed.");
7053 }
7054 return Res;
7055}
7056
Alexey Bataev6402bca2015-12-28 07:25:51 +00007057static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7058 OpenMPScheduleClauseModifier M2,
7059 SourceLocation M1Loc, SourceLocation M2Loc) {
7060 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7061 SmallVector<unsigned, 2> Excluded;
7062 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7063 Excluded.push_back(M2);
7064 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7065 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7066 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7067 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7068 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7069 << getListOfPossibleValues(OMPC_schedule,
7070 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7071 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7072 Excluded)
7073 << getOpenMPClauseName(OMPC_schedule);
7074 return true;
7075 }
7076 return false;
7077}
7078
Alexey Bataev56dafe82014-06-20 07:16:17 +00007079OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007080 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007081 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007082 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7083 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7084 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7085 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7086 return nullptr;
7087 // OpenMP, 2.7.1, Loop Construct, Restrictions
7088 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7089 // but not both.
7090 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7091 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7092 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7093 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7094 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7095 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7096 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7097 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7098 return nullptr;
7099 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007100 if (Kind == OMPC_SCHEDULE_unknown) {
7101 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007102 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7103 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7104 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7105 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7106 Exclude);
7107 } else {
7108 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7109 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007110 }
7111 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7112 << Values << getOpenMPClauseName(OMPC_schedule);
7113 return nullptr;
7114 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007115 // OpenMP, 2.7.1, Loop Construct, Restrictions
7116 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7117 // schedule(guided).
7118 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7119 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7120 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7121 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7122 diag::err_omp_schedule_nonmonotonic_static);
7123 return nullptr;
7124 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007125 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007126 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007127 if (ChunkSize) {
7128 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7129 !ChunkSize->isInstantiationDependent() &&
7130 !ChunkSize->containsUnexpandedParameterPack()) {
7131 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7132 ExprResult Val =
7133 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7134 if (Val.isInvalid())
7135 return nullptr;
7136
7137 ValExpr = Val.get();
7138
7139 // OpenMP [2.7.1, Restrictions]
7140 // chunk_size must be a loop invariant integer expression with a positive
7141 // value.
7142 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007143 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7144 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7145 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007146 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007147 return nullptr;
7148 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007149 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7150 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007151 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7152 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7153 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007154 }
7155 }
7156 }
7157
Alexey Bataev6402bca2015-12-28 07:25:51 +00007158 return new (Context)
7159 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007160 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007161}
7162
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007163OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7164 SourceLocation StartLoc,
7165 SourceLocation EndLoc) {
7166 OMPClause *Res = nullptr;
7167 switch (Kind) {
7168 case OMPC_ordered:
7169 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7170 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007171 case OMPC_nowait:
7172 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7173 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007174 case OMPC_untied:
7175 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7176 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007177 case OMPC_mergeable:
7178 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7179 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007180 case OMPC_read:
7181 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7182 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007183 case OMPC_write:
7184 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7185 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007186 case OMPC_update:
7187 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7188 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007189 case OMPC_capture:
7190 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7191 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007192 case OMPC_seq_cst:
7193 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7194 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007195 case OMPC_threads:
7196 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7197 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007198 case OMPC_simd:
7199 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7200 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007201 case OMPC_nogroup:
7202 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7203 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007204 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007205 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007206 case OMPC_num_threads:
7207 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007208 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007209 case OMPC_collapse:
7210 case OMPC_schedule:
7211 case OMPC_private:
7212 case OMPC_firstprivate:
7213 case OMPC_lastprivate:
7214 case OMPC_shared:
7215 case OMPC_reduction:
7216 case OMPC_linear:
7217 case OMPC_aligned:
7218 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007219 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007220 case OMPC_default:
7221 case OMPC_proc_bind:
7222 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007223 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007224 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007225 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007226 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007227 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007228 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007229 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007230 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007231 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007232 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007233 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007234 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007235 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007236 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007237 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007238 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007239 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007240 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007241 llvm_unreachable("Clause is not allowed.");
7242 }
7243 return Res;
7244}
7245
Alexey Bataev236070f2014-06-20 11:19:47 +00007246OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7247 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007248 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007249 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7250}
7251
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007252OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7253 SourceLocation EndLoc) {
7254 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7255}
7256
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007257OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7258 SourceLocation EndLoc) {
7259 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7260}
7261
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007262OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7263 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007264 return new (Context) OMPReadClause(StartLoc, EndLoc);
7265}
7266
Alexey Bataevdea47612014-07-23 07:46:59 +00007267OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7268 SourceLocation EndLoc) {
7269 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7270}
7271
Alexey Bataev67a4f222014-07-23 10:25:33 +00007272OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7273 SourceLocation EndLoc) {
7274 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7275}
7276
Alexey Bataev459dec02014-07-24 06:46:57 +00007277OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7278 SourceLocation EndLoc) {
7279 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7280}
7281
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007282OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7283 SourceLocation EndLoc) {
7284 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7285}
7286
Alexey Bataev346265e2015-09-25 10:37:12 +00007287OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7288 SourceLocation EndLoc) {
7289 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7290}
7291
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007292OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7293 SourceLocation EndLoc) {
7294 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7295}
7296
Alexey Bataevb825de12015-12-07 10:51:44 +00007297OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7298 SourceLocation EndLoc) {
7299 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7300}
7301
Alexey Bataevc5e02582014-06-16 07:08:35 +00007302OMPClause *Sema::ActOnOpenMPVarListClause(
7303 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7304 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7305 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007306 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007307 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7308 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7309 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007310 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007311 switch (Kind) {
7312 case OMPC_private:
7313 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7314 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007315 case OMPC_firstprivate:
7316 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7317 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007318 case OMPC_lastprivate:
7319 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7320 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007321 case OMPC_shared:
7322 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7323 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007324 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007325 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7326 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007327 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007328 case OMPC_linear:
7329 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007330 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007331 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007332 case OMPC_aligned:
7333 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7334 ColonLoc, EndLoc);
7335 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007336 case OMPC_copyin:
7337 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7338 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007339 case OMPC_copyprivate:
7340 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7341 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007342 case OMPC_flush:
7343 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7344 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007345 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007346 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007347 StartLoc, LParenLoc, EndLoc);
7348 break;
7349 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007350 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7351 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7352 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007353 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007354 case OMPC_to:
7355 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7356 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007357 case OMPC_from:
7358 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7359 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007360 case OMPC_use_device_ptr:
7361 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7362 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007363 case OMPC_is_device_ptr:
7364 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7365 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007366 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007367 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007368 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007369 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007370 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007371 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007372 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007373 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007374 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007375 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007376 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007377 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007378 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007379 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007380 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007381 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007382 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007383 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007384 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007385 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007386 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007387 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007388 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007389 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007390 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007391 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007392 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007393 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007394 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007395 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007396 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007397 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007398 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007399 llvm_unreachable("Clause is not allowed.");
7400 }
7401 return Res;
7402}
7403
Alexey Bataev90c228f2016-02-08 09:29:13 +00007404ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007405 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007406 ExprResult Res = BuildDeclRefExpr(
7407 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7408 if (!Res.isUsable())
7409 return ExprError();
7410 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7411 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7412 if (!Res.isUsable())
7413 return ExprError();
7414 }
7415 if (VK != VK_LValue && Res.get()->isGLValue()) {
7416 Res = DefaultLvalueConversion(Res.get());
7417 if (!Res.isUsable())
7418 return ExprError();
7419 }
7420 return Res;
7421}
7422
Alexey Bataev60da77e2016-02-29 05:54:20 +00007423static std::pair<ValueDecl *, bool>
7424getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7425 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007426 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7427 RefExpr->containsUnexpandedParameterPack())
7428 return std::make_pair(nullptr, true);
7429
Alexey Bataevd985eda2016-02-10 11:29:16 +00007430 // OpenMP [3.1, C/C++]
7431 // A list item is a variable name.
7432 // OpenMP [2.9.3.3, Restrictions, p.1]
7433 // A variable that is part of another variable (as an array or
7434 // structure element) cannot appear in a private clause.
7435 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007436 enum {
7437 NoArrayExpr = -1,
7438 ArraySubscript = 0,
7439 OMPArraySection = 1
7440 } IsArrayExpr = NoArrayExpr;
7441 if (AllowArraySection) {
7442 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7443 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7444 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7445 Base = TempASE->getBase()->IgnoreParenImpCasts();
7446 RefExpr = Base;
7447 IsArrayExpr = ArraySubscript;
7448 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7449 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7450 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7451 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7452 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7453 Base = TempASE->getBase()->IgnoreParenImpCasts();
7454 RefExpr = Base;
7455 IsArrayExpr = OMPArraySection;
7456 }
7457 }
7458 ELoc = RefExpr->getExprLoc();
7459 ERange = RefExpr->getSourceRange();
7460 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007461 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7462 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7463 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7464 (S.getCurrentThisType().isNull() || !ME ||
7465 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7466 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007467 if (IsArrayExpr != NoArrayExpr)
7468 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7469 << ERange;
7470 else {
7471 S.Diag(ELoc,
7472 AllowArraySection
7473 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7474 : diag::err_omp_expected_var_name_member_expr)
7475 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7476 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007477 return std::make_pair(nullptr, false);
7478 }
7479 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7480}
7481
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007482OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7483 SourceLocation StartLoc,
7484 SourceLocation LParenLoc,
7485 SourceLocation EndLoc) {
7486 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007487 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007488 for (auto &RefExpr : VarList) {
7489 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007490 SourceLocation ELoc;
7491 SourceRange ERange;
7492 Expr *SimpleRefExpr = RefExpr;
7493 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007494 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007495 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007496 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007497 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007498 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007499 ValueDecl *D = Res.first;
7500 if (!D)
7501 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007502
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007503 QualType Type = D->getType();
7504 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007505
7506 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7507 // A variable that appears in a private clause must not have an incomplete
7508 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007509 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007510 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007511 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007512
Alexey Bataev758e55e2013-09-06 18:03:48 +00007513 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7514 // in a Construct]
7515 // Variables with the predetermined data-sharing attributes may not be
7516 // listed in data-sharing attributes clauses, except for the cases
7517 // listed below. For these exceptions only, listing a predetermined
7518 // variable in a data-sharing attribute clause is allowed and overrides
7519 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007520 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007521 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007522 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7523 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007524 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007525 continue;
7526 }
7527
Kelvin Libf594a52016-12-17 05:48:59 +00007528 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007529 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007530 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007531 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007532 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7533 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007534 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007535 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007536 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007537 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007538 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007539 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007540 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007541 continue;
7542 }
7543
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007544 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7545 // A list item cannot appear in both a map clause and a data-sharing
7546 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007547 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007548 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007549 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007550 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007551 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007552 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007553 CurrDir == OMPD_target_parallel_for_simd ||
7554 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007555 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007556 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007557 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007558 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7559 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7560 ConflictKind = WhereFoundClauseKind;
7561 return true;
7562 })) {
7563 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007564 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007565 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007566 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007567 ReportOriginalDSA(*this, DSAStack, D, DVar);
7568 continue;
7569 }
7570 }
7571
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007572 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7573 // A variable of class type (or array thereof) that appears in a private
7574 // clause requires an accessible, unambiguous default constructor for the
7575 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007576 // Generate helper private variable and initialize it with the default
7577 // value. The address of the original variable is replaced by the address of
7578 // the new private variable in CodeGen. This new variable is not added to
7579 // IdResolver, so the code in the OpenMP region uses original variable for
7580 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007581 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007582 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7583 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00007584 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007585 if (VDPrivate->isInvalidDecl())
7586 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007587 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007588 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007589
Alexey Bataev90c228f2016-02-08 09:29:13 +00007590 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007591 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007592 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007593 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007594 Vars.push_back((VD || CurContext->isDependentContext())
7595 ? RefExpr->IgnoreParens()
7596 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007597 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007598 }
7599
Alexey Bataeved09d242014-05-28 05:53:51 +00007600 if (Vars.empty())
7601 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007602
Alexey Bataev03b340a2014-10-21 03:16:40 +00007603 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7604 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007605}
7606
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007607namespace {
7608class DiagsUninitializedSeveretyRAII {
7609private:
7610 DiagnosticsEngine &Diags;
7611 SourceLocation SavedLoc;
7612 bool IsIgnored;
7613
7614public:
7615 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7616 bool IsIgnored)
7617 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7618 if (!IsIgnored) {
7619 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7620 /*Map*/ diag::Severity::Ignored, Loc);
7621 }
7622 }
7623 ~DiagsUninitializedSeveretyRAII() {
7624 if (!IsIgnored)
7625 Diags.popMappings(SavedLoc);
7626 }
7627};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007628}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007629
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007630OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7631 SourceLocation StartLoc,
7632 SourceLocation LParenLoc,
7633 SourceLocation EndLoc) {
7634 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007635 SmallVector<Expr *, 8> PrivateCopies;
7636 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007637 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007638 bool IsImplicitClause =
7639 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7640 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7641
Alexey Bataeved09d242014-05-28 05:53:51 +00007642 for (auto &RefExpr : VarList) {
7643 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007644 SourceLocation ELoc;
7645 SourceRange ERange;
7646 Expr *SimpleRefExpr = RefExpr;
7647 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007648 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007649 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007650 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007651 PrivateCopies.push_back(nullptr);
7652 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007653 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007654 ValueDecl *D = Res.first;
7655 if (!D)
7656 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007657
Alexey Bataev60da77e2016-02-29 05:54:20 +00007658 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007659 QualType Type = D->getType();
7660 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007661
7662 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7663 // A variable that appears in a private clause must not have an incomplete
7664 // type or a reference type.
7665 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007666 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007667 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007668 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007669
7670 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7671 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007672 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007673 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007674 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007675
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007676 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007677 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007678 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007679 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007680 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007681 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007682 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7683 // A list item that specifies a given variable may not appear in more
7684 // than one clause on the same directive, except that a variable may be
7685 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007686 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007687 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007688 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007689 << getOpenMPClauseName(DVar.CKind)
7690 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007691 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007692 continue;
7693 }
7694
7695 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7696 // in a Construct]
7697 // Variables with the predetermined data-sharing attributes may not be
7698 // listed in data-sharing attributes clauses, except for the cases
7699 // listed below. For these exceptions only, listing a predetermined
7700 // variable in a data-sharing attribute clause is allowed and overrides
7701 // the variable's predetermined data-sharing attributes.
7702 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7703 // in a Construct, C/C++, p.2]
7704 // Variables with const-qualified type having no mutable member may be
7705 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007706 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007707 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7708 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007709 << getOpenMPClauseName(DVar.CKind)
7710 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007711 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007712 continue;
7713 }
7714
Alexey Bataevf29276e2014-06-18 04:14:57 +00007715 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007716 // OpenMP [2.9.3.4, Restrictions, p.2]
7717 // A list item that is private within a parallel region must not appear
7718 // in a firstprivate clause on a worksharing construct if any of the
7719 // worksharing regions arising from the worksharing construct ever bind
7720 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007721 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007722 !isOpenMPParallelDirective(CurrDir) &&
7723 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007724 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007725 if (DVar.CKind != OMPC_shared &&
7726 (isOpenMPParallelDirective(DVar.DKind) ||
7727 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007728 Diag(ELoc, diag::err_omp_required_access)
7729 << getOpenMPClauseName(OMPC_firstprivate)
7730 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007731 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007732 continue;
7733 }
7734 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007735 // OpenMP [2.9.3.4, Restrictions, p.3]
7736 // A list item that appears in a reduction clause of a parallel construct
7737 // must not appear in a firstprivate clause on a worksharing or task
7738 // construct if any of the worksharing or task regions arising from the
7739 // worksharing or task construct ever bind to any of the parallel regions
7740 // arising from the parallel construct.
7741 // OpenMP [2.9.3.4, Restrictions, p.4]
7742 // A list item that appears in a reduction clause in worksharing
7743 // construct must not appear in a firstprivate clause in a task construct
7744 // encountered during execution of any of the worksharing regions arising
7745 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007746 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007747 DVar = DSAStack->hasInnermostDSA(
7748 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7749 [](OpenMPDirectiveKind K) -> bool {
7750 return isOpenMPParallelDirective(K) ||
7751 isOpenMPWorksharingDirective(K);
7752 },
7753 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007754 if (DVar.CKind == OMPC_reduction &&
7755 (isOpenMPParallelDirective(DVar.DKind) ||
7756 isOpenMPWorksharingDirective(DVar.DKind))) {
7757 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7758 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007759 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007760 continue;
7761 }
7762 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007763
7764 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7765 // A list item that is private within a teams region must not appear in a
7766 // firstprivate clause on a distribute construct if any of the distribute
7767 // regions arising from the distribute construct ever bind to any of the
7768 // teams regions arising from the teams construct.
7769 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7770 // A list item that appears in a reduction clause of a teams construct
7771 // must not appear in a firstprivate clause on a distribute construct if
7772 // any of the distribute regions arising from the distribute construct
7773 // ever bind to any of the teams regions arising from the teams construct.
7774 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7775 // A list item may appear in a firstprivate or lastprivate clause but not
7776 // both.
7777 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007778 DVar = DSAStack->hasInnermostDSA(
7779 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7780 [](OpenMPDirectiveKind K) -> bool {
7781 return isOpenMPTeamsDirective(K);
7782 },
7783 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007784 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7785 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007786 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007787 continue;
7788 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007789 DVar = DSAStack->hasInnermostDSA(
7790 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7791 [](OpenMPDirectiveKind K) -> bool {
7792 return isOpenMPTeamsDirective(K);
7793 },
7794 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007795 if (DVar.CKind == OMPC_reduction &&
7796 isOpenMPTeamsDirective(DVar.DKind)) {
7797 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007798 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007799 continue;
7800 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007801 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007802 if (DVar.CKind == OMPC_lastprivate) {
7803 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007804 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007805 continue;
7806 }
7807 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007808 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7809 // A list item cannot appear in both a map clause and a data-sharing
7810 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007811 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007812 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007813 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007814 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007815 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007816 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007817 CurrDir == OMPD_target_parallel_for_simd ||
7818 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007819 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007820 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007821 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007822 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7823 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7824 ConflictKind = WhereFoundClauseKind;
7825 return true;
7826 })) {
7827 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007828 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007829 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007830 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7831 ReportOriginalDSA(*this, DSAStack, D, DVar);
7832 continue;
7833 }
7834 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007835 }
7836
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007837 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007838 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007839 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007840 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7841 << getOpenMPClauseName(OMPC_firstprivate) << Type
7842 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7843 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007844 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007845 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007846 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007847 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007848 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007849 continue;
7850 }
7851
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007852 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007853 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7854 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007855 // Generate helper private variable and initialize it with the value of the
7856 // original variable. The address of the original variable is replaced by
7857 // the address of the new private variable in the CodeGen. This new variable
7858 // is not added to IdResolver, so the code in the OpenMP region uses
7859 // original variable for proper diagnostics and variable capturing.
7860 Expr *VDInitRefExpr = nullptr;
7861 // For arrays generate initializer for single element and replace it by the
7862 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007863 if (Type->isArrayType()) {
7864 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007865 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007866 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007867 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007868 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007869 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007870 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007871 InitializedEntity Entity =
7872 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007873 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7874
7875 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7876 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7877 if (Result.isInvalid())
7878 VDPrivate->setInvalidDecl();
7879 else
7880 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007881 // Remove temp variable declaration.
7882 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007883 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007884 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7885 ".firstprivate.temp");
7886 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7887 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007888 AddInitializerToDecl(VDPrivate,
7889 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007890 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007891 }
7892 if (VDPrivate->isInvalidDecl()) {
7893 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007894 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007895 diag::note_omp_task_predetermined_firstprivate_here);
7896 }
7897 continue;
7898 }
7899 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007900 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007901 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7902 RefExpr->getExprLoc());
7903 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007904 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007905 if (TopDVar.CKind == OMPC_lastprivate)
7906 Ref = TopDVar.PrivateCopy;
7907 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007908 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007909 if (!IsOpenMPCapturedDecl(D))
7910 ExprCaptures.push_back(Ref->getDecl());
7911 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007912 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007913 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007914 Vars.push_back((VD || CurContext->isDependentContext())
7915 ? RefExpr->IgnoreParens()
7916 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007917 PrivateCopies.push_back(VDPrivateRefExpr);
7918 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007919 }
7920
Alexey Bataeved09d242014-05-28 05:53:51 +00007921 if (Vars.empty())
7922 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007923
7924 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007925 Vars, PrivateCopies, Inits,
7926 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007927}
7928
Alexander Musman1bb328c2014-06-04 13:06:39 +00007929OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7930 SourceLocation StartLoc,
7931 SourceLocation LParenLoc,
7932 SourceLocation EndLoc) {
7933 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007934 SmallVector<Expr *, 8> SrcExprs;
7935 SmallVector<Expr *, 8> DstExprs;
7936 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007937 SmallVector<Decl *, 4> ExprCaptures;
7938 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007939 for (auto &RefExpr : VarList) {
7940 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007941 SourceLocation ELoc;
7942 SourceRange ERange;
7943 Expr *SimpleRefExpr = RefExpr;
7944 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007945 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007946 // It will be analyzed later.
7947 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007948 SrcExprs.push_back(nullptr);
7949 DstExprs.push_back(nullptr);
7950 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007951 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007952 ValueDecl *D = Res.first;
7953 if (!D)
7954 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007955
Alexey Bataev74caaf22016-02-20 04:09:36 +00007956 QualType Type = D->getType();
7957 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007958
7959 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7960 // A variable that appears in a lastprivate clause must not have an
7961 // incomplete type or a reference type.
7962 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007963 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007964 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007965 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007966
7967 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7968 // in a Construct]
7969 // Variables with the predetermined data-sharing attributes may not be
7970 // listed in data-sharing attributes clauses, except for the cases
7971 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007972 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007973 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7974 DVar.CKind != OMPC_firstprivate &&
7975 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7976 Diag(ELoc, diag::err_omp_wrong_dsa)
7977 << getOpenMPClauseName(DVar.CKind)
7978 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007979 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007980 continue;
7981 }
7982
Alexey Bataevf29276e2014-06-18 04:14:57 +00007983 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7984 // OpenMP [2.14.3.5, Restrictions, p.2]
7985 // A list item that is private within a parallel region, or that appears in
7986 // the reduction clause of a parallel construct, must not appear in a
7987 // lastprivate clause on a worksharing construct if any of the corresponding
7988 // worksharing regions ever binds to any of the corresponding parallel
7989 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007990 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007991 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007992 !isOpenMPParallelDirective(CurrDir) &&
7993 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007994 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007995 if (DVar.CKind != OMPC_shared) {
7996 Diag(ELoc, diag::err_omp_required_access)
7997 << getOpenMPClauseName(OMPC_lastprivate)
7998 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007999 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008000 continue;
8001 }
8002 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008003
8004 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8005 // A list item may appear in a firstprivate or lastprivate clause but not
8006 // both.
8007 if (CurrDir == OMPD_distribute) {
8008 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8009 if (DVar.CKind == OMPC_firstprivate) {
8010 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8011 ReportOriginalDSA(*this, DSAStack, D, DVar);
8012 continue;
8013 }
8014 }
8015
Alexander Musman1bb328c2014-06-04 13:06:39 +00008016 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008017 // A variable of class type (or array thereof) that appears in a
8018 // lastprivate clause requires an accessible, unambiguous default
8019 // constructor for the class type, unless the list item is also specified
8020 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008021 // A variable of class type (or array thereof) that appears in a
8022 // lastprivate clause requires an accessible, unambiguous copy assignment
8023 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008024 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008025 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008026 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008027 D->hasAttrs() ? &D->getAttrs() : nullptr);
8028 auto *PseudoSrcExpr =
8029 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008030 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008031 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008032 D->hasAttrs() ? &D->getAttrs() : nullptr);
8033 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008034 // For arrays generate assignment operation for single element and replace
8035 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008036 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008037 PseudoDstExpr, PseudoSrcExpr);
8038 if (AssignmentOp.isInvalid())
8039 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008040 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008041 /*DiscardedValue=*/true);
8042 if (AssignmentOp.isInvalid())
8043 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008044
Alexey Bataev74caaf22016-02-20 04:09:36 +00008045 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008046 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008047 if (TopDVar.CKind == OMPC_firstprivate)
8048 Ref = TopDVar.PrivateCopy;
8049 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008050 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008051 if (!IsOpenMPCapturedDecl(D))
8052 ExprCaptures.push_back(Ref->getDecl());
8053 }
8054 if (TopDVar.CKind == OMPC_firstprivate ||
8055 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008056 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008057 ExprResult RefRes = DefaultLvalueConversion(Ref);
8058 if (!RefRes.isUsable())
8059 continue;
8060 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008061 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8062 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008063 if (!PostUpdateRes.isUsable())
8064 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008065 ExprPostUpdates.push_back(
8066 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008067 }
8068 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008069 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008070 Vars.push_back((VD || CurContext->isDependentContext())
8071 ? RefExpr->IgnoreParens()
8072 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008073 SrcExprs.push_back(PseudoSrcExpr);
8074 DstExprs.push_back(PseudoDstExpr);
8075 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008076 }
8077
8078 if (Vars.empty())
8079 return nullptr;
8080
8081 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008082 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008083 buildPreInits(Context, ExprCaptures),
8084 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008085}
8086
Alexey Bataev758e55e2013-09-06 18:03:48 +00008087OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8088 SourceLocation StartLoc,
8089 SourceLocation LParenLoc,
8090 SourceLocation EndLoc) {
8091 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008092 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008093 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008094 SourceLocation ELoc;
8095 SourceRange ERange;
8096 Expr *SimpleRefExpr = RefExpr;
8097 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008098 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008099 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008100 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008101 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008102 ValueDecl *D = Res.first;
8103 if (!D)
8104 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008105
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008106 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008107 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8108 // in a Construct]
8109 // Variables with the predetermined data-sharing attributes may not be
8110 // listed in data-sharing attributes clauses, except for the cases
8111 // listed below. For these exceptions only, listing a predetermined
8112 // variable in a data-sharing attribute clause is allowed and overrides
8113 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008114 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008115 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8116 DVar.RefExpr) {
8117 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8118 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008119 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008120 continue;
8121 }
8122
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008123 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008124 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008125 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008126 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008127 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8128 ? RefExpr->IgnoreParens()
8129 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008130 }
8131
Alexey Bataeved09d242014-05-28 05:53:51 +00008132 if (Vars.empty())
8133 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008134
8135 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8136}
8137
Alexey Bataevc5e02582014-06-16 07:08:35 +00008138namespace {
8139class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8140 DSAStackTy *Stack;
8141
8142public:
8143 bool VisitDeclRefExpr(DeclRefExpr *E) {
8144 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008145 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008146 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8147 return false;
8148 if (DVar.CKind != OMPC_unknown)
8149 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008150 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8151 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8152 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008153 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008154 return true;
8155 return false;
8156 }
8157 return false;
8158 }
8159 bool VisitStmt(Stmt *S) {
8160 for (auto Child : S->children()) {
8161 if (Child && Visit(Child))
8162 return true;
8163 }
8164 return false;
8165 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008166 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008167};
Alexey Bataev23b69422014-06-18 07:08:49 +00008168} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008169
Alexey Bataev60da77e2016-02-29 05:54:20 +00008170namespace {
8171// Transform MemberExpression for specified FieldDecl of current class to
8172// DeclRefExpr to specified OMPCapturedExprDecl.
8173class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8174 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8175 ValueDecl *Field;
8176 DeclRefExpr *CapturedExpr;
8177
8178public:
8179 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8180 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8181
8182 ExprResult TransformMemberExpr(MemberExpr *E) {
8183 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8184 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008185 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008186 return CapturedExpr;
8187 }
8188 return BaseTransform::TransformMemberExpr(E);
8189 }
8190 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8191};
8192} // namespace
8193
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008194template <typename T>
8195static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8196 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8197 for (auto &Set : Lookups) {
8198 for (auto *D : Set) {
8199 if (auto Res = Gen(cast<ValueDecl>(D)))
8200 return Res;
8201 }
8202 }
8203 return T();
8204}
8205
8206static ExprResult
8207buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8208 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8209 const DeclarationNameInfo &ReductionId, QualType Ty,
8210 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8211 if (ReductionIdScopeSpec.isInvalid())
8212 return ExprError();
8213 SmallVector<UnresolvedSet<8>, 4> Lookups;
8214 if (S) {
8215 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8216 Lookup.suppressDiagnostics();
8217 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8218 auto *D = Lookup.getRepresentativeDecl();
8219 do {
8220 S = S->getParent();
8221 } while (S && !S->isDeclScope(D));
8222 if (S)
8223 S = S->getParent();
8224 Lookups.push_back(UnresolvedSet<8>());
8225 Lookups.back().append(Lookup.begin(), Lookup.end());
8226 Lookup.clear();
8227 }
8228 } else if (auto *ULE =
8229 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8230 Lookups.push_back(UnresolvedSet<8>());
8231 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008232 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008233 if (D == PrevD)
8234 Lookups.push_back(UnresolvedSet<8>());
8235 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8236 Lookups.back().addDecl(DRD);
8237 PrevD = D;
8238 }
8239 }
8240 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8241 Ty->containsUnexpandedParameterPack() ||
8242 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8243 return !D->isInvalidDecl() &&
8244 (D->getType()->isDependentType() ||
8245 D->getType()->isInstantiationDependentType() ||
8246 D->getType()->containsUnexpandedParameterPack());
8247 })) {
8248 UnresolvedSet<8> ResSet;
8249 for (auto &Set : Lookups) {
8250 ResSet.append(Set.begin(), Set.end());
8251 // The last item marks the end of all declarations at the specified scope.
8252 ResSet.addDecl(Set[Set.size() - 1]);
8253 }
8254 return UnresolvedLookupExpr::Create(
8255 SemaRef.Context, /*NamingClass=*/nullptr,
8256 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8257 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8258 }
8259 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8260 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8261 if (!D->isInvalidDecl() &&
8262 SemaRef.Context.hasSameType(D->getType(), Ty))
8263 return D;
8264 return nullptr;
8265 }))
8266 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8267 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8268 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8269 if (!D->isInvalidDecl() &&
8270 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8271 !Ty.isMoreQualifiedThan(D->getType()))
8272 return D;
8273 return nullptr;
8274 })) {
8275 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8276 /*DetectVirtual=*/false);
8277 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8278 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8279 VD->getType().getUnqualifiedType()))) {
8280 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8281 /*DiagID=*/0) !=
8282 Sema::AR_inaccessible) {
8283 SemaRef.BuildBasePathArray(Paths, BasePath);
8284 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8285 }
8286 }
8287 }
8288 }
8289 if (ReductionIdScopeSpec.isSet()) {
8290 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8291 return ExprError();
8292 }
8293 return ExprEmpty();
8294}
8295
Alexey Bataevc5e02582014-06-16 07:08:35 +00008296OMPClause *Sema::ActOnOpenMPReductionClause(
8297 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8298 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008299 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8300 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008301 auto DN = ReductionId.getName();
8302 auto OOK = DN.getCXXOverloadedOperator();
8303 BinaryOperatorKind BOK = BO_Comma;
8304
8305 // OpenMP [2.14.3.6, reduction clause]
8306 // C
8307 // reduction-identifier is either an identifier or one of the following
8308 // operators: +, -, *, &, |, ^, && and ||
8309 // C++
8310 // reduction-identifier is either an id-expression or one of the following
8311 // operators: +, -, *, &, |, ^, && and ||
8312 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8313 switch (OOK) {
8314 case OO_Plus:
8315 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008316 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008317 break;
8318 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008319 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008320 break;
8321 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008322 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008323 break;
8324 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008325 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008326 break;
8327 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008328 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008329 break;
8330 case OO_AmpAmp:
8331 BOK = BO_LAnd;
8332 break;
8333 case OO_PipePipe:
8334 BOK = BO_LOr;
8335 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008336 case OO_New:
8337 case OO_Delete:
8338 case OO_Array_New:
8339 case OO_Array_Delete:
8340 case OO_Slash:
8341 case OO_Percent:
8342 case OO_Tilde:
8343 case OO_Exclaim:
8344 case OO_Equal:
8345 case OO_Less:
8346 case OO_Greater:
8347 case OO_LessEqual:
8348 case OO_GreaterEqual:
8349 case OO_PlusEqual:
8350 case OO_MinusEqual:
8351 case OO_StarEqual:
8352 case OO_SlashEqual:
8353 case OO_PercentEqual:
8354 case OO_CaretEqual:
8355 case OO_AmpEqual:
8356 case OO_PipeEqual:
8357 case OO_LessLess:
8358 case OO_GreaterGreater:
8359 case OO_LessLessEqual:
8360 case OO_GreaterGreaterEqual:
8361 case OO_EqualEqual:
8362 case OO_ExclaimEqual:
8363 case OO_PlusPlus:
8364 case OO_MinusMinus:
8365 case OO_Comma:
8366 case OO_ArrowStar:
8367 case OO_Arrow:
8368 case OO_Call:
8369 case OO_Subscript:
8370 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008371 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008372 case NUM_OVERLOADED_OPERATORS:
8373 llvm_unreachable("Unexpected reduction identifier");
8374 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008375 if (auto II = DN.getAsIdentifierInfo()) {
8376 if (II->isStr("max"))
8377 BOK = BO_GT;
8378 else if (II->isStr("min"))
8379 BOK = BO_LT;
8380 }
8381 break;
8382 }
8383 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008384 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008385 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008386 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008387
8388 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008389 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008390 SmallVector<Expr *, 8> LHSs;
8391 SmallVector<Expr *, 8> RHSs;
8392 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008393 SmallVector<Decl *, 4> ExprCaptures;
8394 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008395 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8396 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008397 for (auto RefExpr : VarList) {
8398 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008399 // OpenMP [2.1, C/C++]
8400 // A list item is a variable or array section, subject to the restrictions
8401 // specified in Section 2.4 on page 42 and in each of the sections
8402 // describing clauses and directives for which a list appears.
8403 // OpenMP [2.14.3.3, Restrictions, p.1]
8404 // A variable that is part of another variable (as an array or
8405 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008406 if (!FirstIter && IR != ER)
8407 ++IR;
8408 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008409 SourceLocation ELoc;
8410 SourceRange ERange;
8411 Expr *SimpleRefExpr = RefExpr;
8412 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8413 /*AllowArraySection=*/true);
8414 if (Res.second) {
8415 // It will be analyzed later.
8416 Vars.push_back(RefExpr);
8417 Privates.push_back(nullptr);
8418 LHSs.push_back(nullptr);
8419 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008420 // Try to find 'declare reduction' corresponding construct before using
8421 // builtin/overloaded operators.
8422 QualType Type = Context.DependentTy;
8423 CXXCastPath BasePath;
8424 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8425 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8426 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8427 if (CurContext->isDependentContext() &&
8428 (DeclareReductionRef.isUnset() ||
8429 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8430 ReductionOps.push_back(DeclareReductionRef.get());
8431 else
8432 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008433 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008434 ValueDecl *D = Res.first;
8435 if (!D)
8436 continue;
8437
Alexey Bataeva1764212015-09-30 09:22:36 +00008438 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008439 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8440 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8441 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008442 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008443 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008444 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8445 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8446 Type = ATy->getElementType();
8447 else
8448 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008449 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008450 } else
8451 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8452 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008453
Alexey Bataevc5e02582014-06-16 07:08:35 +00008454 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8455 // A variable that appears in a private clause must not have an incomplete
8456 // type or a reference type.
8457 if (RequireCompleteType(ELoc, Type,
8458 diag::err_omp_reduction_incomplete_type))
8459 continue;
8460 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008461 // A list item that appears in a reduction clause must not be
8462 // const-qualified.
8463 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008464 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008465 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008466 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008467 bool IsDecl = !VD ||
8468 VD->isThisDeclarationADefinition(Context) ==
8469 VarDecl::DeclarationOnly;
8470 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008471 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008472 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008473 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008474 continue;
8475 }
8476 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8477 // If a list-item is a reference type then it must bind to the same object
8478 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008479 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008480 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008481 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008482 DSARefChecker Check(DSAStack);
8483 if (Check.Visit(VDDef->getInit())) {
8484 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8485 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8486 continue;
8487 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008488 }
8489 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008490
Alexey Bataevc5e02582014-06-16 07:08:35 +00008491 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8492 // in a Construct]
8493 // Variables with the predetermined data-sharing attributes may not be
8494 // listed in data-sharing attributes clauses, except for the cases
8495 // listed below. For these exceptions only, listing a predetermined
8496 // variable in a data-sharing attribute clause is allowed and overrides
8497 // the variable's predetermined data-sharing attributes.
8498 // OpenMP [2.14.3.6, Restrictions, p.3]
8499 // Any number of reduction clauses can be specified on the directive,
8500 // but a list item can appear only once in the reduction clauses for that
8501 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008502 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008503 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008504 if (DVar.CKind == OMPC_reduction) {
8505 Diag(ELoc, diag::err_omp_once_referenced)
8506 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008507 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008508 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008509 } else if (DVar.CKind != OMPC_unknown) {
8510 Diag(ELoc, diag::err_omp_wrong_dsa)
8511 << getOpenMPClauseName(DVar.CKind)
8512 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008513 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008514 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008515 }
8516
8517 // OpenMP [2.14.3.6, Restrictions, p.1]
8518 // A list item that appears in a reduction clause of a worksharing
8519 // construct must be shared in the parallel regions to which any of the
8520 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008521 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8522 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008523 !isOpenMPParallelDirective(CurrDir) &&
8524 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008525 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008526 if (DVar.CKind != OMPC_shared) {
8527 Diag(ELoc, diag::err_omp_required_access)
8528 << getOpenMPClauseName(OMPC_reduction)
8529 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008530 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008531 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008532 }
8533 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008534
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008535 // Try to find 'declare reduction' corresponding construct before using
8536 // builtin/overloaded operators.
8537 CXXCastPath BasePath;
8538 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8539 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8540 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8541 if (DeclareReductionRef.isInvalid())
8542 continue;
8543 if (CurContext->isDependentContext() &&
8544 (DeclareReductionRef.isUnset() ||
8545 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8546 Vars.push_back(RefExpr);
8547 Privates.push_back(nullptr);
8548 LHSs.push_back(nullptr);
8549 RHSs.push_back(nullptr);
8550 ReductionOps.push_back(DeclareReductionRef.get());
8551 continue;
8552 }
8553 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8554 // Not allowed reduction identifier is found.
8555 Diag(ReductionId.getLocStart(),
8556 diag::err_omp_unknown_reduction_identifier)
8557 << Type << ReductionIdRange;
8558 continue;
8559 }
8560
8561 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8562 // The type of a list item that appears in a reduction clause must be valid
8563 // for the reduction-identifier. For a max or min reduction in C, the type
8564 // of the list item must be an allowed arithmetic data type: char, int,
8565 // float, double, or _Bool, possibly modified with long, short, signed, or
8566 // unsigned. For a max or min reduction in C++, the type of the list item
8567 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8568 // double, or bool, possibly modified with long, short, signed, or unsigned.
8569 if (DeclareReductionRef.isUnset()) {
8570 if ((BOK == BO_GT || BOK == BO_LT) &&
8571 !(Type->isScalarType() ||
8572 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8573 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8574 << getLangOpts().CPlusPlus;
8575 if (!ASE && !OASE) {
8576 bool IsDecl = !VD ||
8577 VD->isThisDeclarationADefinition(Context) ==
8578 VarDecl::DeclarationOnly;
8579 Diag(D->getLocation(),
8580 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8581 << D;
8582 }
8583 continue;
8584 }
8585 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8586 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8587 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8588 if (!ASE && !OASE) {
8589 bool IsDecl = !VD ||
8590 VD->isThisDeclarationADefinition(Context) ==
8591 VarDecl::DeclarationOnly;
8592 Diag(D->getLocation(),
8593 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8594 << D;
8595 }
8596 continue;
8597 }
8598 }
8599
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008600 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008601 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008602 D->hasAttrs() ? &D->getAttrs() : nullptr);
8603 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8604 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008605 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008606 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008607 (!ASE &&
8608 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008609 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008610 // Create pseudo array type for private copy. The size for this array will
8611 // be generated during codegen.
8612 // For array subscripts or single variables Private Ty is the same as Type
8613 // (type of the variable or single array element).
8614 PrivateTy = Context.getVariableArrayType(
8615 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8616 Context.getSizeType(), VK_RValue),
8617 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008618 } else if (!ASE && !OASE &&
8619 Context.getAsArrayType(D->getType().getNonReferenceType()))
8620 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008621 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008622 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8623 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008624 // Add initializer for private variable.
8625 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008626 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8627 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8628 if (DeclareReductionRef.isUsable()) {
8629 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8630 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8631 if (DRD->getInitializer()) {
8632 Init = DRDRef;
8633 RHSVD->setInit(DRDRef);
8634 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008635 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008636 } else {
8637 switch (BOK) {
8638 case BO_Add:
8639 case BO_Xor:
8640 case BO_Or:
8641 case BO_LOr:
8642 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8643 if (Type->isScalarType() || Type->isAnyComplexType())
8644 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8645 break;
8646 case BO_Mul:
8647 case BO_LAnd:
8648 if (Type->isScalarType() || Type->isAnyComplexType()) {
8649 // '*' and '&&' reduction ops - initializer is '1'.
8650 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008651 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008652 break;
8653 case BO_And: {
8654 // '&' reduction op - initializer is '~0'.
8655 QualType OrigType = Type;
8656 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8657 Type = ComplexTy->getElementType();
8658 if (Type->isRealFloatingType()) {
8659 llvm::APFloat InitValue =
8660 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8661 /*isIEEE=*/true);
8662 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8663 Type, ELoc);
8664 } else if (Type->isScalarType()) {
8665 auto Size = Context.getTypeSize(Type);
8666 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8667 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8668 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8669 }
8670 if (Init && OrigType->isAnyComplexType()) {
8671 // Init = 0xFFFF + 0xFFFFi;
8672 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8673 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8674 }
8675 Type = OrigType;
8676 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008677 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008678 case BO_LT:
8679 case BO_GT: {
8680 // 'min' reduction op - initializer is 'Largest representable number in
8681 // the reduction list item type'.
8682 // 'max' reduction op - initializer is 'Least representable number in
8683 // the reduction list item type'.
8684 if (Type->isIntegerType() || Type->isPointerType()) {
8685 bool IsSigned = Type->hasSignedIntegerRepresentation();
8686 auto Size = Context.getTypeSize(Type);
8687 QualType IntTy =
8688 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8689 llvm::APInt InitValue =
8690 (BOK != BO_LT)
8691 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8692 : llvm::APInt::getMinValue(Size)
8693 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8694 : llvm::APInt::getMaxValue(Size);
8695 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8696 if (Type->isPointerType()) {
8697 // Cast to pointer type.
8698 auto CastExpr = BuildCStyleCastExpr(
8699 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8700 SourceLocation(), Init);
8701 if (CastExpr.isInvalid())
8702 continue;
8703 Init = CastExpr.get();
8704 }
8705 } else if (Type->isRealFloatingType()) {
8706 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8707 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8708 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8709 Type, ELoc);
8710 }
8711 break;
8712 }
8713 case BO_PtrMemD:
8714 case BO_PtrMemI:
8715 case BO_MulAssign:
8716 case BO_Div:
8717 case BO_Rem:
8718 case BO_Sub:
8719 case BO_Shl:
8720 case BO_Shr:
8721 case BO_LE:
8722 case BO_GE:
8723 case BO_EQ:
8724 case BO_NE:
8725 case BO_AndAssign:
8726 case BO_XorAssign:
8727 case BO_OrAssign:
8728 case BO_Assign:
8729 case BO_AddAssign:
8730 case BO_SubAssign:
8731 case BO_DivAssign:
8732 case BO_RemAssign:
8733 case BO_ShlAssign:
8734 case BO_ShrAssign:
8735 case BO_Comma:
8736 llvm_unreachable("Unexpected reduction operation");
8737 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008738 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008739 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00008740 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008741 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00008742 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008743 if (RHSVD->isInvalidDecl())
8744 continue;
8745 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008746 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8747 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008748 bool IsDecl =
8749 !VD ||
8750 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8751 Diag(D->getLocation(),
8752 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8753 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008754 continue;
8755 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008756 // Store initializer for single element in private copy. Will be used during
8757 // codegen.
8758 PrivateVD->setInit(RHSVD->getInit());
8759 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008760 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008761 ExprResult ReductionOp;
8762 if (DeclareReductionRef.isUsable()) {
8763 QualType RedTy = DeclareReductionRef.get()->getType();
8764 QualType PtrRedTy = Context.getPointerType(RedTy);
8765 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8766 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8767 if (!BasePath.empty()) {
8768 LHS = DefaultLvalueConversion(LHS.get());
8769 RHS = DefaultLvalueConversion(RHS.get());
8770 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8771 CK_UncheckedDerivedToBase, LHS.get(),
8772 &BasePath, LHS.get()->getValueKind());
8773 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8774 CK_UncheckedDerivedToBase, RHS.get(),
8775 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008776 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008777 FunctionProtoType::ExtProtoInfo EPI;
8778 QualType Params[] = {PtrRedTy, PtrRedTy};
8779 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8780 auto *OVE = new (Context) OpaqueValueExpr(
8781 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8782 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8783 Expr *Args[] = {LHS.get(), RHS.get()};
8784 ReductionOp = new (Context)
8785 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8786 } else {
8787 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8788 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8789 if (ReductionOp.isUsable()) {
8790 if (BOK != BO_LT && BOK != BO_GT) {
8791 ReductionOp =
8792 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8793 BO_Assign, LHSDRE, ReductionOp.get());
8794 } else {
8795 auto *ConditionalOp = new (Context) ConditionalOperator(
8796 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8797 RHSDRE, Type, VK_LValue, OK_Ordinary);
8798 ReductionOp =
8799 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8800 BO_Assign, LHSDRE, ConditionalOp);
8801 }
8802 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8803 }
8804 if (ReductionOp.isInvalid())
8805 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008806 }
8807
Alexey Bataev60da77e2016-02-29 05:54:20 +00008808 DeclRefExpr *Ref = nullptr;
8809 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008810 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008811 if (ASE || OASE) {
8812 TransformExprToCaptures RebuildToCapture(*this, D);
8813 VarsExpr =
8814 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8815 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008816 } else {
8817 VarsExpr = Ref =
8818 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008819 }
8820 if (!IsOpenMPCapturedDecl(D)) {
8821 ExprCaptures.push_back(Ref->getDecl());
8822 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8823 ExprResult RefRes = DefaultLvalueConversion(Ref);
8824 if (!RefRes.isUsable())
8825 continue;
8826 ExprResult PostUpdateRes =
8827 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8828 SimpleRefExpr, RefRes.get());
8829 if (!PostUpdateRes.isUsable())
8830 continue;
8831 ExprPostUpdates.push_back(
8832 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008833 }
8834 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008835 }
8836 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8837 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008838 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008839 LHSs.push_back(LHSDRE);
8840 RHSs.push_back(RHSDRE);
8841 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008842 }
8843
8844 if (Vars.empty())
8845 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008846
Alexey Bataevc5e02582014-06-16 07:08:35 +00008847 return OMPReductionClause::Create(
8848 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008849 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008850 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8851 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008852}
8853
Alexey Bataevecba70f2016-04-12 11:02:11 +00008854bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8855 SourceLocation LinLoc) {
8856 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8857 LinKind == OMPC_LINEAR_unknown) {
8858 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8859 return true;
8860 }
8861 return false;
8862}
8863
8864bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8865 OpenMPLinearClauseKind LinKind,
8866 QualType Type) {
8867 auto *VD = dyn_cast_or_null<VarDecl>(D);
8868 // A variable must not have an incomplete type or a reference type.
8869 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8870 return true;
8871 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8872 !Type->isReferenceType()) {
8873 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8874 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8875 return true;
8876 }
8877 Type = Type.getNonReferenceType();
8878
8879 // A list item must not be const-qualified.
8880 if (Type.isConstant(Context)) {
8881 Diag(ELoc, diag::err_omp_const_variable)
8882 << getOpenMPClauseName(OMPC_linear);
8883 if (D) {
8884 bool IsDecl =
8885 !VD ||
8886 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8887 Diag(D->getLocation(),
8888 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8889 << D;
8890 }
8891 return true;
8892 }
8893
8894 // A list item must be of integral or pointer type.
8895 Type = Type.getUnqualifiedType().getCanonicalType();
8896 const auto *Ty = Type.getTypePtrOrNull();
8897 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8898 !Ty->isPointerType())) {
8899 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8900 if (D) {
8901 bool IsDecl =
8902 !VD ||
8903 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8904 Diag(D->getLocation(),
8905 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8906 << D;
8907 }
8908 return true;
8909 }
8910 return false;
8911}
8912
Alexey Bataev182227b2015-08-20 10:54:39 +00008913OMPClause *Sema::ActOnOpenMPLinearClause(
8914 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8915 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8916 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008917 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008918 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008919 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008920 SmallVector<Decl *, 4> ExprCaptures;
8921 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008922 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008923 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008924 for (auto &RefExpr : VarList) {
8925 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008926 SourceLocation ELoc;
8927 SourceRange ERange;
8928 Expr *SimpleRefExpr = RefExpr;
8929 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8930 /*AllowArraySection=*/false);
8931 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008932 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008933 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008934 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008935 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008936 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008937 ValueDecl *D = Res.first;
8938 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008939 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008940
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008941 QualType Type = D->getType();
8942 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008943
8944 // OpenMP [2.14.3.7, linear clause]
8945 // A list-item cannot appear in more than one linear clause.
8946 // A list-item that appears in a linear clause cannot appear in any
8947 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008948 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008949 if (DVar.RefExpr) {
8950 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8951 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008952 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008953 continue;
8954 }
8955
Alexey Bataevecba70f2016-04-12 11:02:11 +00008956 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008957 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008958 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008959
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008960 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008961 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8962 D->hasAttrs() ? &D->getAttrs() : nullptr);
8963 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008964 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008965 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008966 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008967 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008968 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008969 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8970 if (!IsOpenMPCapturedDecl(D)) {
8971 ExprCaptures.push_back(Ref->getDecl());
8972 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8973 ExprResult RefRes = DefaultLvalueConversion(Ref);
8974 if (!RefRes.isUsable())
8975 continue;
8976 ExprResult PostUpdateRes =
8977 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8978 SimpleRefExpr, RefRes.get());
8979 if (!PostUpdateRes.isUsable())
8980 continue;
8981 ExprPostUpdates.push_back(
8982 IgnoredValueConversions(PostUpdateRes.get()).get());
8983 }
8984 }
8985 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008986 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008987 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008988 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008989 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008990 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008991 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008992 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8993
8994 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008995 Vars.push_back((VD || CurContext->isDependentContext())
8996 ? RefExpr->IgnoreParens()
8997 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008998 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008999 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009000 }
9001
9002 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009003 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009004
9005 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009006 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009007 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9008 !Step->isInstantiationDependent() &&
9009 !Step->containsUnexpandedParameterPack()) {
9010 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009011 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009012 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009013 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009014 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009015
Alexander Musman3276a272015-03-21 10:12:56 +00009016 // Build var to save the step value.
9017 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009018 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009019 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009020 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009021 ExprResult CalcStep =
9022 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009023 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009024
Alexander Musman8dba6642014-04-22 13:09:42 +00009025 // Warn about zero linear step (it would be probably better specified as
9026 // making corresponding variables 'const').
9027 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009028 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9029 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009030 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9031 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009032 if (!IsConstant && CalcStep.isUsable()) {
9033 // Calculate the step beforehand instead of doing this on each iteration.
9034 // (This is not used if the number of iterations may be kfold-ed).
9035 CalcStepExpr = CalcStep.get();
9036 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009037 }
9038
Alexey Bataev182227b2015-08-20 10:54:39 +00009039 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9040 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009041 StepExpr, CalcStepExpr,
9042 buildPreInits(Context, ExprCaptures),
9043 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009044}
9045
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009046static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9047 Expr *NumIterations, Sema &SemaRef,
9048 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009049 // Walk the vars and build update/final expressions for the CodeGen.
9050 SmallVector<Expr *, 8> Updates;
9051 SmallVector<Expr *, 8> Finals;
9052 Expr *Step = Clause.getStep();
9053 Expr *CalcStep = Clause.getCalcStep();
9054 // OpenMP [2.14.3.7, linear clause]
9055 // If linear-step is not specified it is assumed to be 1.
9056 if (Step == nullptr)
9057 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009058 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009059 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009060 }
Alexander Musman3276a272015-03-21 10:12:56 +00009061 bool HasErrors = false;
9062 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009063 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009064 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009065 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009066 SourceLocation ELoc;
9067 SourceRange ERange;
9068 Expr *SimpleRefExpr = RefExpr;
9069 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9070 /*AllowArraySection=*/false);
9071 ValueDecl *D = Res.first;
9072 if (Res.second || !D) {
9073 Updates.push_back(nullptr);
9074 Finals.push_back(nullptr);
9075 HasErrors = true;
9076 continue;
9077 }
9078 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9079 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9080 ->getMemberDecl();
9081 }
9082 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009083 Expr *InitExpr = *CurInit;
9084
9085 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009086 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009087 Expr *CapturedRef;
9088 if (LinKind == OMPC_LINEAR_uval)
9089 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9090 else
9091 CapturedRef =
9092 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9093 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9094 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009095
9096 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009097 ExprResult Update;
9098 if (!Info.first) {
9099 Update =
9100 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9101 InitExpr, IV, Step, /* Subtract */ false);
9102 } else
9103 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009104 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9105 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009106
9107 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009108 ExprResult Final;
9109 if (!Info.first) {
9110 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9111 InitExpr, NumIterations, Step,
9112 /* Subtract */ false);
9113 } else
9114 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009115 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9116 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009117
Alexander Musman3276a272015-03-21 10:12:56 +00009118 if (!Update.isUsable() || !Final.isUsable()) {
9119 Updates.push_back(nullptr);
9120 Finals.push_back(nullptr);
9121 HasErrors = true;
9122 } else {
9123 Updates.push_back(Update.get());
9124 Finals.push_back(Final.get());
9125 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009126 ++CurInit;
9127 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009128 }
9129 Clause.setUpdates(Updates);
9130 Clause.setFinals(Finals);
9131 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009132}
9133
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009134OMPClause *Sema::ActOnOpenMPAlignedClause(
9135 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9136 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9137
9138 SmallVector<Expr *, 8> Vars;
9139 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009140 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9141 SourceLocation ELoc;
9142 SourceRange ERange;
9143 Expr *SimpleRefExpr = RefExpr;
9144 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9145 /*AllowArraySection=*/false);
9146 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009147 // It will be analyzed later.
9148 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009149 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009150 ValueDecl *D = Res.first;
9151 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009152 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009153
Alexey Bataev1efd1662016-03-29 10:59:56 +00009154 QualType QType = D->getType();
9155 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009156
9157 // OpenMP [2.8.1, simd construct, Restrictions]
9158 // The type of list items appearing in the aligned clause must be
9159 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009160 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009161 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009162 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009163 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009164 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009165 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009166 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009167 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009168 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009169 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009170 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009171 continue;
9172 }
9173
9174 // OpenMP [2.8.1, simd construct, Restrictions]
9175 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009176 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009177 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009178 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9179 << getOpenMPClauseName(OMPC_aligned);
9180 continue;
9181 }
9182
Alexey Bataev1efd1662016-03-29 10:59:56 +00009183 DeclRefExpr *Ref = nullptr;
9184 if (!VD && IsOpenMPCapturedDecl(D))
9185 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9186 Vars.push_back(DefaultFunctionArrayConversion(
9187 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9188 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009189 }
9190
9191 // OpenMP [2.8.1, simd construct, Description]
9192 // The parameter of the aligned clause, alignment, must be a constant
9193 // positive integer expression.
9194 // If no optional parameter is specified, implementation-defined default
9195 // alignments for SIMD instructions on the target platforms are assumed.
9196 if (Alignment != nullptr) {
9197 ExprResult AlignResult =
9198 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9199 if (AlignResult.isInvalid())
9200 return nullptr;
9201 Alignment = AlignResult.get();
9202 }
9203 if (Vars.empty())
9204 return nullptr;
9205
9206 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9207 EndLoc, Vars, Alignment);
9208}
9209
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009210OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9211 SourceLocation StartLoc,
9212 SourceLocation LParenLoc,
9213 SourceLocation EndLoc) {
9214 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009215 SmallVector<Expr *, 8> SrcExprs;
9216 SmallVector<Expr *, 8> DstExprs;
9217 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009218 for (auto &RefExpr : VarList) {
9219 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9220 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009221 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009222 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009223 SrcExprs.push_back(nullptr);
9224 DstExprs.push_back(nullptr);
9225 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009226 continue;
9227 }
9228
Alexey Bataeved09d242014-05-28 05:53:51 +00009229 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009230 // OpenMP [2.1, C/C++]
9231 // A list item is a variable name.
9232 // OpenMP [2.14.4.1, Restrictions, p.1]
9233 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009234 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009235 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009236 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9237 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009238 continue;
9239 }
9240
9241 Decl *D = DE->getDecl();
9242 VarDecl *VD = cast<VarDecl>(D);
9243
9244 QualType Type = VD->getType();
9245 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9246 // It will be analyzed later.
9247 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009248 SrcExprs.push_back(nullptr);
9249 DstExprs.push_back(nullptr);
9250 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009251 continue;
9252 }
9253
9254 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9255 // A list item that appears in a copyin clause must be threadprivate.
9256 if (!DSAStack->isThreadPrivate(VD)) {
9257 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009258 << getOpenMPClauseName(OMPC_copyin)
9259 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009260 continue;
9261 }
9262
9263 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9264 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009265 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009266 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009267 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009268 auto *SrcVD =
9269 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9270 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009271 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009272 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9273 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009274 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9275 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009276 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009277 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009278 // For arrays generate assignment operation for single element and replace
9279 // it by the original array element in CodeGen.
9280 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9281 PseudoDstExpr, PseudoSrcExpr);
9282 if (AssignmentOp.isInvalid())
9283 continue;
9284 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9285 /*DiscardedValue=*/true);
9286 if (AssignmentOp.isInvalid())
9287 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009288
9289 DSAStack->addDSA(VD, DE, OMPC_copyin);
9290 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009291 SrcExprs.push_back(PseudoSrcExpr);
9292 DstExprs.push_back(PseudoDstExpr);
9293 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009294 }
9295
Alexey Bataeved09d242014-05-28 05:53:51 +00009296 if (Vars.empty())
9297 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009298
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009299 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9300 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009301}
9302
Alexey Bataevbae9a792014-06-27 10:37:06 +00009303OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9304 SourceLocation StartLoc,
9305 SourceLocation LParenLoc,
9306 SourceLocation EndLoc) {
9307 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009308 SmallVector<Expr *, 8> SrcExprs;
9309 SmallVector<Expr *, 8> DstExprs;
9310 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009311 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009312 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9313 SourceLocation ELoc;
9314 SourceRange ERange;
9315 Expr *SimpleRefExpr = RefExpr;
9316 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9317 /*AllowArraySection=*/false);
9318 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009319 // It will be analyzed later.
9320 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009321 SrcExprs.push_back(nullptr);
9322 DstExprs.push_back(nullptr);
9323 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009324 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009325 ValueDecl *D = Res.first;
9326 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009327 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009328
Alexey Bataeve122da12016-03-17 10:50:17 +00009329 QualType Type = D->getType();
9330 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009331
9332 // OpenMP [2.14.4.2, Restrictions, p.2]
9333 // A list item that appears in a copyprivate clause may not appear in a
9334 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009335 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9336 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009337 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9338 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009339 Diag(ELoc, diag::err_omp_wrong_dsa)
9340 << getOpenMPClauseName(DVar.CKind)
9341 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009342 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009343 continue;
9344 }
9345
9346 // OpenMP [2.11.4.2, Restrictions, p.1]
9347 // All list items that appear in a copyprivate clause must be either
9348 // threadprivate or private in the enclosing context.
9349 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009350 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009351 if (DVar.CKind == OMPC_shared) {
9352 Diag(ELoc, diag::err_omp_required_access)
9353 << getOpenMPClauseName(OMPC_copyprivate)
9354 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009355 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009356 continue;
9357 }
9358 }
9359 }
9360
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009361 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009362 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009363 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009364 << getOpenMPClauseName(OMPC_copyprivate) << Type
9365 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009366 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009367 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009368 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009369 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009370 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009371 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009372 continue;
9373 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009374
Alexey Bataevbae9a792014-06-27 10:37:06 +00009375 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9376 // A variable of class type (or array thereof) that appears in a
9377 // copyin clause requires an accessible, unambiguous copy assignment
9378 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009379 Type = Context.getBaseElementType(Type.getNonReferenceType())
9380 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009381 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009382 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9383 D->hasAttrs() ? &D->getAttrs() : nullptr);
9384 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009385 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009386 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9387 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009388 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009389 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009390 PseudoDstExpr, PseudoSrcExpr);
9391 if (AssignmentOp.isInvalid())
9392 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009393 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009394 /*DiscardedValue=*/true);
9395 if (AssignmentOp.isInvalid())
9396 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009397
9398 // No need to mark vars as copyprivate, they are already threadprivate or
9399 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009400 assert(VD || IsOpenMPCapturedDecl(D));
9401 Vars.push_back(
9402 VD ? RefExpr->IgnoreParens()
9403 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009404 SrcExprs.push_back(PseudoSrcExpr);
9405 DstExprs.push_back(PseudoDstExpr);
9406 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009407 }
9408
9409 if (Vars.empty())
9410 return nullptr;
9411
Alexey Bataeva63048e2015-03-23 06:18:07 +00009412 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9413 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009414}
9415
Alexey Bataev6125da92014-07-21 11:26:11 +00009416OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9417 SourceLocation StartLoc,
9418 SourceLocation LParenLoc,
9419 SourceLocation EndLoc) {
9420 if (VarList.empty())
9421 return nullptr;
9422
9423 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9424}
Alexey Bataevdea47612014-07-23 07:46:59 +00009425
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009426OMPClause *
9427Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9428 SourceLocation DepLoc, SourceLocation ColonLoc,
9429 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9430 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009431 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009432 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009433 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009434 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009435 return nullptr;
9436 }
9437 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009438 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9439 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009440 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009441 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009442 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9443 /*Last=*/OMPC_DEPEND_unknown, Except)
9444 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009445 return nullptr;
9446 }
9447 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009448 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009449 llvm::APSInt DepCounter(/*BitWidth=*/32);
9450 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9451 if (DepKind == OMPC_DEPEND_sink) {
9452 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9453 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9454 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009455 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009456 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009457 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9458 DSAStack->getParentOrderedRegionParam()) {
9459 for (auto &RefExpr : VarList) {
9460 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009461 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009462 // It will be analyzed later.
9463 Vars.push_back(RefExpr);
9464 continue;
9465 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009466
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009467 SourceLocation ELoc = RefExpr->getExprLoc();
9468 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9469 if (DepKind == OMPC_DEPEND_sink) {
9470 if (DepCounter >= TotalDepCount) {
9471 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9472 continue;
9473 }
9474 ++DepCounter;
9475 // OpenMP [2.13.9, Summary]
9476 // depend(dependence-type : vec), where dependence-type is:
9477 // 'sink' and where vec is the iteration vector, which has the form:
9478 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9479 // where n is the value specified by the ordered clause in the loop
9480 // directive, xi denotes the loop iteration variable of the i-th nested
9481 // loop associated with the loop directive, and di is a constant
9482 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009483 if (CurContext->isDependentContext()) {
9484 // It will be analyzed later.
9485 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009486 continue;
9487 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009488 SimpleExpr = SimpleExpr->IgnoreImplicit();
9489 OverloadedOperatorKind OOK = OO_None;
9490 SourceLocation OOLoc;
9491 Expr *LHS = SimpleExpr;
9492 Expr *RHS = nullptr;
9493 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9494 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9495 OOLoc = BO->getOperatorLoc();
9496 LHS = BO->getLHS()->IgnoreParenImpCasts();
9497 RHS = BO->getRHS()->IgnoreParenImpCasts();
9498 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9499 OOK = OCE->getOperator();
9500 OOLoc = OCE->getOperatorLoc();
9501 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9502 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9503 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9504 OOK = MCE->getMethodDecl()
9505 ->getNameInfo()
9506 .getName()
9507 .getCXXOverloadedOperator();
9508 OOLoc = MCE->getCallee()->getExprLoc();
9509 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9510 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9511 }
9512 SourceLocation ELoc;
9513 SourceRange ERange;
9514 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9515 /*AllowArraySection=*/false);
9516 if (Res.second) {
9517 // It will be analyzed later.
9518 Vars.push_back(RefExpr);
9519 }
9520 ValueDecl *D = Res.first;
9521 if (!D)
9522 continue;
9523
9524 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9525 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9526 continue;
9527 }
9528 if (RHS) {
9529 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9530 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9531 if (RHSRes.isInvalid())
9532 continue;
9533 }
9534 if (!CurContext->isDependentContext() &&
9535 DSAStack->getParentOrderedRegionParam() &&
9536 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9537 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9538 << DSAStack->getParentLoopControlVariable(
9539 DepCounter.getZExtValue());
9540 continue;
9541 }
9542 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009543 } else {
9544 // OpenMP [2.11.1.1, Restrictions, p.3]
9545 // A variable that is part of another variable (such as a field of a
9546 // structure) but is not an array element or an array section cannot
9547 // appear in a depend clause.
9548 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9549 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9550 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9551 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9552 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009553 (ASE &&
9554 !ASE->getBase()
9555 ->getType()
9556 .getNonReferenceType()
9557 ->isPointerType() &&
9558 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009559 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9560 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009561 continue;
9562 }
9563 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009564 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9565 }
9566
9567 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9568 TotalDepCount > VarList.size() &&
9569 DSAStack->getParentOrderedRegionParam()) {
9570 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9571 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9572 }
9573 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9574 Vars.empty())
9575 return nullptr;
9576 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009577 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9578 DepKind, DepLoc, ColonLoc, Vars);
9579 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9580 DSAStack->addDoacrossDependClause(C, OpsOffs);
9581 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009582}
Michael Wonge710d542015-08-07 16:16:36 +00009583
9584OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9585 SourceLocation LParenLoc,
9586 SourceLocation EndLoc) {
9587 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009588
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009589 // OpenMP [2.9.1, Restrictions]
9590 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009591 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9592 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009593 return nullptr;
9594
Michael Wonge710d542015-08-07 16:16:36 +00009595 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9596}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009597
9598static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9599 DSAStackTy *Stack, CXXRecordDecl *RD) {
9600 if (!RD || RD->isInvalidDecl())
9601 return true;
9602
9603 auto QTy = SemaRef.Context.getRecordType(RD);
9604 if (RD->isDynamicClass()) {
9605 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9606 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9607 return false;
9608 }
9609 auto *DC = RD;
9610 bool IsCorrect = true;
9611 for (auto *I : DC->decls()) {
9612 if (I) {
9613 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9614 if (MD->isStatic()) {
9615 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9616 SemaRef.Diag(MD->getLocation(),
9617 diag::note_omp_static_member_in_target);
9618 IsCorrect = false;
9619 }
9620 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9621 if (VD->isStaticDataMember()) {
9622 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9623 SemaRef.Diag(VD->getLocation(),
9624 diag::note_omp_static_member_in_target);
9625 IsCorrect = false;
9626 }
9627 }
9628 }
9629 }
9630
9631 for (auto &I : RD->bases()) {
9632 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9633 I.getType()->getAsCXXRecordDecl()))
9634 IsCorrect = false;
9635 }
9636 return IsCorrect;
9637}
9638
9639static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9640 DSAStackTy *Stack, QualType QTy) {
9641 NamedDecl *ND;
9642 if (QTy->isIncompleteType(&ND)) {
9643 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9644 return false;
9645 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009646 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009647 return false;
9648 }
9649 return true;
9650}
9651
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009652/// \brief Return true if it can be proven that the provided array expression
9653/// (array section or array subscript) does NOT specify the whole size of the
9654/// array whose base type is \a BaseQTy.
9655static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9656 const Expr *E,
9657 QualType BaseQTy) {
9658 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9659
9660 // If this is an array subscript, it refers to the whole size if the size of
9661 // the dimension is constant and equals 1. Also, an array section assumes the
9662 // format of an array subscript if no colon is used.
9663 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9664 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9665 return ATy->getSize().getSExtValue() != 1;
9666 // Size can't be evaluated statically.
9667 return false;
9668 }
9669
9670 assert(OASE && "Expecting array section if not an array subscript.");
9671 auto *LowerBound = OASE->getLowerBound();
9672 auto *Length = OASE->getLength();
9673
9674 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009675 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009676 if (LowerBound) {
9677 llvm::APSInt ConstLowerBound;
9678 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9679 return false; // Can't get the integer value as a constant.
9680 if (ConstLowerBound.getSExtValue())
9681 return true;
9682 }
9683
9684 // If we don't have a length we covering the whole dimension.
9685 if (!Length)
9686 return false;
9687
9688 // If the base is a pointer, we don't have a way to get the size of the
9689 // pointee.
9690 if (BaseQTy->isPointerType())
9691 return false;
9692
9693 // We can only check if the length is the same as the size of the dimension
9694 // if we have a constant array.
9695 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9696 if (!CATy)
9697 return false;
9698
9699 llvm::APSInt ConstLength;
9700 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9701 return false; // Can't get the integer value as a constant.
9702
9703 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9704}
9705
9706// Return true if it can be proven that the provided array expression (array
9707// section or array subscript) does NOT specify a single element of the array
9708// whose base type is \a BaseQTy.
9709static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009710 const Expr *E,
9711 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009712 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9713
9714 // An array subscript always refer to a single element. Also, an array section
9715 // assumes the format of an array subscript if no colon is used.
9716 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9717 return false;
9718
9719 assert(OASE && "Expecting array section if not an array subscript.");
9720 auto *Length = OASE->getLength();
9721
9722 // If we don't have a length we have to check if the array has unitary size
9723 // for this dimension. Also, we should always expect a length if the base type
9724 // is pointer.
9725 if (!Length) {
9726 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9727 return ATy->getSize().getSExtValue() != 1;
9728 // We cannot assume anything.
9729 return false;
9730 }
9731
9732 // Check if the length evaluates to 1.
9733 llvm::APSInt ConstLength;
9734 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9735 return false; // Can't get the integer value as a constant.
9736
9737 return ConstLength.getSExtValue() != 1;
9738}
9739
Samuel Antao661c0902016-05-26 17:39:58 +00009740// Return the expression of the base of the mappable expression or null if it
9741// cannot be determined and do all the necessary checks to see if the expression
9742// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009743// components of the expression.
9744static Expr *CheckMapClauseExpressionBase(
9745 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009746 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9747 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009748 SourceLocation ELoc = E->getExprLoc();
9749 SourceRange ERange = E->getSourceRange();
9750
9751 // The base of elements of list in a map clause have to be either:
9752 // - a reference to variable or field.
9753 // - a member expression.
9754 // - an array expression.
9755 //
9756 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9757 // reference to 'r'.
9758 //
9759 // If we have:
9760 //
9761 // struct SS {
9762 // Bla S;
9763 // foo() {
9764 // #pragma omp target map (S.Arr[:12]);
9765 // }
9766 // }
9767 //
9768 // We want to retrieve the member expression 'this->S';
9769
9770 Expr *RelevantExpr = nullptr;
9771
Samuel Antao5de996e2016-01-22 20:21:36 +00009772 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9773 // If a list item is an array section, it must specify contiguous storage.
9774 //
9775 // For this restriction it is sufficient that we make sure only references
9776 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009777 // exist except in the rightmost expression (unless they cover the whole
9778 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009779 //
9780 // r.ArrS[3:5].Arr[6:7]
9781 //
9782 // r.ArrS[3:5].x
9783 //
9784 // but these would be valid:
9785 // r.ArrS[3].Arr[6:7]
9786 //
9787 // r.ArrS[3].x
9788
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009789 bool AllowUnitySizeArraySection = true;
9790 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009791
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009792 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009793 E = E->IgnoreParenImpCasts();
9794
9795 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9796 if (!isa<VarDecl>(CurE->getDecl()))
9797 break;
9798
9799 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009800
9801 // If we got a reference to a declaration, we should not expect any array
9802 // section before that.
9803 AllowUnitySizeArraySection = false;
9804 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009805
9806 // Record the component.
9807 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9808 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009809 continue;
9810 }
9811
9812 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9813 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9814
9815 if (isa<CXXThisExpr>(BaseE))
9816 // We found a base expression: this->Val.
9817 RelevantExpr = CurE;
9818 else
9819 E = BaseE;
9820
9821 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9822 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9823 << CurE->getSourceRange();
9824 break;
9825 }
9826
9827 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9828
9829 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9830 // A bit-field cannot appear in a map clause.
9831 //
9832 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009833 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9834 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009835 break;
9836 }
9837
9838 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9839 // If the type of a list item is a reference to a type T then the type
9840 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009841 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009842
9843 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9844 // A list item cannot be a variable that is a member of a structure with
9845 // a union type.
9846 //
9847 if (auto *RT = CurType->getAs<RecordType>())
9848 if (RT->isUnionType()) {
9849 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9850 << CurE->getSourceRange();
9851 break;
9852 }
9853
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009854 // If we got a member expression, we should not expect any array section
9855 // before that:
9856 //
9857 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9858 // If a list item is an element of a structure, only the rightmost symbol
9859 // of the variable reference can be an array section.
9860 //
9861 AllowUnitySizeArraySection = false;
9862 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009863
9864 // Record the component.
9865 CurComponents.push_back(
9866 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009867 continue;
9868 }
9869
9870 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9871 E = CurE->getBase()->IgnoreParenImpCasts();
9872
9873 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9874 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9875 << 0 << CurE->getSourceRange();
9876 break;
9877 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009878
9879 // If we got an array subscript that express the whole dimension we
9880 // can have any array expressions before. If it only expressing part of
9881 // the dimension, we can only have unitary-size array expressions.
9882 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9883 E->getType()))
9884 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009885
9886 // Record the component - we don't have any declaration associated.
9887 CurComponents.push_back(
9888 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009889 continue;
9890 }
9891
9892 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009893 E = CurE->getBase()->IgnoreParenImpCasts();
9894
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009895 auto CurType =
9896 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9897
Samuel Antao5de996e2016-01-22 20:21:36 +00009898 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9899 // If the type of a list item is a reference to a type T then the type
9900 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009901 if (CurType->isReferenceType())
9902 CurType = CurType->getPointeeType();
9903
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009904 bool IsPointer = CurType->isAnyPointerType();
9905
9906 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009907 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9908 << 0 << CurE->getSourceRange();
9909 break;
9910 }
9911
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009912 bool NotWhole =
9913 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9914 bool NotUnity =
9915 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9916
Samuel Antaodab51bb2016-07-18 23:22:11 +00009917 if (AllowWholeSizeArraySection) {
9918 // Any array section is currently allowed. Allowing a whole size array
9919 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009920 //
9921 // If this array section refers to the whole dimension we can still
9922 // accept other array sections before this one, except if the base is a
9923 // pointer. Otherwise, only unitary sections are accepted.
9924 if (NotWhole || IsPointer)
9925 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009926 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009927 // A unity or whole array section is not allowed and that is not
9928 // compatible with the properties of the current array section.
9929 SemaRef.Diag(
9930 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9931 << CurE->getSourceRange();
9932 break;
9933 }
Samuel Antao90927002016-04-26 14:54:23 +00009934
9935 // Record the component - we don't have any declaration associated.
9936 CurComponents.push_back(
9937 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009938 continue;
9939 }
9940
9941 // If nothing else worked, this is not a valid map clause expression.
9942 SemaRef.Diag(ELoc,
9943 diag::err_omp_expected_named_var_member_or_array_expression)
9944 << ERange;
9945 break;
9946 }
9947
9948 return RelevantExpr;
9949}
9950
9951// Return true if expression E associated with value VD has conflicts with other
9952// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009953static bool CheckMapConflicts(
9954 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9955 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009956 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9957 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009958 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009959 SourceLocation ELoc = E->getExprLoc();
9960 SourceRange ERange = E->getSourceRange();
9961
9962 // In order to easily check the conflicts we need to match each component of
9963 // the expression under test with the components of the expressions that are
9964 // already in the stack.
9965
Samuel Antao5de996e2016-01-22 20:21:36 +00009966 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009967 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009968 "Map clause expression with unexpected base!");
9969
9970 // Variables to help detecting enclosing problems in data environment nests.
9971 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009972 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009973
Samuel Antao90927002016-04-26 14:54:23 +00009974 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9975 VD, CurrentRegionOnly,
9976 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009977 StackComponents,
9978 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009979
Samuel Antao5de996e2016-01-22 20:21:36 +00009980 assert(!StackComponents.empty() &&
9981 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009982 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009983 "Map clause expression with unexpected base!");
9984
Samuel Antao90927002016-04-26 14:54:23 +00009985 // The whole expression in the stack.
9986 auto *RE = StackComponents.front().getAssociatedExpression();
9987
Samuel Antao5de996e2016-01-22 20:21:36 +00009988 // Expressions must start from the same base. Here we detect at which
9989 // point both expressions diverge from each other and see if we can
9990 // detect if the memory referred to both expressions is contiguous and
9991 // do not overlap.
9992 auto CI = CurComponents.rbegin();
9993 auto CE = CurComponents.rend();
9994 auto SI = StackComponents.rbegin();
9995 auto SE = StackComponents.rend();
9996 for (; CI != CE && SI != SE; ++CI, ++SI) {
9997
9998 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9999 // At most one list item can be an array item derived from a given
10000 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010001 if (CurrentRegionOnly &&
10002 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10003 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10004 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10005 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10006 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010007 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010008 << CI->getAssociatedExpression()->getSourceRange();
10009 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10010 diag::note_used_here)
10011 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010012 return true;
10013 }
10014
10015 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010016 if (CI->getAssociatedExpression()->getStmtClass() !=
10017 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010018 break;
10019
10020 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010021 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010022 break;
10023 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010024 // Check if the extra components of the expressions in the enclosing
10025 // data environment are redundant for the current base declaration.
10026 // If they are, the maps completely overlap, which is legal.
10027 for (; SI != SE; ++SI) {
10028 QualType Type;
10029 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010030 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010031 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010032 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10033 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010034 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10035 Type =
10036 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10037 }
10038 if (Type.isNull() || Type->isAnyPointerType() ||
10039 CheckArrayExpressionDoesNotReferToWholeSize(
10040 SemaRef, SI->getAssociatedExpression(), Type))
10041 break;
10042 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010043
10044 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10045 // List items of map clauses in the same construct must not share
10046 // original storage.
10047 //
10048 // If the expressions are exactly the same or one is a subset of the
10049 // other, it means they are sharing storage.
10050 if (CI == CE && SI == SE) {
10051 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010052 if (CKind == OMPC_map)
10053 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10054 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010055 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010056 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10057 << ERange;
10058 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010059 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10060 << RE->getSourceRange();
10061 return true;
10062 } else {
10063 // If we find the same expression in the enclosing data environment,
10064 // that is legal.
10065 IsEnclosedByDataEnvironmentExpr = true;
10066 return false;
10067 }
10068 }
10069
Samuel Antao90927002016-04-26 14:54:23 +000010070 QualType DerivedType =
10071 std::prev(CI)->getAssociatedDeclaration()->getType();
10072 SourceLocation DerivedLoc =
10073 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010074
10075 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10076 // If the type of a list item is a reference to a type T then the type
10077 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010078 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010079
10080 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10081 // A variable for which the type is pointer and an array section
10082 // derived from that variable must not appear as list items of map
10083 // clauses of the same construct.
10084 //
10085 // Also, cover one of the cases in:
10086 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10087 // If any part of the original storage of a list item has corresponding
10088 // storage in the device data environment, all of the original storage
10089 // must have corresponding storage in the device data environment.
10090 //
10091 if (DerivedType->isAnyPointerType()) {
10092 if (CI == CE || SI == SE) {
10093 SemaRef.Diag(
10094 DerivedLoc,
10095 diag::err_omp_pointer_mapped_along_with_derived_section)
10096 << DerivedLoc;
10097 } else {
10098 assert(CI != CE && SI != SE);
10099 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10100 << DerivedLoc;
10101 }
10102 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10103 << RE->getSourceRange();
10104 return true;
10105 }
10106
10107 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10108 // List items of map clauses in the same construct must not share
10109 // original storage.
10110 //
10111 // An expression is a subset of the other.
10112 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010113 if (CKind == OMPC_map)
10114 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10115 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010116 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010117 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10118 << ERange;
10119 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010120 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10121 << RE->getSourceRange();
10122 return true;
10123 }
10124
10125 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010126 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010127 if (!CurrentRegionOnly && SI != SE)
10128 EnclosingExpr = RE;
10129
10130 // The current expression is a subset of the expression in the data
10131 // environment.
10132 IsEnclosedByDataEnvironmentExpr |=
10133 (!CurrentRegionOnly && CI != CE && SI == SE);
10134
10135 return false;
10136 });
10137
10138 if (CurrentRegionOnly)
10139 return FoundError;
10140
10141 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10142 // If any part of the original storage of a list item has corresponding
10143 // storage in the device data environment, all of the original storage must
10144 // have corresponding storage in the device data environment.
10145 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10146 // If a list item is an element of a structure, and a different element of
10147 // the structure has a corresponding list item in the device data environment
10148 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010149 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010150 // data environment prior to the task encountering the construct.
10151 //
10152 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10153 SemaRef.Diag(ELoc,
10154 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10155 << ERange;
10156 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10157 << EnclosingExpr->getSourceRange();
10158 return true;
10159 }
10160
10161 return FoundError;
10162}
10163
Samuel Antao661c0902016-05-26 17:39:58 +000010164namespace {
10165// Utility struct that gathers all the related lists associated with a mappable
10166// expression.
10167struct MappableVarListInfo final {
10168 // The list of expressions.
10169 ArrayRef<Expr *> VarList;
10170 // The list of processed expressions.
10171 SmallVector<Expr *, 16> ProcessedVarList;
10172 // The mappble components for each expression.
10173 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10174 // The base declaration of the variable.
10175 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10176
10177 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10178 // We have a list of components and base declarations for each entry in the
10179 // variable list.
10180 VarComponents.reserve(VarList.size());
10181 VarBaseDeclarations.reserve(VarList.size());
10182 }
10183};
10184}
10185
10186// Check the validity of the provided variable list for the provided clause kind
10187// \a CKind. In the check process the valid expressions, and mappable expression
10188// components and variables are extracted and used to fill \a Vars,
10189// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10190// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10191static void
10192checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10193 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10194 SourceLocation StartLoc,
10195 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10196 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010197 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10198 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010199 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010200
Samuel Antao90927002016-04-26 14:54:23 +000010201 // Keep track of the mappable components and base declarations in this clause.
10202 // Each entry in the list is going to have a list of components associated. We
10203 // record each set of the components so that we can build the clause later on.
10204 // In the end we should have the same amount of declarations and component
10205 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010206
Samuel Antao661c0902016-05-26 17:39:58 +000010207 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010208 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010209 SourceLocation ELoc = RE->getExprLoc();
10210
Kelvin Li0bff7af2015-11-23 05:32:03 +000010211 auto *VE = RE->IgnoreParenLValueCasts();
10212
10213 if (VE->isValueDependent() || VE->isTypeDependent() ||
10214 VE->isInstantiationDependent() ||
10215 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010216 // We can only analyze this information once the missing information is
10217 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010218 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010219 continue;
10220 }
10221
10222 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010223
Samuel Antao5de996e2016-01-22 20:21:36 +000010224 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010225 SemaRef.Diag(ELoc,
10226 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010227 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010228 continue;
10229 }
10230
Samuel Antao90927002016-04-26 14:54:23 +000010231 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10232 ValueDecl *CurDeclaration = nullptr;
10233
10234 // Obtain the array or member expression bases if required. Also, fill the
10235 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010236 auto *BE =
10237 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010238 if (!BE)
10239 continue;
10240
Samuel Antao90927002016-04-26 14:54:23 +000010241 assert(!CurComponents.empty() &&
10242 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010243
Samuel Antao90927002016-04-26 14:54:23 +000010244 // For the following checks, we rely on the base declaration which is
10245 // expected to be associated with the last component. The declaration is
10246 // expected to be a variable or a field (if 'this' is being mapped).
10247 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10248 assert(CurDeclaration && "Null decl on map clause.");
10249 assert(
10250 CurDeclaration->isCanonicalDecl() &&
10251 "Expecting components to have associated only canonical declarations.");
10252
10253 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10254 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010255
10256 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010257 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010258
10259 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010260 // threadprivate variables cannot appear in a map clause.
10261 // OpenMP 4.5 [2.10.5, target update Construct]
10262 // threadprivate variables cannot appear in a from clause.
10263 if (VD && DSAS->isThreadPrivate(VD)) {
10264 auto DVar = DSAS->getTopDSA(VD, false);
10265 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10266 << getOpenMPClauseName(CKind);
10267 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010268 continue;
10269 }
10270
Samuel Antao5de996e2016-01-22 20:21:36 +000010271 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10272 // A list item cannot appear in both a map clause and a data-sharing
10273 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010274
Samuel Antao5de996e2016-01-22 20:21:36 +000010275 // Check conflicts with other map clause expressions. We check the conflicts
10276 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010277 // environment, because the restrictions are different. We only have to
10278 // check conflicts across regions for the map clauses.
10279 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10280 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010281 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010282 if (CKind == OMPC_map &&
10283 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10284 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010285 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010286
Samuel Antao661c0902016-05-26 17:39:58 +000010287 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010288 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10289 // If the type of a list item is a reference to a type T then the type will
10290 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010291 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010292
Samuel Antao661c0902016-05-26 17:39:58 +000010293 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10294 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010295 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010296 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010297 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10298 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010299 continue;
10300
Samuel Antao661c0902016-05-26 17:39:58 +000010301 if (CKind == OMPC_map) {
10302 // target enter data
10303 // OpenMP [2.10.2, Restrictions, p. 99]
10304 // A map-type must be specified in all map clauses and must be either
10305 // to or alloc.
10306 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10307 if (DKind == OMPD_target_enter_data &&
10308 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10309 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10310 << (IsMapTypeImplicit ? 1 : 0)
10311 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10312 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010313 continue;
10314 }
Samuel Antao661c0902016-05-26 17:39:58 +000010315
10316 // target exit_data
10317 // OpenMP [2.10.3, Restrictions, p. 102]
10318 // A map-type must be specified in all map clauses and must be either
10319 // from, release, or delete.
10320 if (DKind == OMPD_target_exit_data &&
10321 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10322 MapType == OMPC_MAP_delete)) {
10323 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10324 << (IsMapTypeImplicit ? 1 : 0)
10325 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10326 << getOpenMPDirectiveName(DKind);
10327 continue;
10328 }
10329
10330 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10331 // A list item cannot appear in both a map clause and a data-sharing
10332 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010333 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010334 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010335 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010336 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10337 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010338 auto DVar = DSAS->getTopDSA(VD, false);
10339 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010340 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010341 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010342 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010343 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10344 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10345 continue;
10346 }
10347 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010348 }
10349
Samuel Antao90927002016-04-26 14:54:23 +000010350 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010351 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010352
10353 // Store the components in the stack so that they can be used to check
10354 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010355 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10356 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010357
10358 // Save the components and declaration to create the clause. For purposes of
10359 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010360 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010361 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10362 MVLI.VarComponents.back().append(CurComponents.begin(),
10363 CurComponents.end());
10364 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10365 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010366 }
Samuel Antao661c0902016-05-26 17:39:58 +000010367}
10368
10369OMPClause *
10370Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10371 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10372 SourceLocation MapLoc, SourceLocation ColonLoc,
10373 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10374 SourceLocation LParenLoc, SourceLocation EndLoc) {
10375 MappableVarListInfo MVLI(VarList);
10376 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10377 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010378
Samuel Antao5de996e2016-01-22 20:21:36 +000010379 // We need to produce a map clause even if we don't have variables so that
10380 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010381 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10382 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10383 MVLI.VarComponents, MapTypeModifier, MapType,
10384 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010385}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010386
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010387QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10388 TypeResult ParsedType) {
10389 assert(ParsedType.isUsable());
10390
10391 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10392 if (ReductionType.isNull())
10393 return QualType();
10394
10395 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10396 // A type name in a declare reduction directive cannot be a function type, an
10397 // array type, a reference type, or a type qualified with const, volatile or
10398 // restrict.
10399 if (ReductionType.hasQualifiers()) {
10400 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10401 return QualType();
10402 }
10403
10404 if (ReductionType->isFunctionType()) {
10405 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10406 return QualType();
10407 }
10408 if (ReductionType->isReferenceType()) {
10409 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10410 return QualType();
10411 }
10412 if (ReductionType->isArrayType()) {
10413 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10414 return QualType();
10415 }
10416 return ReductionType;
10417}
10418
10419Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10420 Scope *S, DeclContext *DC, DeclarationName Name,
10421 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10422 AccessSpecifier AS, Decl *PrevDeclInScope) {
10423 SmallVector<Decl *, 8> Decls;
10424 Decls.reserve(ReductionTypes.size());
10425
10426 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10427 ForRedeclaration);
10428 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10429 // A reduction-identifier may not be re-declared in the current scope for the
10430 // same type or for a type that is compatible according to the base language
10431 // rules.
10432 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10433 OMPDeclareReductionDecl *PrevDRD = nullptr;
10434 bool InCompoundScope = true;
10435 if (S != nullptr) {
10436 // Find previous declaration with the same name not referenced in other
10437 // declarations.
10438 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10439 InCompoundScope =
10440 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10441 LookupName(Lookup, S);
10442 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10443 /*AllowInlineNamespace=*/false);
10444 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10445 auto Filter = Lookup.makeFilter();
10446 while (Filter.hasNext()) {
10447 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10448 if (InCompoundScope) {
10449 auto I = UsedAsPrevious.find(PrevDecl);
10450 if (I == UsedAsPrevious.end())
10451 UsedAsPrevious[PrevDecl] = false;
10452 if (auto *D = PrevDecl->getPrevDeclInScope())
10453 UsedAsPrevious[D] = true;
10454 }
10455 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10456 PrevDecl->getLocation();
10457 }
10458 Filter.done();
10459 if (InCompoundScope) {
10460 for (auto &PrevData : UsedAsPrevious) {
10461 if (!PrevData.second) {
10462 PrevDRD = PrevData.first;
10463 break;
10464 }
10465 }
10466 }
10467 } else if (PrevDeclInScope != nullptr) {
10468 auto *PrevDRDInScope = PrevDRD =
10469 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10470 do {
10471 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10472 PrevDRDInScope->getLocation();
10473 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10474 } while (PrevDRDInScope != nullptr);
10475 }
10476 for (auto &TyData : ReductionTypes) {
10477 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10478 bool Invalid = false;
10479 if (I != PreviousRedeclTypes.end()) {
10480 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10481 << TyData.first;
10482 Diag(I->second, diag::note_previous_definition);
10483 Invalid = true;
10484 }
10485 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10486 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10487 Name, TyData.first, PrevDRD);
10488 DC->addDecl(DRD);
10489 DRD->setAccess(AS);
10490 Decls.push_back(DRD);
10491 if (Invalid)
10492 DRD->setInvalidDecl();
10493 else
10494 PrevDRD = DRD;
10495 }
10496
10497 return DeclGroupPtrTy::make(
10498 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10499}
10500
10501void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10502 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10503
10504 // Enter new function scope.
10505 PushFunctionScope();
10506 getCurFunction()->setHasBranchProtectedScope();
10507 getCurFunction()->setHasOMPDeclareReductionCombiner();
10508
10509 if (S != nullptr)
10510 PushDeclContext(S, DRD);
10511 else
10512 CurContext = DRD;
10513
10514 PushExpressionEvaluationContext(PotentiallyEvaluated);
10515
10516 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010517 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10518 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10519 // uses semantics of argument handles by value, but it should be passed by
10520 // reference. C lang does not support references, so pass all parameters as
10521 // pointers.
10522 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010523 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010524 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010525 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10526 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10527 // uses semantics of argument handles by value, but it should be passed by
10528 // reference. C lang does not support references, so pass all parameters as
10529 // pointers.
10530 // Create 'T omp_out;' variable.
10531 auto *OmpOutParm =
10532 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10533 if (S != nullptr) {
10534 PushOnScopeChains(OmpInParm, S);
10535 PushOnScopeChains(OmpOutParm, S);
10536 } else {
10537 DRD->addDecl(OmpInParm);
10538 DRD->addDecl(OmpOutParm);
10539 }
10540}
10541
10542void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10543 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10544 DiscardCleanupsInEvaluationContext();
10545 PopExpressionEvaluationContext();
10546
10547 PopDeclContext();
10548 PopFunctionScopeInfo();
10549
10550 if (Combiner != nullptr)
10551 DRD->setCombiner(Combiner);
10552 else
10553 DRD->setInvalidDecl();
10554}
10555
10556void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10557 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10558
10559 // Enter new function scope.
10560 PushFunctionScope();
10561 getCurFunction()->setHasBranchProtectedScope();
10562
10563 if (S != nullptr)
10564 PushDeclContext(S, DRD);
10565 else
10566 CurContext = DRD;
10567
10568 PushExpressionEvaluationContext(PotentiallyEvaluated);
10569
10570 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010571 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10572 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10573 // uses semantics of argument handles by value, but it should be passed by
10574 // reference. C lang does not support references, so pass all parameters as
10575 // pointers.
10576 // Create 'T omp_priv;' variable.
10577 auto *OmpPrivParm =
10578 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010579 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10580 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10581 // uses semantics of argument handles by value, but it should be passed by
10582 // reference. C lang does not support references, so pass all parameters as
10583 // pointers.
10584 // Create 'T omp_orig;' variable.
10585 auto *OmpOrigParm =
10586 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010587 if (S != nullptr) {
10588 PushOnScopeChains(OmpPrivParm, S);
10589 PushOnScopeChains(OmpOrigParm, S);
10590 } else {
10591 DRD->addDecl(OmpPrivParm);
10592 DRD->addDecl(OmpOrigParm);
10593 }
10594}
10595
10596void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10597 Expr *Initializer) {
10598 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10599 DiscardCleanupsInEvaluationContext();
10600 PopExpressionEvaluationContext();
10601
10602 PopDeclContext();
10603 PopFunctionScopeInfo();
10604
10605 if (Initializer != nullptr)
10606 DRD->setInitializer(Initializer);
10607 else
10608 DRD->setInvalidDecl();
10609}
10610
10611Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10612 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10613 for (auto *D : DeclReductions.get()) {
10614 if (IsValid) {
10615 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10616 if (S != nullptr)
10617 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10618 } else
10619 D->setInvalidDecl();
10620 }
10621 return DeclReductions;
10622}
10623
David Majnemer9d168222016-08-05 17:44:54 +000010624OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010625 SourceLocation StartLoc,
10626 SourceLocation LParenLoc,
10627 SourceLocation EndLoc) {
10628 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010629
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010630 // OpenMP [teams Constrcut, Restrictions]
10631 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010632 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10633 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010634 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010635
10636 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10637}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010638
10639OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10640 SourceLocation StartLoc,
10641 SourceLocation LParenLoc,
10642 SourceLocation EndLoc) {
10643 Expr *ValExpr = ThreadLimit;
10644
10645 // OpenMP [teams Constrcut, Restrictions]
10646 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010647 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10648 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010649 return nullptr;
10650
David Majnemer9d168222016-08-05 17:44:54 +000010651 return new (Context)
10652 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010653}
Alexey Bataeva0569352015-12-01 10:17:31 +000010654
10655OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10656 SourceLocation StartLoc,
10657 SourceLocation LParenLoc,
10658 SourceLocation EndLoc) {
10659 Expr *ValExpr = Priority;
10660
10661 // OpenMP [2.9.1, task Constrcut]
10662 // The priority-value is a non-negative numerical scalar expression.
10663 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10664 /*StrictlyPositive=*/false))
10665 return nullptr;
10666
10667 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10668}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010669
10670OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10671 SourceLocation StartLoc,
10672 SourceLocation LParenLoc,
10673 SourceLocation EndLoc) {
10674 Expr *ValExpr = Grainsize;
10675
10676 // OpenMP [2.9.2, taskloop Constrcut]
10677 // The parameter of the grainsize clause must be a positive integer
10678 // expression.
10679 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10680 /*StrictlyPositive=*/true))
10681 return nullptr;
10682
10683 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10684}
Alexey Bataev382967a2015-12-08 12:06:20 +000010685
10686OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10687 SourceLocation StartLoc,
10688 SourceLocation LParenLoc,
10689 SourceLocation EndLoc) {
10690 Expr *ValExpr = NumTasks;
10691
10692 // OpenMP [2.9.2, taskloop Constrcut]
10693 // The parameter of the num_tasks clause must be a positive integer
10694 // expression.
10695 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10696 /*StrictlyPositive=*/true))
10697 return nullptr;
10698
10699 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10700}
10701
Alexey Bataev28c75412015-12-15 08:19:24 +000010702OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10703 SourceLocation LParenLoc,
10704 SourceLocation EndLoc) {
10705 // OpenMP [2.13.2, critical construct, Description]
10706 // ... where hint-expression is an integer constant expression that evaluates
10707 // to a valid lock hint.
10708 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10709 if (HintExpr.isInvalid())
10710 return nullptr;
10711 return new (Context)
10712 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10713}
10714
Carlo Bertollib4adf552016-01-15 18:50:31 +000010715OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10716 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10717 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10718 SourceLocation EndLoc) {
10719 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10720 std::string Values;
10721 Values += "'";
10722 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10723 Values += "'";
10724 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10725 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10726 return nullptr;
10727 }
10728 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010729 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010730 if (ChunkSize) {
10731 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10732 !ChunkSize->isInstantiationDependent() &&
10733 !ChunkSize->containsUnexpandedParameterPack()) {
10734 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10735 ExprResult Val =
10736 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10737 if (Val.isInvalid())
10738 return nullptr;
10739
10740 ValExpr = Val.get();
10741
10742 // OpenMP [2.7.1, Restrictions]
10743 // chunk_size must be a loop invariant integer expression with a positive
10744 // value.
10745 llvm::APSInt Result;
10746 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10747 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10748 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10749 << "dist_schedule" << ChunkSize->getSourceRange();
10750 return nullptr;
10751 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010752 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10753 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010754 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10755 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10756 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010757 }
10758 }
10759 }
10760
10761 return new (Context)
10762 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010763 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010764}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010765
10766OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10767 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10768 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10769 SourceLocation KindLoc, SourceLocation EndLoc) {
10770 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010771 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010772 std::string Value;
10773 SourceLocation Loc;
10774 Value += "'";
10775 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10776 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010777 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010778 Loc = MLoc;
10779 } else {
10780 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010781 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010782 Loc = KindLoc;
10783 }
10784 Value += "'";
10785 Diag(Loc, diag::err_omp_unexpected_clause_value)
10786 << Value << getOpenMPClauseName(OMPC_defaultmap);
10787 return nullptr;
10788 }
10789
10790 return new (Context)
10791 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10792}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010793
10794bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10795 DeclContext *CurLexicalContext = getCurLexicalContext();
10796 if (!CurLexicalContext->isFileContext() &&
10797 !CurLexicalContext->isExternCContext() &&
10798 !CurLexicalContext->isExternCXXContext()) {
10799 Diag(Loc, diag::err_omp_region_not_file_context);
10800 return false;
10801 }
10802 if (IsInOpenMPDeclareTargetContext) {
10803 Diag(Loc, diag::err_omp_enclosed_declare_target);
10804 return false;
10805 }
10806
10807 IsInOpenMPDeclareTargetContext = true;
10808 return true;
10809}
10810
10811void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10812 assert(IsInOpenMPDeclareTargetContext &&
10813 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10814
10815 IsInOpenMPDeclareTargetContext = false;
10816}
10817
David Majnemer9d168222016-08-05 17:44:54 +000010818void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10819 CXXScopeSpec &ScopeSpec,
10820 const DeclarationNameInfo &Id,
10821 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10822 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010823 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10824 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10825
10826 if (Lookup.isAmbiguous())
10827 return;
10828 Lookup.suppressDiagnostics();
10829
10830 if (!Lookup.isSingleResult()) {
10831 if (TypoCorrection Corrected =
10832 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10833 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10834 CTK_ErrorRecovery)) {
10835 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10836 << Id.getName());
10837 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10838 return;
10839 }
10840
10841 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10842 return;
10843 }
10844
10845 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10846 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10847 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10848 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10849
10850 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10851 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10852 ND->addAttr(A);
10853 if (ASTMutationListener *ML = Context.getASTMutationListener())
10854 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10855 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10856 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10857 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10858 << Id.getName();
10859 }
10860 } else
10861 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10862}
10863
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010864static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10865 Sema &SemaRef, Decl *D) {
10866 if (!D)
10867 return;
10868 Decl *LD = nullptr;
10869 if (isa<TagDecl>(D)) {
10870 LD = cast<TagDecl>(D)->getDefinition();
10871 } else if (isa<VarDecl>(D)) {
10872 LD = cast<VarDecl>(D)->getDefinition();
10873
10874 // If this is an implicit variable that is legal and we do not need to do
10875 // anything.
10876 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010877 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10878 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10879 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010880 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010881 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010882 return;
10883 }
10884
10885 } else if (isa<FunctionDecl>(D)) {
10886 const FunctionDecl *FD = nullptr;
10887 if (cast<FunctionDecl>(D)->hasBody(FD))
10888 LD = const_cast<FunctionDecl *>(FD);
10889
10890 // If the definition is associated with the current declaration in the
10891 // target region (it can be e.g. a lambda) that is legal and we do not need
10892 // to do anything else.
10893 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010894 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10895 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10896 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010897 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010898 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010899 return;
10900 }
10901 }
10902 if (!LD)
10903 LD = D;
10904 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10905 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10906 // Outlined declaration is not declared target.
10907 if (LD->isOutOfLine()) {
10908 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10909 SemaRef.Diag(SL, diag::note_used_here) << SR;
10910 } else {
10911 DeclContext *DC = LD->getDeclContext();
10912 while (DC) {
10913 if (isa<FunctionDecl>(DC) &&
10914 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10915 break;
10916 DC = DC->getParent();
10917 }
10918 if (DC)
10919 return;
10920
10921 // Is not declared in target context.
10922 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10923 SemaRef.Diag(SL, diag::note_used_here) << SR;
10924 }
10925 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010926 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10927 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10928 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010929 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010930 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010931 }
10932}
10933
10934static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10935 Sema &SemaRef, DSAStackTy *Stack,
10936 ValueDecl *VD) {
10937 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10938 return true;
10939 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10940 return false;
10941 return true;
10942}
10943
10944void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10945 if (!D || D->isInvalidDecl())
10946 return;
10947 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10948 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10949 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10950 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10951 if (DSAStack->isThreadPrivate(VD)) {
10952 Diag(SL, diag::err_omp_threadprivate_in_target);
10953 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10954 return;
10955 }
10956 }
10957 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10958 // Problem if any with var declared with incomplete type will be reported
10959 // as normal, so no need to check it here.
10960 if ((E || !VD->getType()->isIncompleteType()) &&
10961 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10962 // Mark decl as declared target to prevent further diagnostic.
10963 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010964 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10965 Context, OMPDeclareTargetDeclAttr::MT_To);
10966 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010967 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010968 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010969 }
10970 return;
10971 }
10972 }
10973 if (!E) {
10974 // Checking declaration inside declare target region.
10975 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10976 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010977 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10978 Context, OMPDeclareTargetDeclAttr::MT_To);
10979 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010980 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010981 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010982 }
10983 return;
10984 }
10985 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10986}
Samuel Antao661c0902016-05-26 17:39:58 +000010987
10988OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10989 SourceLocation StartLoc,
10990 SourceLocation LParenLoc,
10991 SourceLocation EndLoc) {
10992 MappableVarListInfo MVLI(VarList);
10993 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10994 if (MVLI.ProcessedVarList.empty())
10995 return nullptr;
10996
10997 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10998 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10999 MVLI.VarComponents);
11000}
Samuel Antaoec172c62016-05-26 17:49:04 +000011001
11002OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11003 SourceLocation StartLoc,
11004 SourceLocation LParenLoc,
11005 SourceLocation EndLoc) {
11006 MappableVarListInfo MVLI(VarList);
11007 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11008 if (MVLI.ProcessedVarList.empty())
11009 return nullptr;
11010
11011 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11012 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11013 MVLI.VarComponents);
11014}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011015
11016OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11017 SourceLocation StartLoc,
11018 SourceLocation LParenLoc,
11019 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011020 MappableVarListInfo MVLI(VarList);
11021 SmallVector<Expr *, 8> PrivateCopies;
11022 SmallVector<Expr *, 8> Inits;
11023
Carlo Bertolli2404b172016-07-13 15:37:16 +000011024 for (auto &RefExpr : VarList) {
11025 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11026 SourceLocation ELoc;
11027 SourceRange ERange;
11028 Expr *SimpleRefExpr = RefExpr;
11029 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11030 if (Res.second) {
11031 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011032 MVLI.ProcessedVarList.push_back(RefExpr);
11033 PrivateCopies.push_back(nullptr);
11034 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011035 }
11036 ValueDecl *D = Res.first;
11037 if (!D)
11038 continue;
11039
11040 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011041 Type = Type.getNonReferenceType().getUnqualifiedType();
11042
11043 auto *VD = dyn_cast<VarDecl>(D);
11044
11045 // Item should be a pointer or reference to pointer.
11046 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011047 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11048 << 0 << RefExpr->getSourceRange();
11049 continue;
11050 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011051
11052 // Build the private variable and the expression that refers to it.
11053 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11054 D->hasAttrs() ? &D->getAttrs() : nullptr);
11055 if (VDPrivate->isInvalidDecl())
11056 continue;
11057
11058 CurContext->addDecl(VDPrivate);
11059 auto VDPrivateRefExpr = buildDeclRefExpr(
11060 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11061
11062 // Add temporary variable to initialize the private copy of the pointer.
11063 auto *VDInit =
11064 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11065 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11066 RefExpr->getExprLoc());
11067 AddInitializerToDecl(VDPrivate,
11068 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011069 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011070
11071 // If required, build a capture to implement the privatization initialized
11072 // with the current list item value.
11073 DeclRefExpr *Ref = nullptr;
11074 if (!VD)
11075 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11076 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11077 PrivateCopies.push_back(VDPrivateRefExpr);
11078 Inits.push_back(VDInitRefExpr);
11079
11080 // We need to add a data sharing attribute for this variable to make sure it
11081 // is correctly captured. A variable that shows up in a use_device_ptr has
11082 // similar properties of a first private variable.
11083 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11084
11085 // Create a mappable component for the list item. List items in this clause
11086 // only need a component.
11087 MVLI.VarBaseDeclarations.push_back(D);
11088 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11089 MVLI.VarComponents.back().push_back(
11090 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011091 }
11092
Samuel Antaocc10b852016-07-28 14:23:26 +000011093 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011094 return nullptr;
11095
Samuel Antaocc10b852016-07-28 14:23:26 +000011096 return OMPUseDevicePtrClause::Create(
11097 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11098 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011099}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011100
11101OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11102 SourceLocation StartLoc,
11103 SourceLocation LParenLoc,
11104 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011105 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011106 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011107 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011108 SourceLocation ELoc;
11109 SourceRange ERange;
11110 Expr *SimpleRefExpr = RefExpr;
11111 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11112 if (Res.second) {
11113 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011114 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011115 }
11116 ValueDecl *D = Res.first;
11117 if (!D)
11118 continue;
11119
11120 QualType Type = D->getType();
11121 // item should be a pointer or array or reference to pointer or array
11122 if (!Type.getNonReferenceType()->isPointerType() &&
11123 !Type.getNonReferenceType()->isArrayType()) {
11124 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11125 << 0 << RefExpr->getSourceRange();
11126 continue;
11127 }
Samuel Antao6890b092016-07-28 14:25:09 +000011128
11129 // Check if the declaration in the clause does not show up in any data
11130 // sharing attribute.
11131 auto DVar = DSAStack->getTopDSA(D, false);
11132 if (isOpenMPPrivate(DVar.CKind)) {
11133 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11134 << getOpenMPClauseName(DVar.CKind)
11135 << getOpenMPClauseName(OMPC_is_device_ptr)
11136 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11137 ReportOriginalDSA(*this, DSAStack, D, DVar);
11138 continue;
11139 }
11140
11141 Expr *ConflictExpr;
11142 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011143 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011144 [&ConflictExpr](
11145 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11146 OpenMPClauseKind) -> bool {
11147 ConflictExpr = R.front().getAssociatedExpression();
11148 return true;
11149 })) {
11150 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11151 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11152 << ConflictExpr->getSourceRange();
11153 continue;
11154 }
11155
11156 // Store the components in the stack so that they can be used to check
11157 // against other clauses later on.
11158 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11159 DSAStack->addMappableExpressionComponents(
11160 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11161
11162 // Record the expression we've just processed.
11163 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11164
11165 // Create a mappable component for the list item. List items in this clause
11166 // only need a component. We use a null declaration to signal fields in
11167 // 'this'.
11168 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11169 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11170 "Unexpected device pointer expression!");
11171 MVLI.VarBaseDeclarations.push_back(
11172 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11173 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11174 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011175 }
11176
Samuel Antao6890b092016-07-28 14:25:09 +000011177 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011178 return nullptr;
11179
Samuel Antao6890b092016-07-28 14:25:09 +000011180 return OMPIsDevicePtrClause::Create(
11181 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11182 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011183}