blob: ba7bb6b5877b2d4720d279793f1119b0cef25197 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Kelvin Libf594a52016-12-17 05:48:59 +00001597 case OMPD_teams:
1598 case OMPD_target_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001611 case OMPD_simd:
1612 case OMPD_for:
1613 case OMPD_for_simd:
1614 case OMPD_sections:
1615 case OMPD_section:
1616 case OMPD_single:
1617 case OMPD_master:
1618 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001619 case OMPD_taskgroup:
1620 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001621 case OMPD_ordered:
1622 case OMPD_atomic:
1623 case OMPD_target_data:
1624 case OMPD_target:
1625 case OMPD_target_parallel:
1626 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001627 case OMPD_target_parallel_for_simd:
1628 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001629 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001630 std::make_pair(StringRef(), QualType()) // __context with shared vars
1631 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001632 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1633 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001634 break;
1635 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001636 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001637 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001638 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1639 FunctionProtoType::ExtProtoInfo EPI;
1640 EPI.Variadic = true;
1641 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001642 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001643 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001644 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1645 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1646 std::make_pair(".copy_fn.",
1647 Context.getPointerType(CopyFnType).withConst()),
1648 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1650 };
1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001653 // Mark this captured region as inlined, because we don't use outlined
1654 // function directly.
1655 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1656 AlwaysInlineAttr::CreateImplicit(
1657 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001658 break;
1659 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001660 case OMPD_taskloop:
1661 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001662 QualType KmpInt32Ty =
1663 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1664 QualType KmpUInt64Ty =
1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1666 QualType KmpInt64Ty =
1667 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1668 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1669 FunctionProtoType::ExtProtoInfo EPI;
1670 EPI.Variadic = true;
1671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001672 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001673 std::make_pair(".global_tid.", KmpInt32Ty),
1674 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1675 std::make_pair(".privates.",
1676 Context.VoidPtrTy.withConst().withRestrict()),
1677 std::make_pair(
1678 ".copy_fn.",
1679 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1680 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1681 std::make_pair(".lb.", KmpUInt64Ty),
1682 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1683 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001684 std::make_pair(StringRef(), QualType()) // __context with shared vars
1685 };
1686 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1687 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001688 // Mark this captured region as inlined, because we don't use outlined
1689 // function directly.
1690 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1691 AlwaysInlineAttr::CreateImplicit(
1692 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001693 break;
1694 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001695 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001696 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001697 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001698 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001699 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001700 case OMPD_teams_distribute_parallel_for_simd:
1701 case OMPD_teams_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001702 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1703 QualType KmpInt32PtrTy =
1704 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1705 Sema::CapturedParamNameType Params[] = {
1706 std::make_pair(".global_tid.", KmpInt32PtrTy),
1707 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1708 std::make_pair(".previous.lb.", Context.getSizeType()),
1709 std::make_pair(".previous.ub.", Context.getSizeType()),
1710 std::make_pair(StringRef(), QualType()) // __context with shared vars
1711 };
1712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1713 Params);
1714 break;
1715 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001716 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001717 case OMPD_taskyield:
1718 case OMPD_barrier:
1719 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001720 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001721 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001722 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001723 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001724 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001725 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001726 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001727 case OMPD_declare_target:
1728 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001729 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001730 llvm_unreachable("OpenMP Directive is not allowed");
1731 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001732 llvm_unreachable("Unknown OpenMP directive");
1733 }
1734}
1735
Alexey Bataev3392d762016-02-16 11:18:12 +00001736static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001737 Expr *CaptureExpr, bool WithInit,
1738 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001739 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001740 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001741 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001742 QualType Ty = Init->getType();
1743 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1744 if (S.getLangOpts().CPlusPlus)
1745 Ty = C.getLValueReferenceType(Ty);
1746 else {
1747 Ty = C.getPointerType(Ty);
1748 ExprResult Res =
1749 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1750 if (!Res.isUsable())
1751 return nullptr;
1752 Init = Res.get();
1753 }
Alexey Bataev61205072016-03-02 04:57:40 +00001754 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001755 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001756 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1757 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001758 if (!WithInit)
1759 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001760 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001761 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1762 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001763 return CED;
1764}
1765
Alexey Bataev61205072016-03-02 04:57:40 +00001766static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1767 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001768 OMPCapturedExprDecl *CD;
1769 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1770 CD = cast<OMPCapturedExprDecl>(VD);
1771 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001772 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1773 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001774 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001775 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001776}
1777
Alexey Bataev5a3af132016-03-29 08:58:54 +00001778static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1779 if (!Ref) {
1780 auto *CD =
1781 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1782 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1783 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1784 CaptureExpr->getExprLoc());
1785 }
1786 ExprResult Res = Ref;
1787 if (!S.getLangOpts().CPlusPlus &&
1788 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1789 Ref->getType()->isPointerType())
1790 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1791 if (!Res.isUsable())
1792 return ExprError();
1793 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001794}
1795
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001796StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1797 ArrayRef<OMPClause *> Clauses) {
1798 if (!S.isUsable()) {
1799 ActOnCapturedRegionError();
1800 return StmtError();
1801 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001802
1803 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001804 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001805 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001806 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001807 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001808 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001809 Clause->getClauseKind() == OMPC_copyprivate ||
1810 (getLangOpts().OpenMPUseTLS &&
1811 getASTContext().getTargetInfo().isTLSSupported() &&
1812 Clause->getClauseKind() == OMPC_copyin)) {
1813 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001814 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001815 for (auto *VarRef : Clause->children()) {
1816 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001817 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001818 }
1819 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001820 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001821 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001822 // Mark all variables in private list clauses as used in inner region.
1823 // Required for proper codegen of combined directives.
1824 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001825 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001826 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1827 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001828 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1829 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001830 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001831 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1832 if (auto *E = C->getPostUpdateExpr())
1833 MarkDeclarationsReferencedInExpr(E);
1834 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001835 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001836 if (Clause->getClauseKind() == OMPC_schedule)
1837 SC = cast<OMPScheduleClause>(Clause);
1838 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001839 OC = cast<OMPOrderedClause>(Clause);
1840 else if (Clause->getClauseKind() == OMPC_linear)
1841 LCs.push_back(cast<OMPLinearClause>(Clause));
1842 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001843 bool ErrorFound = false;
1844 // OpenMP, 2.7.1 Loop Construct, Restrictions
1845 // The nonmonotonic modifier cannot be specified if an ordered clause is
1846 // specified.
1847 if (SC &&
1848 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1849 SC->getSecondScheduleModifier() ==
1850 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1851 OC) {
1852 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1853 ? SC->getFirstScheduleModifierLoc()
1854 : SC->getSecondScheduleModifierLoc(),
1855 diag::err_omp_schedule_nonmonotonic_ordered)
1856 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1857 ErrorFound = true;
1858 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001859 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1860 for (auto *C : LCs) {
1861 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1862 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1863 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001864 ErrorFound = true;
1865 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001866 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1867 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1868 OC->getNumForLoops()) {
1869 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1870 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1871 ErrorFound = true;
1872 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001873 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001874 ActOnCapturedRegionError();
1875 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001876 }
1877 return ActOnCapturedRegionEnd(S.get());
1878}
1879
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001880static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1881 OpenMPDirectiveKind CurrentRegion,
1882 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001883 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001884 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001885 if (Stack->getCurScope()) {
1886 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001887 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001888 bool NestingProhibited = false;
1889 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001890 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001891 enum {
1892 NoRecommend,
1893 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001894 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001895 ShouldBeInTargetRegion,
1896 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001897 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001898 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001899 // OpenMP [2.16, Nesting of Regions]
1900 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001901 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001902 // An ordered construct with the simd clause is the only OpenMP
1903 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001904 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001905 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1906 // message.
1907 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1908 ? diag::err_omp_prohibited_region_simd
1909 : diag::warn_omp_nesting_simd);
1910 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001911 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001912 if (ParentRegion == OMPD_atomic) {
1913 // OpenMP [2.16, Nesting of Regions]
1914 // OpenMP constructs may not be nested inside an atomic region.
1915 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1916 return true;
1917 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001918 if (CurrentRegion == OMPD_section) {
1919 // OpenMP [2.7.2, sections Construct, Restrictions]
1920 // Orphaned section directives are prohibited. That is, the section
1921 // directives must appear within the sections construct and must not be
1922 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001923 if (ParentRegion != OMPD_sections &&
1924 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001925 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1926 << (ParentRegion != OMPD_unknown)
1927 << getOpenMPDirectiveName(ParentRegion);
1928 return true;
1929 }
1930 return false;
1931 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001932 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001933 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001934 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00001935 if (ParentRegion == OMPD_unknown &&
1936 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001937 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001938 if (CurrentRegion == OMPD_cancellation_point ||
1939 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001940 // OpenMP [2.16, Nesting of Regions]
1941 // A cancellation point construct for which construct-type-clause is
1942 // taskgroup must be nested inside a task construct. A cancellation
1943 // point construct for which construct-type-clause is not taskgroup must
1944 // be closely nested inside an OpenMP construct that matches the type
1945 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001946 // A cancel construct for which construct-type-clause is taskgroup must be
1947 // nested inside a task construct. A cancel construct for which
1948 // construct-type-clause is not taskgroup must be closely nested inside an
1949 // OpenMP construct that matches the type specified in
1950 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001951 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001952 !((CancelRegion == OMPD_parallel &&
1953 (ParentRegion == OMPD_parallel ||
1954 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001955 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001956 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1957 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001958 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1959 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001960 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1961 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001962 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001963 // OpenMP [2.16, Nesting of Regions]
1964 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001965 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001966 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001967 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001968 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1969 // OpenMP [2.16, Nesting of Regions]
1970 // A critical region may not be nested (closely or otherwise) inside a
1971 // critical region with the same name. Note that this restriction is not
1972 // sufficient to prevent deadlock.
1973 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001974 bool DeadLock = Stack->hasDirective(
1975 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1976 const DeclarationNameInfo &DNI,
1977 SourceLocation Loc) -> bool {
1978 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1979 PreviousCriticalLoc = Loc;
1980 return true;
1981 } else
1982 return false;
1983 },
1984 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001985 if (DeadLock) {
1986 SemaRef.Diag(StartLoc,
1987 diag::err_omp_prohibited_region_critical_same_name)
1988 << CurrentName.getName();
1989 if (PreviousCriticalLoc.isValid())
1990 SemaRef.Diag(PreviousCriticalLoc,
1991 diag::note_omp_previous_critical_region);
1992 return true;
1993 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001994 } else if (CurrentRegion == OMPD_barrier) {
1995 // OpenMP [2.16, Nesting of Regions]
1996 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001997 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001998 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1999 isOpenMPTaskingDirective(ParentRegion) ||
2000 ParentRegion == OMPD_master ||
2001 ParentRegion == OMPD_critical ||
2002 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002003 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002004 !isOpenMPParallelDirective(CurrentRegion) &&
2005 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002006 // OpenMP [2.16, Nesting of Regions]
2007 // A worksharing region may not be closely nested inside a worksharing,
2008 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002009 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2010 isOpenMPTaskingDirective(ParentRegion) ||
2011 ParentRegion == OMPD_master ||
2012 ParentRegion == OMPD_critical ||
2013 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002014 Recommend = ShouldBeInParallelRegion;
2015 } else if (CurrentRegion == OMPD_ordered) {
2016 // OpenMP [2.16, Nesting of Regions]
2017 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002018 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002019 // An ordered region must be closely nested inside a loop region (or
2020 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002021 // OpenMP [2.8.1,simd Construct, Restrictions]
2022 // An ordered construct with the simd clause is the only OpenMP construct
2023 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002024 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002025 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002026 !(isOpenMPSimdDirective(ParentRegion) ||
2027 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002028 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002029 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002030 // OpenMP [2.16, Nesting of Regions]
2031 // If specified, a teams construct must be contained within a target
2032 // construct.
2033 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002034 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002035 Recommend = ShouldBeInTargetRegion;
2036 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2037 }
Kelvin Libf594a52016-12-17 05:48:59 +00002038 if (!NestingProhibited &&
2039 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2040 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2041 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002042 // OpenMP [2.16, Nesting of Regions]
2043 // distribute, parallel, parallel sections, parallel workshare, and the
2044 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2045 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002046 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2047 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002048 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002049 }
David Majnemer9d168222016-08-05 17:44:54 +00002050 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002051 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002052 // OpenMP 4.5 [2.17 Nesting of Regions]
2053 // The region associated with the distribute construct must be strictly
2054 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002055 NestingProhibited =
2056 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002057 Recommend = ShouldBeInTeamsRegion;
2058 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002059 if (!NestingProhibited &&
2060 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2061 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2062 // OpenMP 4.5 [2.17 Nesting of Regions]
2063 // If a target, target update, target data, target enter data, or
2064 // target exit data construct is encountered during execution of a
2065 // target region, the behavior is unspecified.
2066 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002067 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2068 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002069 if (isOpenMPTargetExecutionDirective(K)) {
2070 OffendingRegion = K;
2071 return true;
2072 } else
2073 return false;
2074 },
2075 false /* don't skip top directive */);
2076 CloseNesting = false;
2077 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002078 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002079 if (OrphanSeen) {
2080 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2081 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2082 } else {
2083 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2084 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2085 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2086 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002087 return true;
2088 }
2089 }
2090 return false;
2091}
2092
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002093static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2094 ArrayRef<OMPClause *> Clauses,
2095 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2096 bool ErrorFound = false;
2097 unsigned NamedModifiersNumber = 0;
2098 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2099 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002100 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002101 for (const auto *C : Clauses) {
2102 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2103 // At most one if clause without a directive-name-modifier can appear on
2104 // the directive.
2105 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2106 if (FoundNameModifiers[CurNM]) {
2107 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2108 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2109 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2110 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002111 } else if (CurNM != OMPD_unknown) {
2112 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002113 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002114 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002115 FoundNameModifiers[CurNM] = IC;
2116 if (CurNM == OMPD_unknown)
2117 continue;
2118 // Check if the specified name modifier is allowed for the current
2119 // directive.
2120 // At most one if clause with the particular directive-name-modifier can
2121 // appear on the directive.
2122 bool MatchFound = false;
2123 for (auto NM : AllowedNameModifiers) {
2124 if (CurNM == NM) {
2125 MatchFound = true;
2126 break;
2127 }
2128 }
2129 if (!MatchFound) {
2130 S.Diag(IC->getNameModifierLoc(),
2131 diag::err_omp_wrong_if_directive_name_modifier)
2132 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2133 ErrorFound = true;
2134 }
2135 }
2136 }
2137 // If any if clause on the directive includes a directive-name-modifier then
2138 // all if clauses on the directive must include a directive-name-modifier.
2139 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2140 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2141 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2142 diag::err_omp_no_more_if_clause);
2143 } else {
2144 std::string Values;
2145 std::string Sep(", ");
2146 unsigned AllowedCnt = 0;
2147 unsigned TotalAllowedNum =
2148 AllowedNameModifiers.size() - NamedModifiersNumber;
2149 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2150 ++Cnt) {
2151 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2152 if (!FoundNameModifiers[NM]) {
2153 Values += "'";
2154 Values += getOpenMPDirectiveName(NM);
2155 Values += "'";
2156 if (AllowedCnt + 2 == TotalAllowedNum)
2157 Values += " or ";
2158 else if (AllowedCnt + 1 != TotalAllowedNum)
2159 Values += Sep;
2160 ++AllowedCnt;
2161 }
2162 }
2163 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2164 diag::err_omp_unnamed_if_clause)
2165 << (TotalAllowedNum > 1) << Values;
2166 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002167 for (auto Loc : NameModifierLoc) {
2168 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2169 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002170 ErrorFound = true;
2171 }
2172 return ErrorFound;
2173}
2174
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002175StmtResult Sema::ActOnOpenMPExecutableDirective(
2176 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2177 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2178 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002179 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002180 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2181 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002182 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002183
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002184 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002185 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002186 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002187 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002188 if (AStmt) {
2189 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2190
2191 // Check default data sharing attributes for referenced variables.
2192 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2193 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2194 if (DSAChecker.isErrorFound())
2195 return StmtError();
2196 // Generate list of implicitly defined firstprivate variables.
2197 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002198
2199 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2200 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2201 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2202 SourceLocation(), SourceLocation())) {
2203 ClausesWithImplicit.push_back(Implicit);
2204 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2205 DSAChecker.getImplicitFirstprivate().size();
2206 } else
2207 ErrorFound = true;
2208 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002209 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002210
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002211 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002212 switch (Kind) {
2213 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002214 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2215 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002216 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002217 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002218 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002219 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2220 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002221 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002222 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002223 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2224 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002225 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002226 case OMPD_for_simd:
2227 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2228 EndLoc, VarsWithInheritedDSA);
2229 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002230 case OMPD_sections:
2231 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2232 EndLoc);
2233 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002234 case OMPD_section:
2235 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002236 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002237 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2238 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002239 case OMPD_single:
2240 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2241 EndLoc);
2242 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002243 case OMPD_master:
2244 assert(ClausesWithImplicit.empty() &&
2245 "No clauses are allowed for 'omp master' directive");
2246 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2247 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002248 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002249 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2250 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002251 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002252 case OMPD_parallel_for:
2253 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2254 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002255 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002256 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002257 case OMPD_parallel_for_simd:
2258 Res = ActOnOpenMPParallelForSimdDirective(
2259 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002260 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002261 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002262 case OMPD_parallel_sections:
2263 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2264 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002265 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002266 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002267 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002268 Res =
2269 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002270 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002271 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002272 case OMPD_taskyield:
2273 assert(ClausesWithImplicit.empty() &&
2274 "No clauses are allowed for 'omp taskyield' directive");
2275 assert(AStmt == nullptr &&
2276 "No associated statement allowed for 'omp taskyield' directive");
2277 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2278 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002279 case OMPD_barrier:
2280 assert(ClausesWithImplicit.empty() &&
2281 "No clauses are allowed for 'omp barrier' directive");
2282 assert(AStmt == nullptr &&
2283 "No associated statement allowed for 'omp barrier' directive");
2284 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2285 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002286 case OMPD_taskwait:
2287 assert(ClausesWithImplicit.empty() &&
2288 "No clauses are allowed for 'omp taskwait' directive");
2289 assert(AStmt == nullptr &&
2290 "No associated statement allowed for 'omp taskwait' directive");
2291 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2292 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002293 case OMPD_taskgroup:
2294 assert(ClausesWithImplicit.empty() &&
2295 "No clauses are allowed for 'omp taskgroup' directive");
2296 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2297 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002298 case OMPD_flush:
2299 assert(AStmt == nullptr &&
2300 "No associated statement allowed for 'omp flush' directive");
2301 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2302 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002303 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002304 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2305 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002306 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002307 case OMPD_atomic:
2308 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2309 EndLoc);
2310 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002311 case OMPD_teams:
2312 Res =
2313 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2314 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002315 case OMPD_target:
2316 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2317 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002318 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002319 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002320 case OMPD_target_parallel:
2321 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2322 StartLoc, EndLoc);
2323 AllowedNameModifiers.push_back(OMPD_target);
2324 AllowedNameModifiers.push_back(OMPD_parallel);
2325 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002326 case OMPD_target_parallel_for:
2327 Res = ActOnOpenMPTargetParallelForDirective(
2328 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2329 AllowedNameModifiers.push_back(OMPD_target);
2330 AllowedNameModifiers.push_back(OMPD_parallel);
2331 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002332 case OMPD_cancellation_point:
2333 assert(ClausesWithImplicit.empty() &&
2334 "No clauses are allowed for 'omp cancellation point' directive");
2335 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2336 "cancellation point' directive");
2337 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2338 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002339 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002340 assert(AStmt == nullptr &&
2341 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002342 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2343 CancelRegion);
2344 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002345 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002346 case OMPD_target_data:
2347 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2348 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002349 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002350 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002351 case OMPD_target_enter_data:
2352 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2353 EndLoc);
2354 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2355 break;
Samuel Antao72590762016-01-19 20:04:50 +00002356 case OMPD_target_exit_data:
2357 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2358 EndLoc);
2359 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2360 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002361 case OMPD_taskloop:
2362 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2363 EndLoc, VarsWithInheritedDSA);
2364 AllowedNameModifiers.push_back(OMPD_taskloop);
2365 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002366 case OMPD_taskloop_simd:
2367 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2368 EndLoc, VarsWithInheritedDSA);
2369 AllowedNameModifiers.push_back(OMPD_taskloop);
2370 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002371 case OMPD_distribute:
2372 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2373 EndLoc, VarsWithInheritedDSA);
2374 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002375 case OMPD_target_update:
2376 assert(!AStmt && "Statement is not allowed for target update");
2377 Res =
2378 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2379 AllowedNameModifiers.push_back(OMPD_target_update);
2380 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002381 case OMPD_distribute_parallel_for:
2382 Res = ActOnOpenMPDistributeParallelForDirective(
2383 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2384 AllowedNameModifiers.push_back(OMPD_parallel);
2385 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002386 case OMPD_distribute_parallel_for_simd:
2387 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2388 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2389 AllowedNameModifiers.push_back(OMPD_parallel);
2390 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002391 case OMPD_distribute_simd:
2392 Res = ActOnOpenMPDistributeSimdDirective(
2393 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2394 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002395 case OMPD_target_parallel_for_simd:
2396 Res = ActOnOpenMPTargetParallelForSimdDirective(
2397 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2398 AllowedNameModifiers.push_back(OMPD_target);
2399 AllowedNameModifiers.push_back(OMPD_parallel);
2400 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002401 case OMPD_target_simd:
2402 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2403 EndLoc, VarsWithInheritedDSA);
2404 AllowedNameModifiers.push_back(OMPD_target);
2405 break;
Kelvin Li02532872016-08-05 14:37:37 +00002406 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002407 Res = ActOnOpenMPTeamsDistributeDirective(
2408 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002409 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002410 case OMPD_teams_distribute_simd:
2411 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2412 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2413 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002414 case OMPD_teams_distribute_parallel_for_simd:
2415 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2416 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2417 AllowedNameModifiers.push_back(OMPD_parallel);
2418 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002419 case OMPD_teams_distribute_parallel_for:
2420 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2421 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2422 AllowedNameModifiers.push_back(OMPD_parallel);
2423 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002424 case OMPD_target_teams:
2425 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2426 EndLoc);
2427 AllowedNameModifiers.push_back(OMPD_target);
2428 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002429 case OMPD_declare_target:
2430 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002431 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002432 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002433 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002434 llvm_unreachable("OpenMP Directive is not allowed");
2435 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002436 llvm_unreachable("Unknown OpenMP directive");
2437 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002438
Alexey Bataev4acb8592014-07-07 13:01:15 +00002439 for (auto P : VarsWithInheritedDSA) {
2440 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2441 << P.first << P.second->getSourceRange();
2442 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002443 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2444
2445 if (!AllowedNameModifiers.empty())
2446 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2447 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002448
Alexey Bataeved09d242014-05-28 05:53:51 +00002449 if (ErrorFound)
2450 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002451 return Res;
2452}
2453
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002454Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2455 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002456 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002457 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2458 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002459 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002460 assert(Linears.size() == LinModifiers.size());
2461 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002462 if (!DG || DG.get().isNull())
2463 return DeclGroupPtrTy();
2464
2465 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002466 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002467 return DG;
2468 }
2469 auto *ADecl = DG.get().getSingleDecl();
2470 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2471 ADecl = FTD->getTemplatedDecl();
2472
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002473 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2474 if (!FD) {
2475 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002476 return DeclGroupPtrTy();
2477 }
2478
Alexey Bataev2af33e32016-04-07 12:45:37 +00002479 // OpenMP [2.8.2, declare simd construct, Description]
2480 // The parameter of the simdlen clause must be a constant positive integer
2481 // expression.
2482 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002483 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002484 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002485 // OpenMP [2.8.2, declare simd construct, Description]
2486 // The special this pointer can be used as if was one of the arguments to the
2487 // function in any of the linear, aligned, or uniform clauses.
2488 // The uniform clause declares one or more arguments to have an invariant
2489 // value for all concurrent invocations of the function in the execution of a
2490 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002491 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2492 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002493 for (auto *E : Uniforms) {
2494 E = E->IgnoreParenImpCasts();
2495 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2496 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2497 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2498 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002499 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2500 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002501 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002502 }
2503 if (isa<CXXThisExpr>(E)) {
2504 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002505 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002506 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002507 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2508 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002509 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002510 // OpenMP [2.8.2, declare simd construct, Description]
2511 // The aligned clause declares that the object to which each list item points
2512 // is aligned to the number of bytes expressed in the optional parameter of
2513 // the aligned clause.
2514 // The special this pointer can be used as if was one of the arguments to the
2515 // function in any of the linear, aligned, or uniform clauses.
2516 // The type of list items appearing in the aligned clause must be array,
2517 // pointer, reference to array, or reference to pointer.
2518 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2519 Expr *AlignedThis = nullptr;
2520 for (auto *E : Aligneds) {
2521 E = E->IgnoreParenImpCasts();
2522 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2523 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2524 auto *CanonPVD = PVD->getCanonicalDecl();
2525 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2526 FD->getParamDecl(PVD->getFunctionScopeIndex())
2527 ->getCanonicalDecl() == CanonPVD) {
2528 // OpenMP [2.8.1, simd construct, Restrictions]
2529 // A list-item cannot appear in more than one aligned clause.
2530 if (AlignedArgs.count(CanonPVD) > 0) {
2531 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2532 << 1 << E->getSourceRange();
2533 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2534 diag::note_omp_explicit_dsa)
2535 << getOpenMPClauseName(OMPC_aligned);
2536 continue;
2537 }
2538 AlignedArgs[CanonPVD] = E;
2539 QualType QTy = PVD->getType()
2540 .getNonReferenceType()
2541 .getUnqualifiedType()
2542 .getCanonicalType();
2543 const Type *Ty = QTy.getTypePtrOrNull();
2544 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2545 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2546 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2547 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2548 }
2549 continue;
2550 }
2551 }
2552 if (isa<CXXThisExpr>(E)) {
2553 if (AlignedThis) {
2554 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2555 << 2 << E->getSourceRange();
2556 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2557 << getOpenMPClauseName(OMPC_aligned);
2558 }
2559 AlignedThis = E;
2560 continue;
2561 }
2562 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2563 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2564 }
2565 // The optional parameter of the aligned clause, alignment, must be a constant
2566 // positive integer expression. If no optional parameter is specified,
2567 // implementation-defined default alignments for SIMD instructions on the
2568 // target platforms are assumed.
2569 SmallVector<Expr *, 4> NewAligns;
2570 for (auto *E : Alignments) {
2571 ExprResult Align;
2572 if (E)
2573 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2574 NewAligns.push_back(Align.get());
2575 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002576 // OpenMP [2.8.2, declare simd construct, Description]
2577 // The linear clause declares one or more list items to be private to a SIMD
2578 // lane and to have a linear relationship with respect to the iteration space
2579 // of a loop.
2580 // The special this pointer can be used as if was one of the arguments to the
2581 // function in any of the linear, aligned, or uniform clauses.
2582 // When a linear-step expression is specified in a linear clause it must be
2583 // either a constant integer expression or an integer-typed parameter that is
2584 // specified in a uniform clause on the directive.
2585 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2586 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2587 auto MI = LinModifiers.begin();
2588 for (auto *E : Linears) {
2589 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2590 ++MI;
2591 E = E->IgnoreParenImpCasts();
2592 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2593 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2594 auto *CanonPVD = PVD->getCanonicalDecl();
2595 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2596 FD->getParamDecl(PVD->getFunctionScopeIndex())
2597 ->getCanonicalDecl() == CanonPVD) {
2598 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2599 // A list-item cannot appear in more than one linear clause.
2600 if (LinearArgs.count(CanonPVD) > 0) {
2601 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2602 << getOpenMPClauseName(OMPC_linear)
2603 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2604 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2605 diag::note_omp_explicit_dsa)
2606 << getOpenMPClauseName(OMPC_linear);
2607 continue;
2608 }
2609 // Each argument can appear in at most one uniform or linear clause.
2610 if (UniformedArgs.count(CanonPVD) > 0) {
2611 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2612 << getOpenMPClauseName(OMPC_linear)
2613 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2614 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2615 diag::note_omp_explicit_dsa)
2616 << getOpenMPClauseName(OMPC_uniform);
2617 continue;
2618 }
2619 LinearArgs[CanonPVD] = E;
2620 if (E->isValueDependent() || E->isTypeDependent() ||
2621 E->isInstantiationDependent() ||
2622 E->containsUnexpandedParameterPack())
2623 continue;
2624 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2625 PVD->getOriginalType());
2626 continue;
2627 }
2628 }
2629 if (isa<CXXThisExpr>(E)) {
2630 if (UniformedLinearThis) {
2631 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2632 << getOpenMPClauseName(OMPC_linear)
2633 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2634 << E->getSourceRange();
2635 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2636 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2637 : OMPC_linear);
2638 continue;
2639 }
2640 UniformedLinearThis = E;
2641 if (E->isValueDependent() || E->isTypeDependent() ||
2642 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2643 continue;
2644 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2645 E->getType());
2646 continue;
2647 }
2648 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2649 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2650 }
2651 Expr *Step = nullptr;
2652 Expr *NewStep = nullptr;
2653 SmallVector<Expr *, 4> NewSteps;
2654 for (auto *E : Steps) {
2655 // Skip the same step expression, it was checked already.
2656 if (Step == E || !E) {
2657 NewSteps.push_back(E ? NewStep : nullptr);
2658 continue;
2659 }
2660 Step = E;
2661 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2662 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2663 auto *CanonPVD = PVD->getCanonicalDecl();
2664 if (UniformedArgs.count(CanonPVD) == 0) {
2665 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2666 << Step->getSourceRange();
2667 } else if (E->isValueDependent() || E->isTypeDependent() ||
2668 E->isInstantiationDependent() ||
2669 E->containsUnexpandedParameterPack() ||
2670 CanonPVD->getType()->hasIntegerRepresentation())
2671 NewSteps.push_back(Step);
2672 else {
2673 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2674 << Step->getSourceRange();
2675 }
2676 continue;
2677 }
2678 NewStep = Step;
2679 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2680 !Step->isInstantiationDependent() &&
2681 !Step->containsUnexpandedParameterPack()) {
2682 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2683 .get();
2684 if (NewStep)
2685 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2686 }
2687 NewSteps.push_back(NewStep);
2688 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002689 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2690 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002691 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002692 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2693 const_cast<Expr **>(Linears.data()), Linears.size(),
2694 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2695 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002696 ADecl->addAttr(NewAttr);
2697 return ConvertDeclToDeclGroup(ADecl);
2698}
2699
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002700StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2701 Stmt *AStmt,
2702 SourceLocation StartLoc,
2703 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002704 if (!AStmt)
2705 return StmtError();
2706
Alexey Bataev9959db52014-05-06 10:08:46 +00002707 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2708 // 1.2.2 OpenMP Language Terminology
2709 // Structured block - An executable statement with a single entry at the
2710 // top and a single exit at the bottom.
2711 // The point of exit cannot be a branch out of the structured block.
2712 // longjmp() and throw() must not violate the entry/exit criteria.
2713 CS->getCapturedDecl()->setNothrow();
2714
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002715 getCurFunction()->setHasBranchProtectedScope();
2716
Alexey Bataev25e5b442015-09-15 12:52:43 +00002717 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2718 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002719}
2720
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002721namespace {
2722/// \brief Helper class for checking canonical form of the OpenMP loops and
2723/// extracting iteration space of each loop in the loop nest, that will be used
2724/// for IR generation.
2725class OpenMPIterationSpaceChecker {
2726 /// \brief Reference to Sema.
2727 Sema &SemaRef;
2728 /// \brief A location for diagnostics (when there is no some better location).
2729 SourceLocation DefaultLoc;
2730 /// \brief A location for diagnostics (when increment is not compatible).
2731 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002732 /// \brief A source location for referring to loop init later.
2733 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002734 /// \brief A source location for referring to condition later.
2735 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002736 /// \brief A source location for referring to increment later.
2737 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002738 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002739 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002740 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002741 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002742 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002743 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002744 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002745 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002746 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002747 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002748 /// \brief This flag is true when condition is one of:
2749 /// Var < UB
2750 /// Var <= UB
2751 /// UB > Var
2752 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002753 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002754 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002755 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002756 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002757 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002758
2759public:
2760 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002761 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002762 /// \brief Check init-expr for canonical loop form and save loop counter
2763 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002764 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002765 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2766 /// for less/greater and for strict/non-strict comparison.
2767 bool CheckCond(Expr *S);
2768 /// \brief Check incr-expr for canonical loop form and return true if it
2769 /// does not conform, otherwise save loop step (#Step).
2770 bool CheckInc(Expr *S);
2771 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002772 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002773 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002774 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002775 /// \brief Source range of the loop init.
2776 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2777 /// \brief Source range of the loop condition.
2778 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2779 /// \brief Source range of the loop increment.
2780 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2781 /// \brief True if the step should be subtracted.
2782 bool ShouldSubtractStep() const { return SubtractStep; }
2783 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002784 Expr *
2785 BuildNumIterations(Scope *S, const bool LimitedType,
2786 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002787 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002788 Expr *BuildPreCond(Scope *S, Expr *Cond,
2789 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002790 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002791 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2792 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002793 /// \brief Build reference expression to the private counter be used for
2794 /// codegen.
2795 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002796 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002797 Expr *BuildCounterInit() const;
2798 /// \brief Build step of the counter be used for codegen.
2799 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002800 /// \brief Return true if any expression is dependent.
2801 bool Dependent() const;
2802
2803private:
2804 /// \brief Check the right-hand side of an assignment in the increment
2805 /// expression.
2806 bool CheckIncRHS(Expr *RHS);
2807 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002808 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002809 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002810 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002811 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002812 /// \brief Helper to set loop increment.
2813 bool SetStep(Expr *NewStep, bool Subtract);
2814};
2815
2816bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002817 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002818 assert(!LB && !UB && !Step);
2819 return false;
2820 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002821 return LCDecl->getType()->isDependentType() ||
2822 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2823 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002824}
2825
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002826static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002827 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2828 E = ExprTemp->getSubExpr();
2829
2830 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2831 E = MTE->GetTemporaryExpr();
2832
2833 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2834 E = Binder->getSubExpr();
2835
2836 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2837 E = ICE->getSubExprAsWritten();
2838 return E->IgnoreParens();
2839}
2840
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002841bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2842 Expr *NewLCRefExpr,
2843 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002844 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002845 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002846 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002847 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002848 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002849 LCDecl = getCanonicalDecl(NewLCDecl);
2850 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002851 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2852 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002853 if ((Ctor->isCopyOrMoveConstructor() ||
2854 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2855 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002856 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002857 LB = NewLB;
2858 return false;
2859}
2860
2861bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002862 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002863 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002864 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2865 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002866 if (!NewUB)
2867 return true;
2868 UB = NewUB;
2869 TestIsLessOp = LessOp;
2870 TestIsStrictOp = StrictOp;
2871 ConditionSrcRange = SR;
2872 ConditionLoc = SL;
2873 return false;
2874}
2875
2876bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2877 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002878 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002879 if (!NewStep)
2880 return true;
2881 if (!NewStep->isValueDependent()) {
2882 // Check that the step is integer expression.
2883 SourceLocation StepLoc = NewStep->getLocStart();
2884 ExprResult Val =
2885 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2886 if (Val.isInvalid())
2887 return true;
2888 NewStep = Val.get();
2889
2890 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2891 // If test-expr is of form var relational-op b and relational-op is < or
2892 // <= then incr-expr must cause var to increase on each iteration of the
2893 // loop. If test-expr is of form var relational-op b and relational-op is
2894 // > or >= then incr-expr must cause var to decrease on each iteration of
2895 // the loop.
2896 // If test-expr is of form b relational-op var and relational-op is < or
2897 // <= then incr-expr must cause var to decrease on each iteration of the
2898 // loop. If test-expr is of form b relational-op var and relational-op is
2899 // > or >= then incr-expr must cause var to increase on each iteration of
2900 // the loop.
2901 llvm::APSInt Result;
2902 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2903 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2904 bool IsConstNeg =
2905 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002906 bool IsConstPos =
2907 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002908 bool IsConstZero = IsConstant && !Result.getBoolValue();
2909 if (UB && (IsConstZero ||
2910 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002911 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002912 SemaRef.Diag(NewStep->getExprLoc(),
2913 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002914 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002915 SemaRef.Diag(ConditionLoc,
2916 diag::note_omp_loop_cond_requres_compatible_incr)
2917 << TestIsLessOp << ConditionSrcRange;
2918 return true;
2919 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002920 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002921 NewStep =
2922 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2923 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002924 Subtract = !Subtract;
2925 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002926 }
2927
2928 Step = NewStep;
2929 SubtractStep = Subtract;
2930 return false;
2931}
2932
Alexey Bataev9c821032015-04-30 04:23:23 +00002933bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002934 // Check init-expr for canonical loop form and save loop counter
2935 // variable - #Var and its initialization value - #LB.
2936 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2937 // var = lb
2938 // integer-type var = lb
2939 // random-access-iterator-type var = lb
2940 // pointer-type var = lb
2941 //
2942 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002943 if (EmitDiags) {
2944 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2945 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002946 return true;
2947 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002948 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2949 if (!ExprTemp->cleanupsHaveSideEffects())
2950 S = ExprTemp->getSubExpr();
2951
Alexander Musmana5f070a2014-10-01 06:03:56 +00002952 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002953 if (Expr *E = dyn_cast<Expr>(S))
2954 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002955 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002956 if (BO->getOpcode() == BO_Assign) {
2957 auto *LHS = BO->getLHS()->IgnoreParens();
2958 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2959 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2960 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2961 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2962 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2963 }
2964 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2965 if (ME->isArrow() &&
2966 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2967 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2968 }
2969 }
David Majnemer9d168222016-08-05 17:44:54 +00002970 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002971 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002972 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002973 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002974 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002975 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002976 SemaRef.Diag(S->getLocStart(),
2977 diag::ext_omp_loop_not_canonical_init)
2978 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002979 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002980 }
2981 }
2982 }
David Majnemer9d168222016-08-05 17:44:54 +00002983 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002984 if (CE->getOperator() == OO_Equal) {
2985 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00002986 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002987 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2988 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2989 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2990 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
2991 }
2992 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2993 if (ME->isArrow() &&
2994 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2995 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2996 }
2997 }
2998 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002999
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003000 if (Dependent() || SemaRef.CurContext->isDependentContext())
3001 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003002 if (EmitDiags) {
3003 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3004 << S->getSourceRange();
3005 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003006 return true;
3007}
3008
Alexey Bataev23b69422014-06-18 07:08:49 +00003009/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003010/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003011static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003012 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003013 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003014 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003015 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3016 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003017 if ((Ctor->isCopyOrMoveConstructor() ||
3018 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3019 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003020 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003021 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3022 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3023 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3024 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3025 return getCanonicalDecl(ME->getMemberDecl());
3026 return getCanonicalDecl(VD);
3027 }
3028 }
3029 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3030 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3031 return getCanonicalDecl(ME->getMemberDecl());
3032 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003033}
3034
3035bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3036 // Check test-expr for canonical form, save upper-bound UB, flags for
3037 // less/greater and for strict/non-strict comparison.
3038 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3039 // var relational-op b
3040 // b relational-op var
3041 //
3042 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003043 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003044 return true;
3045 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003046 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003047 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003048 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003049 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003050 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003051 return SetUB(BO->getRHS(),
3052 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3053 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3054 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003055 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003056 return SetUB(BO->getLHS(),
3057 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3058 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3059 BO->getSourceRange(), BO->getOperatorLoc());
3060 }
David Majnemer9d168222016-08-05 17:44:54 +00003061 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003062 if (CE->getNumArgs() == 2) {
3063 auto Op = CE->getOperator();
3064 switch (Op) {
3065 case OO_Greater:
3066 case OO_GreaterEqual:
3067 case OO_Less:
3068 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003069 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003070 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3071 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3072 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003073 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003074 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3075 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3076 CE->getOperatorLoc());
3077 break;
3078 default:
3079 break;
3080 }
3081 }
3082 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003083 if (Dependent() || SemaRef.CurContext->isDependentContext())
3084 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003085 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003086 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003087 return true;
3088}
3089
3090bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3091 // RHS of canonical loop form increment can be:
3092 // var + incr
3093 // incr + var
3094 // var - incr
3095 //
3096 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003097 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003098 if (BO->isAdditiveOp()) {
3099 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003100 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003101 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003102 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003103 return SetStep(BO->getLHS(), false);
3104 }
David Majnemer9d168222016-08-05 17:44:54 +00003105 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003106 bool IsAdd = CE->getOperator() == OO_Plus;
3107 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003108 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003109 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003110 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 return SetStep(CE->getArg(0), false);
3112 }
3113 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003114 if (Dependent() || SemaRef.CurContext->isDependentContext())
3115 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003116 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003117 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003118 return true;
3119}
3120
3121bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3122 // Check incr-expr for canonical loop form and return true if it
3123 // does not conform.
3124 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3125 // ++var
3126 // var++
3127 // --var
3128 // var--
3129 // var += incr
3130 // var -= incr
3131 // var = var + incr
3132 // var = incr + var
3133 // var = var - incr
3134 //
3135 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003136 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003137 return true;
3138 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003139 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3140 if (!ExprTemp->cleanupsHaveSideEffects())
3141 S = ExprTemp->getSubExpr();
3142
Alexander Musmana5f070a2014-10-01 06:03:56 +00003143 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003144 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003145 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003146 if (UO->isIncrementDecrementOp() &&
3147 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003148 return SetStep(SemaRef
3149 .ActOnIntegerConstant(UO->getLocStart(),
3150 (UO->isDecrementOp() ? -1 : 1))
3151 .get(),
3152 false);
3153 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003154 switch (BO->getOpcode()) {
3155 case BO_AddAssign:
3156 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003157 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003158 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3159 break;
3160 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003161 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003162 return CheckIncRHS(BO->getRHS());
3163 break;
3164 default:
3165 break;
3166 }
David Majnemer9d168222016-08-05 17:44:54 +00003167 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 switch (CE->getOperator()) {
3169 case OO_PlusPlus:
3170 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003171 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003172 return SetStep(SemaRef
3173 .ActOnIntegerConstant(
3174 CE->getLocStart(),
3175 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3176 .get(),
3177 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003178 break;
3179 case OO_PlusEqual:
3180 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003181 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003182 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3183 break;
3184 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003185 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 return CheckIncRHS(CE->getArg(1));
3187 break;
3188 default:
3189 break;
3190 }
3191 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003192 if (Dependent() || SemaRef.CurContext->isDependentContext())
3193 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003194 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003195 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003196 return true;
3197}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003198
Alexey Bataev5a3af132016-03-29 08:58:54 +00003199static ExprResult
3200tryBuildCapture(Sema &SemaRef, Expr *Capture,
3201 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003202 if (SemaRef.CurContext->isDependentContext())
3203 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003204 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3205 return SemaRef.PerformImplicitConversion(
3206 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3207 /*AllowExplicit=*/true);
3208 auto I = Captures.find(Capture);
3209 if (I != Captures.end())
3210 return buildCapture(SemaRef, Capture, I->second);
3211 DeclRefExpr *Ref = nullptr;
3212 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3213 Captures[Capture] = Ref;
3214 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003215}
3216
Alexander Musmana5f070a2014-10-01 06:03:56 +00003217/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003218Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3219 Scope *S, const bool LimitedType,
3220 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003221 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003222 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003223 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003224 SemaRef.getLangOpts().CPlusPlus) {
3225 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003226 auto *UBExpr = TestIsLessOp ? UB : LB;
3227 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003228 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3229 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003230 if (!Upper || !Lower)
3231 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003232
3233 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3234
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003235 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003236 // BuildBinOp already emitted error, this one is to point user to upper
3237 // and lower bound, and to tell what is passed to 'operator-'.
3238 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3239 << Upper->getSourceRange() << Lower->getSourceRange();
3240 return nullptr;
3241 }
3242 }
3243
3244 if (!Diff.isUsable())
3245 return nullptr;
3246
3247 // Upper - Lower [- 1]
3248 if (TestIsStrictOp)
3249 Diff = SemaRef.BuildBinOp(
3250 S, DefaultLoc, BO_Sub, Diff.get(),
3251 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3252 if (!Diff.isUsable())
3253 return nullptr;
3254
3255 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003256 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3257 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003258 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003259 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003260 if (!Diff.isUsable())
3261 return nullptr;
3262
3263 // Parentheses (for dumping/debugging purposes only).
3264 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3265 if (!Diff.isUsable())
3266 return nullptr;
3267
3268 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003269 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003270 if (!Diff.isUsable())
3271 return nullptr;
3272
Alexander Musman174b3ca2014-10-06 11:16:29 +00003273 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003274 QualType Type = Diff.get()->getType();
3275 auto &C = SemaRef.Context;
3276 bool UseVarType = VarType->hasIntegerRepresentation() &&
3277 C.getTypeSize(Type) > C.getTypeSize(VarType);
3278 if (!Type->isIntegerType() || UseVarType) {
3279 unsigned NewSize =
3280 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3281 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3282 : Type->hasSignedIntegerRepresentation();
3283 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003284 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3285 Diff = SemaRef.PerformImplicitConversion(
3286 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3287 if (!Diff.isUsable())
3288 return nullptr;
3289 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003290 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003291 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003292 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3293 if (NewSize != C.getTypeSize(Type)) {
3294 if (NewSize < C.getTypeSize(Type)) {
3295 assert(NewSize == 64 && "incorrect loop var size");
3296 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3297 << InitSrcRange << ConditionSrcRange;
3298 }
3299 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003300 NewSize, Type->hasSignedIntegerRepresentation() ||
3301 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003302 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3303 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3304 Sema::AA_Converting, true);
3305 if (!Diff.isUsable())
3306 return nullptr;
3307 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003308 }
3309 }
3310
Alexander Musmana5f070a2014-10-01 06:03:56 +00003311 return Diff.get();
3312}
3313
Alexey Bataev5a3af132016-03-29 08:58:54 +00003314Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3315 Scope *S, Expr *Cond,
3316 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003317 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3318 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3319 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003320
Alexey Bataev5a3af132016-03-29 08:58:54 +00003321 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3322 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3323 if (!NewLB.isUsable() || !NewUB.isUsable())
3324 return nullptr;
3325
Alexey Bataev62dbb972015-04-22 11:59:37 +00003326 auto CondExpr = SemaRef.BuildBinOp(
3327 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3328 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003329 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003330 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003331 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3332 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003333 CondExpr = SemaRef.PerformImplicitConversion(
3334 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3335 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003336 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003337 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3338 // Otherwise use original loop conditon and evaluate it in runtime.
3339 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3340}
3341
Alexander Musmana5f070a2014-10-01 06:03:56 +00003342/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003343DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003344 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003345 auto *VD = dyn_cast<VarDecl>(LCDecl);
3346 if (!VD) {
3347 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3348 auto *Ref = buildDeclRefExpr(
3349 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003350 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3351 // If the loop control decl is explicitly marked as private, do not mark it
3352 // as captured again.
3353 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3354 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003355 return Ref;
3356 }
3357 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003358 DefaultLoc);
3359}
3360
3361Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003362 if (LCDecl && !LCDecl->isInvalidDecl()) {
3363 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003364 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003365 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3366 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003367 if (PrivateVar->isInvalidDecl())
3368 return nullptr;
3369 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3370 }
3371 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003372}
3373
Samuel Antao4c8035b2016-12-12 18:00:20 +00003374/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3376
3377/// \brief Build step of the counter be used for codegen.
3378Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3379
3380/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003381struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003382 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003383 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003384 /// \brief This expression calculates the number of iterations in the loop.
3385 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003386 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003387 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003388 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003389 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003390 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003391 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003392 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003393 /// \brief This is step for the #CounterVar used to generate its update:
3394 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003395 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003396 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003397 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003398 /// \brief Source range of the loop init.
3399 SourceRange InitSrcRange;
3400 /// \brief Source range of the loop condition.
3401 SourceRange CondSrcRange;
3402 /// \brief Source range of the loop increment.
3403 SourceRange IncSrcRange;
3404};
3405
Alexey Bataev23b69422014-06-18 07:08:49 +00003406} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003407
Alexey Bataev9c821032015-04-30 04:23:23 +00003408void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3409 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3410 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003411 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3412 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003413 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3414 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003415 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3416 if (auto *D = ISC.GetLoopDecl()) {
3417 auto *VD = dyn_cast<VarDecl>(D);
3418 if (!VD) {
3419 if (auto *Private = IsOpenMPCapturedDecl(D))
3420 VD = Private;
3421 else {
3422 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3423 /*WithInit=*/false);
3424 VD = cast<VarDecl>(Ref->getDecl());
3425 }
3426 }
3427 DSAStack->addLoopControlVariable(D, VD);
3428 }
3429 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003430 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003431 }
3432}
3433
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003434/// \brief Called on a for stmt to check and extract its iteration space
3435/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003436static bool CheckOpenMPIterationSpace(
3437 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3438 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003439 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003440 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003441 LoopIterationSpace &ResultIterSpace,
3442 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003443 // OpenMP [2.6, Canonical Loop Form]
3444 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003445 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003446 if (!For) {
3447 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003448 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3449 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3450 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3451 if (NestedLoopCount > 1) {
3452 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3453 SemaRef.Diag(DSA.getConstructLoc(),
3454 diag::note_omp_collapse_ordered_expr)
3455 << 2 << CollapseLoopCountExpr->getSourceRange()
3456 << OrderedLoopCountExpr->getSourceRange();
3457 else if (CollapseLoopCountExpr)
3458 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3459 diag::note_omp_collapse_ordered_expr)
3460 << 0 << CollapseLoopCountExpr->getSourceRange();
3461 else
3462 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3463 diag::note_omp_collapse_ordered_expr)
3464 << 1 << OrderedLoopCountExpr->getSourceRange();
3465 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003466 return true;
3467 }
3468 assert(For->getBody());
3469
3470 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3471
3472 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003473 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003474 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003475 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003476
3477 bool HasErrors = false;
3478
3479 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003480 if (auto *LCDecl = ISC.GetLoopDecl()) {
3481 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003482
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003483 // OpenMP [2.6, Canonical Loop Form]
3484 // Var is one of the following:
3485 // A variable of signed or unsigned integer type.
3486 // For C++, a variable of a random access iterator type.
3487 // For C, a variable of a pointer type.
3488 auto VarType = LCDecl->getType().getNonReferenceType();
3489 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3490 !VarType->isPointerType() &&
3491 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3492 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3493 << SemaRef.getLangOpts().CPlusPlus;
3494 HasErrors = true;
3495 }
3496
3497 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3498 // a Construct
3499 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3500 // parallel for construct is (are) private.
3501 // The loop iteration variable in the associated for-loop of a simd
3502 // construct with just one associated for-loop is linear with a
3503 // constant-linear-step that is the increment of the associated for-loop.
3504 // Exclude loop var from the list of variables with implicitly defined data
3505 // sharing attributes.
3506 VarsWithImplicitDSA.erase(LCDecl);
3507
3508 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3509 // in a Construct, C/C++].
3510 // The loop iteration variable in the associated for-loop of a simd
3511 // construct with just one associated for-loop may be listed in a linear
3512 // clause with a constant-linear-step that is the increment of the
3513 // associated for-loop.
3514 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3515 // parallel for construct may be listed in a private or lastprivate clause.
3516 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3517 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3518 // declared in the loop and it is predetermined as a private.
3519 auto PredeterminedCKind =
3520 isOpenMPSimdDirective(DKind)
3521 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3522 : OMPC_private;
3523 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3524 DVar.CKind != PredeterminedCKind) ||
3525 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3526 isOpenMPDistributeDirective(DKind)) &&
3527 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3528 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3529 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3530 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3531 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3532 << getOpenMPClauseName(PredeterminedCKind);
3533 if (DVar.RefExpr == nullptr)
3534 DVar.CKind = PredeterminedCKind;
3535 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3536 HasErrors = true;
3537 } else if (LoopDeclRefExpr != nullptr) {
3538 // Make the loop iteration variable private (for worksharing constructs),
3539 // linear (for simd directives with the only one associated loop) or
3540 // lastprivate (for simd directives with several collapsed or ordered
3541 // loops).
3542 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003543 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3544 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003545 /*FromParent=*/false);
3546 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3547 }
3548
3549 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3550
3551 // Check test-expr.
3552 HasErrors |= ISC.CheckCond(For->getCond());
3553
3554 // Check incr-expr.
3555 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003556 }
3557
Alexander Musmana5f070a2014-10-01 06:03:56 +00003558 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003559 return HasErrors;
3560
Alexander Musmana5f070a2014-10-01 06:03:56 +00003561 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003562 ResultIterSpace.PreCond =
3563 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003564 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003565 DSA.getCurScope(),
3566 (isOpenMPWorksharingDirective(DKind) ||
3567 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3568 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003569 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003570 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003571 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3572 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3573 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3574 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3575 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3576 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3577
Alexey Bataev62dbb972015-04-22 11:59:37 +00003578 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3579 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003580 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003581 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003582 ResultIterSpace.CounterInit == nullptr ||
3583 ResultIterSpace.CounterStep == nullptr);
3584
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003585 return HasErrors;
3586}
3587
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003588/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003589static ExprResult
3590BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3591 ExprResult Start,
3592 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003593 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003594 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3595 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003596 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003597 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003598 VarRef.get()->getType())) {
3599 NewStart = SemaRef.PerformImplicitConversion(
3600 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3601 /*AllowExplicit=*/true);
3602 if (!NewStart.isUsable())
3603 return ExprError();
3604 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003605
3606 auto Init =
3607 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3608 return Init;
3609}
3610
Alexander Musmana5f070a2014-10-01 06:03:56 +00003611/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003612static ExprResult
3613BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3614 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3615 ExprResult Step, bool Subtract,
3616 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003617 // Add parentheses (for debugging purposes only).
3618 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3619 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3620 !Step.isUsable())
3621 return ExprError();
3622
Alexey Bataev5a3af132016-03-29 08:58:54 +00003623 ExprResult NewStep = Step;
3624 if (Captures)
3625 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003626 if (NewStep.isInvalid())
3627 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003628 ExprResult Update =
3629 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003630 if (!Update.isUsable())
3631 return ExprError();
3632
Alexey Bataevc0214e02016-02-16 12:13:49 +00003633 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3634 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003635 ExprResult NewStart = Start;
3636 if (Captures)
3637 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003638 if (NewStart.isInvalid())
3639 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003640
Alexey Bataevc0214e02016-02-16 12:13:49 +00003641 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3642 ExprResult SavedUpdate = Update;
3643 ExprResult UpdateVal;
3644 if (VarRef.get()->getType()->isOverloadableType() ||
3645 NewStart.get()->getType()->isOverloadableType() ||
3646 Update.get()->getType()->isOverloadableType()) {
3647 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3648 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3649 Update =
3650 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3651 if (Update.isUsable()) {
3652 UpdateVal =
3653 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3654 VarRef.get(), SavedUpdate.get());
3655 if (UpdateVal.isUsable()) {
3656 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3657 UpdateVal.get());
3658 }
3659 }
3660 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3661 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003662
Alexey Bataevc0214e02016-02-16 12:13:49 +00003663 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3664 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3665 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3666 NewStart.get(), SavedUpdate.get());
3667 if (!Update.isUsable())
3668 return ExprError();
3669
Alexey Bataev11481f52016-02-17 10:29:05 +00003670 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3671 VarRef.get()->getType())) {
3672 Update = SemaRef.PerformImplicitConversion(
3673 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3674 if (!Update.isUsable())
3675 return ExprError();
3676 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003677
3678 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3679 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003680 return Update;
3681}
3682
3683/// \brief Convert integer expression \a E to make it have at least \a Bits
3684/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003685static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003686 if (E == nullptr)
3687 return ExprError();
3688 auto &C = SemaRef.Context;
3689 QualType OldType = E->getType();
3690 unsigned HasBits = C.getTypeSize(OldType);
3691 if (HasBits >= Bits)
3692 return ExprResult(E);
3693 // OK to convert to signed, because new type has more bits than old.
3694 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3695 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3696 true);
3697}
3698
3699/// \brief Check if the given expression \a E is a constant integer that fits
3700/// into \a Bits bits.
3701static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3702 if (E == nullptr)
3703 return false;
3704 llvm::APSInt Result;
3705 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3706 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3707 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003708}
3709
Alexey Bataev5a3af132016-03-29 08:58:54 +00003710/// Build preinits statement for the given declarations.
3711static Stmt *buildPreInits(ASTContext &Context,
3712 SmallVectorImpl<Decl *> &PreInits) {
3713 if (!PreInits.empty()) {
3714 return new (Context) DeclStmt(
3715 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3716 SourceLocation(), SourceLocation());
3717 }
3718 return nullptr;
3719}
3720
3721/// Build preinits statement for the given declarations.
3722static Stmt *buildPreInits(ASTContext &Context,
3723 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3724 if (!Captures.empty()) {
3725 SmallVector<Decl *, 16> PreInits;
3726 for (auto &Pair : Captures)
3727 PreInits.push_back(Pair.second->getDecl());
3728 return buildPreInits(Context, PreInits);
3729 }
3730 return nullptr;
3731}
3732
3733/// Build postupdate expression for the given list of postupdates expressions.
3734static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3735 Expr *PostUpdate = nullptr;
3736 if (!PostUpdates.empty()) {
3737 for (auto *E : PostUpdates) {
3738 Expr *ConvE = S.BuildCStyleCastExpr(
3739 E->getExprLoc(),
3740 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3741 E->getExprLoc(), E)
3742 .get();
3743 PostUpdate = PostUpdate
3744 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3745 PostUpdate, ConvE)
3746 .get()
3747 : ConvE;
3748 }
3749 }
3750 return PostUpdate;
3751}
3752
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003753/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003754/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3755/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003756static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003757CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3758 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3759 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003760 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003761 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003762 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003763 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003764 // Found 'collapse' clause - calculate collapse number.
3765 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003766 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003767 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003768 }
3769 if (OrderedLoopCountExpr) {
3770 // Found 'ordered' clause - calculate collapse number.
3771 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003772 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3773 if (Result.getLimitedValue() < NestedLoopCount) {
3774 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3775 diag::err_omp_wrong_ordered_loop_count)
3776 << OrderedLoopCountExpr->getSourceRange();
3777 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3778 diag::note_collapse_loop_count)
3779 << CollapseLoopCountExpr->getSourceRange();
3780 }
3781 NestedLoopCount = Result.getLimitedValue();
3782 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003783 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003784 // This is helper routine for loop directives (e.g., 'for', 'simd',
3785 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003786 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003787 SmallVector<LoopIterationSpace, 4> IterSpaces;
3788 IterSpaces.resize(NestedLoopCount);
3789 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003791 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003792 NestedLoopCount, CollapseLoopCountExpr,
3793 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003794 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003795 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003796 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003797 // OpenMP [2.8.1, simd construct, Restrictions]
3798 // All loops associated with the construct must be perfectly nested; that
3799 // is, there must be no intervening code nor any OpenMP directive between
3800 // any two loops.
3801 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003802 }
3803
Alexander Musmana5f070a2014-10-01 06:03:56 +00003804 Built.clear(/* size */ NestedLoopCount);
3805
3806 if (SemaRef.CurContext->isDependentContext())
3807 return NestedLoopCount;
3808
3809 // An example of what is generated for the following code:
3810 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003811 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003812 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003813 // for (k = 0; k < NK; ++k)
3814 // for (j = J0; j < NJ; j+=2) {
3815 // <loop body>
3816 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003817 //
3818 // We generate the code below.
3819 // Note: the loop body may be outlined in CodeGen.
3820 // Note: some counters may be C++ classes, operator- is used to find number of
3821 // iterations and operator+= to calculate counter value.
3822 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3823 // or i64 is currently supported).
3824 //
3825 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3826 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3827 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3828 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3829 // // similar updates for vars in clauses (e.g. 'linear')
3830 // <loop body (using local i and j)>
3831 // }
3832 // i = NI; // assign final values of counters
3833 // j = NJ;
3834 //
3835
3836 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3837 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003838 // Precondition tests if there is at least one iteration (all conditions are
3839 // true).
3840 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003841 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003842 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003843 32 /* Bits */, SemaRef
3844 .PerformImplicitConversion(
3845 N0->IgnoreImpCasts(), N0->getType(),
3846 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003847 .get(),
3848 SemaRef);
3849 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003850 64 /* Bits */, SemaRef
3851 .PerformImplicitConversion(
3852 N0->IgnoreImpCasts(), N0->getType(),
3853 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003854 .get(),
3855 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003856
3857 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3858 return NestedLoopCount;
3859
3860 auto &C = SemaRef.Context;
3861 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3862
3863 Scope *CurScope = DSA.getCurScope();
3864 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003865 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003866 PreCond =
3867 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3868 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003869 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003870 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003871 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003872 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3873 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003874 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003875 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003876 SemaRef
3877 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3878 Sema::AA_Converting,
3879 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003880 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003881 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003882 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003883 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003884 SemaRef
3885 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3886 Sema::AA_Converting,
3887 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003888 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003889 }
3890
3891 // Choose either the 32-bit or 64-bit version.
3892 ExprResult LastIteration = LastIteration64;
3893 if (LastIteration32.isUsable() &&
3894 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3895 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3896 FitsInto(
3897 32 /* Bits */,
3898 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3899 LastIteration64.get(), SemaRef)))
3900 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003901 QualType VType = LastIteration.get()->getType();
3902 QualType RealVType = VType;
3903 QualType StrideVType = VType;
3904 if (isOpenMPTaskLoopDirective(DKind)) {
3905 VType =
3906 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3907 StrideVType =
3908 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3909 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003910
3911 if (!LastIteration.isUsable())
3912 return 0;
3913
3914 // Save the number of iterations.
3915 ExprResult NumIterations = LastIteration;
3916 {
3917 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003918 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
3919 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003920 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3921 if (!LastIteration.isUsable())
3922 return 0;
3923 }
3924
3925 // Calculate the last iteration number beforehand instead of doing this on
3926 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3927 llvm::APSInt Result;
3928 bool IsConstant =
3929 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3930 ExprResult CalcLastIteration;
3931 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003932 ExprResult SaveRef =
3933 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003934 LastIteration = SaveRef;
3935
3936 // Prepare SaveRef + 1.
3937 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003938 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003939 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3940 if (!NumIterations.isUsable())
3941 return 0;
3942 }
3943
3944 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3945
David Majnemer9d168222016-08-05 17:44:54 +00003946 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003947 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003948 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3949 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003950 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003951 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3952 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003953 SemaRef.AddInitializerToDecl(
3954 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3955 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3956
3957 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003958 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3959 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003960 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3961 /*DirectInit*/ false,
3962 /*TypeMayContainAuto*/ false);
3963
3964 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3965 // This will be used to implement clause 'lastprivate'.
3966 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003967 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3968 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003969 SemaRef.AddInitializerToDecl(
3970 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3971 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3972
3973 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00003974 VarDecl *STDecl =
3975 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3976 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003977 SemaRef.AddInitializerToDecl(
3978 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3979 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3980
3981 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00003982 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00003983 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3984 UB.get(), LastIteration.get());
3985 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3986 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3987 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3988 CondOp.get());
3989 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00003990
3991 // If we have a combined directive that combines 'distribute', 'for' or
3992 // 'simd' we need to be able to access the bounds of the schedule of the
3993 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
3994 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
3995 if (isOpenMPLoopBoundSharingDirective(DKind)) {
3996 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
3997
3998 // We expect to have at least 2 more parameters than the 'parallel'
3999 // directive does - the lower and upper bounds of the previous schedule.
4000 assert(CD->getNumParams() >= 4 &&
4001 "Unexpected number of parameters in loop combined directive");
4002
4003 // Set the proper type for the bounds given what we learned from the
4004 // enclosed loops.
4005 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4006 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4007
4008 // Previous lower and upper bounds are obtained from the region
4009 // parameters.
4010 PrevLB =
4011 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4012 PrevUB =
4013 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4014 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004015 }
4016
4017 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004018 ExprResult IV;
4019 ExprResult Init;
4020 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004021 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4022 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004023 Expr *RHS =
4024 (isOpenMPWorksharingDirective(DKind) ||
4025 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4026 ? LB.get()
4027 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004028 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4029 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004030 }
4031
Alexander Musmanc6388682014-12-15 07:07:06 +00004032 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004033 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004034 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004035 (isOpenMPWorksharingDirective(DKind) ||
4036 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004037 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4038 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4039 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004040
4041 // Loop increment (IV = IV + 1)
4042 SourceLocation IncLoc;
4043 ExprResult Inc =
4044 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4045 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4046 if (!Inc.isUsable())
4047 return 0;
4048 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004049 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4050 if (!Inc.isUsable())
4051 return 0;
4052
4053 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4054 // Used for directives with static scheduling.
4055 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004056 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4057 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004058 // LB + ST
4059 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4060 if (!NextLB.isUsable())
4061 return 0;
4062 // LB = LB + ST
4063 NextLB =
4064 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4065 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4066 if (!NextLB.isUsable())
4067 return 0;
4068 // UB + ST
4069 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4070 if (!NextUB.isUsable())
4071 return 0;
4072 // UB = UB + ST
4073 NextUB =
4074 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4075 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4076 if (!NextUB.isUsable())
4077 return 0;
4078 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004079
4080 // Build updates and final values of the loop counters.
4081 bool HasErrors = false;
4082 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004083 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004084 Built.Updates.resize(NestedLoopCount);
4085 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004086 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004087 {
4088 ExprResult Div;
4089 // Go from inner nested loop to outer.
4090 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4091 LoopIterationSpace &IS = IterSpaces[Cnt];
4092 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4093 // Build: Iter = (IV / Div) % IS.NumIters
4094 // where Div is product of previous iterations' IS.NumIters.
4095 ExprResult Iter;
4096 if (Div.isUsable()) {
4097 Iter =
4098 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4099 } else {
4100 Iter = IV;
4101 assert((Cnt == (int)NestedLoopCount - 1) &&
4102 "unusable div expected on first iteration only");
4103 }
4104
4105 if (Cnt != 0 && Iter.isUsable())
4106 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4107 IS.NumIterations);
4108 if (!Iter.isUsable()) {
4109 HasErrors = true;
4110 break;
4111 }
4112
Alexey Bataev39f915b82015-05-08 10:41:21 +00004113 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004114 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4115 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4116 IS.CounterVar->getExprLoc(),
4117 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004118 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004119 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004120 if (!Init.isUsable()) {
4121 HasErrors = true;
4122 break;
4123 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004124 ExprResult Update = BuildCounterUpdate(
4125 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4126 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004127 if (!Update.isUsable()) {
4128 HasErrors = true;
4129 break;
4130 }
4131
4132 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4133 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004134 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004135 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004136 if (!Final.isUsable()) {
4137 HasErrors = true;
4138 break;
4139 }
4140
4141 // Build Div for the next iteration: Div <- Div * IS.NumIters
4142 if (Cnt != 0) {
4143 if (Div.isUnset())
4144 Div = IS.NumIterations;
4145 else
4146 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4147 IS.NumIterations);
4148
4149 // Add parentheses (for debugging purposes only).
4150 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004151 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004152 if (!Div.isUsable()) {
4153 HasErrors = true;
4154 break;
4155 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004156 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004157 }
4158 if (!Update.isUsable() || !Final.isUsable()) {
4159 HasErrors = true;
4160 break;
4161 }
4162 // Save results
4163 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004164 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004165 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004166 Built.Updates[Cnt] = Update.get();
4167 Built.Finals[Cnt] = Final.get();
4168 }
4169 }
4170
4171 if (HasErrors)
4172 return 0;
4173
4174 // Save results
4175 Built.IterationVarRef = IV.get();
4176 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004177 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004178 Built.CalcLastIteration =
4179 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004180 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004181 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004182 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183 Built.Init = Init.get();
4184 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004185 Built.LB = LB.get();
4186 Built.UB = UB.get();
4187 Built.IL = IL.get();
4188 Built.ST = ST.get();
4189 Built.EUB = EUB.get();
4190 Built.NLB = NextLB.get();
4191 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004192 Built.PrevLB = PrevLB.get();
4193 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004194
Alexey Bataev8b427062016-05-25 12:36:08 +00004195 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4196 // Fill data for doacross depend clauses.
4197 for (auto Pair : DSA.getDoacrossDependClauses()) {
4198 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4199 Pair.first->setCounterValue(CounterVal);
4200 else {
4201 if (NestedLoopCount != Pair.second.size() ||
4202 NestedLoopCount != LoopMultipliers.size() + 1) {
4203 // Erroneous case - clause has some problems.
4204 Pair.first->setCounterValue(CounterVal);
4205 continue;
4206 }
4207 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4208 auto I = Pair.second.rbegin();
4209 auto IS = IterSpaces.rbegin();
4210 auto ILM = LoopMultipliers.rbegin();
4211 Expr *UpCounterVal = CounterVal;
4212 Expr *Multiplier = nullptr;
4213 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4214 if (I->first) {
4215 assert(IS->CounterStep);
4216 Expr *NormalizedOffset =
4217 SemaRef
4218 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4219 I->first, IS->CounterStep)
4220 .get();
4221 if (Multiplier) {
4222 NormalizedOffset =
4223 SemaRef
4224 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4225 NormalizedOffset, Multiplier)
4226 .get();
4227 }
4228 assert(I->second == OO_Plus || I->second == OO_Minus);
4229 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004230 UpCounterVal = SemaRef
4231 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4232 UpCounterVal, NormalizedOffset)
4233 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004234 }
4235 Multiplier = *ILM;
4236 ++I;
4237 ++IS;
4238 ++ILM;
4239 }
4240 Pair.first->setCounterValue(UpCounterVal);
4241 }
4242 }
4243
Alexey Bataevabfc0692014-06-25 06:52:00 +00004244 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004245}
4246
Alexey Bataev10e775f2015-07-30 11:36:16 +00004247static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004248 auto CollapseClauses =
4249 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4250 if (CollapseClauses.begin() != CollapseClauses.end())
4251 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004252 return nullptr;
4253}
4254
Alexey Bataev10e775f2015-07-30 11:36:16 +00004255static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004256 auto OrderedClauses =
4257 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4258 if (OrderedClauses.begin() != OrderedClauses.end())
4259 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004260 return nullptr;
4261}
4262
Kelvin Lic5609492016-07-15 04:39:07 +00004263static bool checkSimdlenSafelenSpecified(Sema &S,
4264 const ArrayRef<OMPClause *> Clauses) {
4265 OMPSafelenClause *Safelen = nullptr;
4266 OMPSimdlenClause *Simdlen = nullptr;
4267
4268 for (auto *Clause : Clauses) {
4269 if (Clause->getClauseKind() == OMPC_safelen)
4270 Safelen = cast<OMPSafelenClause>(Clause);
4271 else if (Clause->getClauseKind() == OMPC_simdlen)
4272 Simdlen = cast<OMPSimdlenClause>(Clause);
4273 if (Safelen && Simdlen)
4274 break;
4275 }
4276
4277 if (Simdlen && Safelen) {
4278 llvm::APSInt SimdlenRes, SafelenRes;
4279 auto SimdlenLength = Simdlen->getSimdlen();
4280 auto SafelenLength = Safelen->getSafelen();
4281 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4282 SimdlenLength->isInstantiationDependent() ||
4283 SimdlenLength->containsUnexpandedParameterPack())
4284 return false;
4285 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4286 SafelenLength->isInstantiationDependent() ||
4287 SafelenLength->containsUnexpandedParameterPack())
4288 return false;
4289 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4290 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4291 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4292 // If both simdlen and safelen clauses are specified, the value of the
4293 // simdlen parameter must be less than or equal to the value of the safelen
4294 // parameter.
4295 if (SimdlenRes > SafelenRes) {
4296 S.Diag(SimdlenLength->getExprLoc(),
4297 diag::err_omp_wrong_simdlen_safelen_values)
4298 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4299 return true;
4300 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004301 }
4302 return false;
4303}
4304
Alexey Bataev4acb8592014-07-07 13:01:15 +00004305StmtResult Sema::ActOnOpenMPSimdDirective(
4306 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4307 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004308 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004309 if (!AStmt)
4310 return StmtError();
4311
4312 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004313 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4315 // define the nested loops number.
4316 unsigned NestedLoopCount = CheckOpenMPLoop(
4317 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4318 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004319 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004320 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004321
Alexander Musmana5f070a2014-10-01 06:03:56 +00004322 assert((CurContext->isDependentContext() || B.builtAll()) &&
4323 "omp simd loop exprs were not built");
4324
Alexander Musman3276a272015-03-21 10:12:56 +00004325 if (!CurContext->isDependentContext()) {
4326 // Finalize the clauses that need pre-built expressions for CodeGen.
4327 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004328 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004329 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004330 B.NumIterations, *this, CurScope,
4331 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004332 return StmtError();
4333 }
4334 }
4335
Kelvin Lic5609492016-07-15 04:39:07 +00004336 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004337 return StmtError();
4338
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004339 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004340 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4341 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004342}
4343
Alexey Bataev4acb8592014-07-07 13:01:15 +00004344StmtResult Sema::ActOnOpenMPForDirective(
4345 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4346 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004347 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004348 if (!AStmt)
4349 return StmtError();
4350
4351 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004352 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004353 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4354 // define the nested loops number.
4355 unsigned NestedLoopCount = CheckOpenMPLoop(
4356 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4357 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004358 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004359 return StmtError();
4360
Alexander Musmana5f070a2014-10-01 06:03:56 +00004361 assert((CurContext->isDependentContext() || B.builtAll()) &&
4362 "omp for loop exprs were not built");
4363
Alexey Bataev54acd402015-08-04 11:18:19 +00004364 if (!CurContext->isDependentContext()) {
4365 // Finalize the clauses that need pre-built expressions for CodeGen.
4366 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004367 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004368 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004369 B.NumIterations, *this, CurScope,
4370 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004371 return StmtError();
4372 }
4373 }
4374
Alexey Bataevf29276e2014-06-18 04:14:57 +00004375 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004376 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004377 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004378}
4379
Alexander Musmanf82886e2014-09-18 05:12:34 +00004380StmtResult Sema::ActOnOpenMPForSimdDirective(
4381 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4382 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004383 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004384 if (!AStmt)
4385 return StmtError();
4386
4387 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004388 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004389 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4390 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004391 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004392 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4393 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4394 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004395 if (NestedLoopCount == 0)
4396 return StmtError();
4397
Alexander Musmanc6388682014-12-15 07:07:06 +00004398 assert((CurContext->isDependentContext() || B.builtAll()) &&
4399 "omp for simd loop exprs were not built");
4400
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004401 if (!CurContext->isDependentContext()) {
4402 // Finalize the clauses that need pre-built expressions for CodeGen.
4403 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004404 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004405 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004406 B.NumIterations, *this, CurScope,
4407 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004408 return StmtError();
4409 }
4410 }
4411
Kelvin Lic5609492016-07-15 04:39:07 +00004412 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004413 return StmtError();
4414
Alexander Musmanf82886e2014-09-18 05:12:34 +00004415 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004416 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4417 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004418}
4419
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004420StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4421 Stmt *AStmt,
4422 SourceLocation StartLoc,
4423 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004424 if (!AStmt)
4425 return StmtError();
4426
4427 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004428 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004429 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004430 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004431 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004432 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004433 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004434 return StmtError();
4435 // All associated statements must be '#pragma omp section' except for
4436 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004437 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004438 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4439 if (SectionStmt)
4440 Diag(SectionStmt->getLocStart(),
4441 diag::err_omp_sections_substmt_not_section);
4442 return StmtError();
4443 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004444 cast<OMPSectionDirective>(SectionStmt)
4445 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004446 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004447 } else {
4448 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4449 return StmtError();
4450 }
4451
4452 getCurFunction()->setHasBranchProtectedScope();
4453
Alexey Bataev25e5b442015-09-15 12:52:43 +00004454 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4455 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004456}
4457
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004458StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4459 SourceLocation StartLoc,
4460 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004461 if (!AStmt)
4462 return StmtError();
4463
4464 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004465
4466 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004467 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004468
Alexey Bataev25e5b442015-09-15 12:52:43 +00004469 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4470 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004471}
4472
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004473StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4474 Stmt *AStmt,
4475 SourceLocation StartLoc,
4476 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004477 if (!AStmt)
4478 return StmtError();
4479
4480 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004481
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004482 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004483
Alexey Bataev3255bf32015-01-19 05:20:46 +00004484 // OpenMP [2.7.3, single Construct, Restrictions]
4485 // The copyprivate clause must not be used with the nowait clause.
4486 OMPClause *Nowait = nullptr;
4487 OMPClause *Copyprivate = nullptr;
4488 for (auto *Clause : Clauses) {
4489 if (Clause->getClauseKind() == OMPC_nowait)
4490 Nowait = Clause;
4491 else if (Clause->getClauseKind() == OMPC_copyprivate)
4492 Copyprivate = Clause;
4493 if (Copyprivate && Nowait) {
4494 Diag(Copyprivate->getLocStart(),
4495 diag::err_omp_single_copyprivate_with_nowait);
4496 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4497 return StmtError();
4498 }
4499 }
4500
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004501 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4502}
4503
Alexander Musman80c22892014-07-17 08:54:58 +00004504StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4505 SourceLocation StartLoc,
4506 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004507 if (!AStmt)
4508 return StmtError();
4509
4510 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004511
4512 getCurFunction()->setHasBranchProtectedScope();
4513
4514 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4515}
4516
Alexey Bataev28c75412015-12-15 08:19:24 +00004517StmtResult Sema::ActOnOpenMPCriticalDirective(
4518 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4519 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004520 if (!AStmt)
4521 return StmtError();
4522
4523 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004524
Alexey Bataev28c75412015-12-15 08:19:24 +00004525 bool ErrorFound = false;
4526 llvm::APSInt Hint;
4527 SourceLocation HintLoc;
4528 bool DependentHint = false;
4529 for (auto *C : Clauses) {
4530 if (C->getClauseKind() == OMPC_hint) {
4531 if (!DirName.getName()) {
4532 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4533 ErrorFound = true;
4534 }
4535 Expr *E = cast<OMPHintClause>(C)->getHint();
4536 if (E->isTypeDependent() || E->isValueDependent() ||
4537 E->isInstantiationDependent())
4538 DependentHint = true;
4539 else {
4540 Hint = E->EvaluateKnownConstInt(Context);
4541 HintLoc = C->getLocStart();
4542 }
4543 }
4544 }
4545 if (ErrorFound)
4546 return StmtError();
4547 auto Pair = DSAStack->getCriticalWithHint(DirName);
4548 if (Pair.first && DirName.getName() && !DependentHint) {
4549 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4550 Diag(StartLoc, diag::err_omp_critical_with_hint);
4551 if (HintLoc.isValid()) {
4552 Diag(HintLoc, diag::note_omp_critical_hint_here)
4553 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4554 } else
4555 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4556 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4557 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4558 << 1
4559 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4560 /*Radix=*/10, /*Signed=*/false);
4561 } else
4562 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4563 }
4564 }
4565
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004566 getCurFunction()->setHasBranchProtectedScope();
4567
Alexey Bataev28c75412015-12-15 08:19:24 +00004568 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4569 Clauses, AStmt);
4570 if (!Pair.first && DirName.getName() && !DependentHint)
4571 DSAStack->addCriticalWithHint(Dir, Hint);
4572 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004573}
4574
Alexey Bataev4acb8592014-07-07 13:01:15 +00004575StmtResult Sema::ActOnOpenMPParallelForDirective(
4576 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4577 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004578 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004579 if (!AStmt)
4580 return StmtError();
4581
Alexey Bataev4acb8592014-07-07 13:01:15 +00004582 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4583 // 1.2.2 OpenMP Language Terminology
4584 // Structured block - An executable statement with a single entry at the
4585 // top and a single exit at the bottom.
4586 // The point of exit cannot be a branch out of the structured block.
4587 // longjmp() and throw() must not violate the entry/exit criteria.
4588 CS->getCapturedDecl()->setNothrow();
4589
Alexander Musmanc6388682014-12-15 07:07:06 +00004590 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004591 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4592 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004593 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004594 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4595 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4596 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004597 if (NestedLoopCount == 0)
4598 return StmtError();
4599
Alexander Musmana5f070a2014-10-01 06:03:56 +00004600 assert((CurContext->isDependentContext() || B.builtAll()) &&
4601 "omp parallel for loop exprs were not built");
4602
Alexey Bataev54acd402015-08-04 11:18:19 +00004603 if (!CurContext->isDependentContext()) {
4604 // Finalize the clauses that need pre-built expressions for CodeGen.
4605 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004606 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004607 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004608 B.NumIterations, *this, CurScope,
4609 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004610 return StmtError();
4611 }
4612 }
4613
Alexey Bataev4acb8592014-07-07 13:01:15 +00004614 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004615 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004616 NestedLoopCount, Clauses, AStmt, B,
4617 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004618}
4619
Alexander Musmane4e893b2014-09-23 09:33:00 +00004620StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4622 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004623 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004624 if (!AStmt)
4625 return StmtError();
4626
Alexander Musmane4e893b2014-09-23 09:33:00 +00004627 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4628 // 1.2.2 OpenMP Language Terminology
4629 // Structured block - An executable statement with a single entry at the
4630 // top and a single exit at the bottom.
4631 // The point of exit cannot be a branch out of the structured block.
4632 // longjmp() and throw() must not violate the entry/exit criteria.
4633 CS->getCapturedDecl()->setNothrow();
4634
Alexander Musmanc6388682014-12-15 07:07:06 +00004635 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004636 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4637 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004638 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004639 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4640 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4641 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004642 if (NestedLoopCount == 0)
4643 return StmtError();
4644
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004645 if (!CurContext->isDependentContext()) {
4646 // Finalize the clauses that need pre-built expressions for CodeGen.
4647 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004648 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004649 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004650 B.NumIterations, *this, CurScope,
4651 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004652 return StmtError();
4653 }
4654 }
4655
Kelvin Lic5609492016-07-15 04:39:07 +00004656 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004657 return StmtError();
4658
Alexander Musmane4e893b2014-09-23 09:33:00 +00004659 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004660 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004661 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004662}
4663
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004664StmtResult
4665Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4666 Stmt *AStmt, SourceLocation StartLoc,
4667 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004668 if (!AStmt)
4669 return StmtError();
4670
4671 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004672 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004673 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004674 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004675 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004676 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004677 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004678 return StmtError();
4679 // All associated statements must be '#pragma omp section' except for
4680 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004681 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004682 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4683 if (SectionStmt)
4684 Diag(SectionStmt->getLocStart(),
4685 diag::err_omp_parallel_sections_substmt_not_section);
4686 return StmtError();
4687 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004688 cast<OMPSectionDirective>(SectionStmt)
4689 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004690 }
4691 } else {
4692 Diag(AStmt->getLocStart(),
4693 diag::err_omp_parallel_sections_not_compound_stmt);
4694 return StmtError();
4695 }
4696
4697 getCurFunction()->setHasBranchProtectedScope();
4698
Alexey Bataev25e5b442015-09-15 12:52:43 +00004699 return OMPParallelSectionsDirective::Create(
4700 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004701}
4702
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004703StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4704 Stmt *AStmt, SourceLocation StartLoc,
4705 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004706 if (!AStmt)
4707 return StmtError();
4708
David Majnemer9d168222016-08-05 17:44:54 +00004709 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004710 // 1.2.2 OpenMP Language Terminology
4711 // Structured block - An executable statement with a single entry at the
4712 // top and a single exit at the bottom.
4713 // The point of exit cannot be a branch out of the structured block.
4714 // longjmp() and throw() must not violate the entry/exit criteria.
4715 CS->getCapturedDecl()->setNothrow();
4716
4717 getCurFunction()->setHasBranchProtectedScope();
4718
Alexey Bataev25e5b442015-09-15 12:52:43 +00004719 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4720 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004721}
4722
Alexey Bataev68446b72014-07-18 07:47:19 +00004723StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4724 SourceLocation EndLoc) {
4725 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4726}
4727
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004728StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4729 SourceLocation EndLoc) {
4730 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4731}
4732
Alexey Bataev2df347a2014-07-18 10:17:07 +00004733StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4734 SourceLocation EndLoc) {
4735 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4736}
4737
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004738StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4739 SourceLocation StartLoc,
4740 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004741 if (!AStmt)
4742 return StmtError();
4743
4744 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004745
4746 getCurFunction()->setHasBranchProtectedScope();
4747
4748 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4749}
4750
Alexey Bataev6125da92014-07-21 11:26:11 +00004751StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4752 SourceLocation StartLoc,
4753 SourceLocation EndLoc) {
4754 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4755 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4756}
4757
Alexey Bataev346265e2015-09-25 10:37:12 +00004758StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4759 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004760 SourceLocation StartLoc,
4761 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004762 OMPClause *DependFound = nullptr;
4763 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004764 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004765 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004766 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004767 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004768 for (auto *C : Clauses) {
4769 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4770 DependFound = C;
4771 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4772 if (DependSourceClause) {
4773 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4774 << getOpenMPDirectiveName(OMPD_ordered)
4775 << getOpenMPClauseName(OMPC_depend) << 2;
4776 ErrorFound = true;
4777 } else
4778 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004779 if (DependSinkClause) {
4780 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4781 << 0;
4782 ErrorFound = true;
4783 }
4784 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4785 if (DependSourceClause) {
4786 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4787 << 1;
4788 ErrorFound = true;
4789 }
4790 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004791 }
4792 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004793 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004794 else if (C->getClauseKind() == OMPC_simd)
4795 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004796 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004797 if (!ErrorFound && !SC &&
4798 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004799 // OpenMP [2.8.1,simd Construct, Restrictions]
4800 // An ordered construct with the simd clause is the only OpenMP construct
4801 // that can appear in the simd region.
4802 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004803 ErrorFound = true;
4804 } else if (DependFound && (TC || SC)) {
4805 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4806 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4807 ErrorFound = true;
4808 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4809 Diag(DependFound->getLocStart(),
4810 diag::err_omp_ordered_directive_without_param);
4811 ErrorFound = true;
4812 } else if (TC || Clauses.empty()) {
4813 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4814 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4815 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4816 << (TC != nullptr);
4817 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4818 ErrorFound = true;
4819 }
4820 }
4821 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004822 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004823
4824 if (AStmt) {
4825 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4826
4827 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004828 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004829
4830 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004831}
4832
Alexey Bataev1d160b12015-03-13 12:27:31 +00004833namespace {
4834/// \brief Helper class for checking expression in 'omp atomic [update]'
4835/// construct.
4836class OpenMPAtomicUpdateChecker {
4837 /// \brief Error results for atomic update expressions.
4838 enum ExprAnalysisErrorCode {
4839 /// \brief A statement is not an expression statement.
4840 NotAnExpression,
4841 /// \brief Expression is not builtin binary or unary operation.
4842 NotABinaryOrUnaryExpression,
4843 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4844 NotAnUnaryIncDecExpression,
4845 /// \brief An expression is not of scalar type.
4846 NotAScalarType,
4847 /// \brief A binary operation is not an assignment operation.
4848 NotAnAssignmentOp,
4849 /// \brief RHS part of the binary operation is not a binary expression.
4850 NotABinaryExpression,
4851 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4852 /// expression.
4853 NotABinaryOperator,
4854 /// \brief RHS binary operation does not have reference to the updated LHS
4855 /// part.
4856 NotAnUpdateExpression,
4857 /// \brief No errors is found.
4858 NoError
4859 };
4860 /// \brief Reference to Sema.
4861 Sema &SemaRef;
4862 /// \brief A location for note diagnostics (when error is found).
4863 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004864 /// \brief 'x' lvalue part of the source atomic expression.
4865 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004866 /// \brief 'expr' rvalue part of the source atomic expression.
4867 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004868 /// \brief Helper expression of the form
4869 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4870 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4871 Expr *UpdateExpr;
4872 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4873 /// important for non-associative operations.
4874 bool IsXLHSInRHSPart;
4875 BinaryOperatorKind Op;
4876 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004877 /// \brief true if the source expression is a postfix unary operation, false
4878 /// if it is a prefix unary operation.
4879 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004880
4881public:
4882 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004883 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004884 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004885 /// \brief Check specified statement that it is suitable for 'atomic update'
4886 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004887 /// expression. If DiagId and NoteId == 0, then only check is performed
4888 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004889 /// \param DiagId Diagnostic which should be emitted if error is found.
4890 /// \param NoteId Diagnostic note for the main error message.
4891 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004892 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004893 /// \brief Return the 'x' lvalue part of the source atomic expression.
4894 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004895 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4896 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004897 /// \brief Return the update expression used in calculation of the updated
4898 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4899 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4900 Expr *getUpdateExpr() const { return UpdateExpr; }
4901 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4902 /// false otherwise.
4903 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4904
Alexey Bataevb78ca832015-04-01 03:33:17 +00004905 /// \brief true if the source expression is a postfix unary operation, false
4906 /// if it is a prefix unary operation.
4907 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4908
Alexey Bataev1d160b12015-03-13 12:27:31 +00004909private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004910 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4911 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004912};
4913} // namespace
4914
4915bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4916 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4917 ExprAnalysisErrorCode ErrorFound = NoError;
4918 SourceLocation ErrorLoc, NoteLoc;
4919 SourceRange ErrorRange, NoteRange;
4920 // Allowed constructs are:
4921 // x = x binop expr;
4922 // x = expr binop x;
4923 if (AtomicBinOp->getOpcode() == BO_Assign) {
4924 X = AtomicBinOp->getLHS();
4925 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4926 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4927 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4928 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4929 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004930 Op = AtomicInnerBinOp->getOpcode();
4931 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004932 auto *LHS = AtomicInnerBinOp->getLHS();
4933 auto *RHS = AtomicInnerBinOp->getRHS();
4934 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4935 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4936 /*Canonical=*/true);
4937 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4938 /*Canonical=*/true);
4939 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4940 /*Canonical=*/true);
4941 if (XId == LHSId) {
4942 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004943 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004944 } else if (XId == RHSId) {
4945 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004946 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004947 } else {
4948 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4949 ErrorRange = AtomicInnerBinOp->getSourceRange();
4950 NoteLoc = X->getExprLoc();
4951 NoteRange = X->getSourceRange();
4952 ErrorFound = NotAnUpdateExpression;
4953 }
4954 } else {
4955 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4956 ErrorRange = AtomicInnerBinOp->getSourceRange();
4957 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4958 NoteRange = SourceRange(NoteLoc, NoteLoc);
4959 ErrorFound = NotABinaryOperator;
4960 }
4961 } else {
4962 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4963 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4964 ErrorFound = NotABinaryExpression;
4965 }
4966 } else {
4967 ErrorLoc = AtomicBinOp->getExprLoc();
4968 ErrorRange = AtomicBinOp->getSourceRange();
4969 NoteLoc = AtomicBinOp->getOperatorLoc();
4970 NoteRange = SourceRange(NoteLoc, NoteLoc);
4971 ErrorFound = NotAnAssignmentOp;
4972 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004973 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004974 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4975 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4976 return true;
4977 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004978 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004979 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004980}
4981
4982bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4983 unsigned NoteId) {
4984 ExprAnalysisErrorCode ErrorFound = NoError;
4985 SourceLocation ErrorLoc, NoteLoc;
4986 SourceRange ErrorRange, NoteRange;
4987 // Allowed constructs are:
4988 // x++;
4989 // x--;
4990 // ++x;
4991 // --x;
4992 // x binop= expr;
4993 // x = x binop expr;
4994 // x = expr binop x;
4995 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4996 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4997 if (AtomicBody->getType()->isScalarType() ||
4998 AtomicBody->isInstantiationDependent()) {
4999 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5000 AtomicBody->IgnoreParenImpCasts())) {
5001 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005002 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005003 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005004 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005005 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005006 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005007 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005008 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5009 AtomicBody->IgnoreParenImpCasts())) {
5010 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005011 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005012 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005013 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5014 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005015 // Check for Unary Operation
5016 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005017 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005018 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5019 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005020 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005021 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5022 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005023 } else {
5024 ErrorFound = NotAnUnaryIncDecExpression;
5025 ErrorLoc = AtomicUnaryOp->getExprLoc();
5026 ErrorRange = AtomicUnaryOp->getSourceRange();
5027 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5028 NoteRange = SourceRange(NoteLoc, NoteLoc);
5029 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005030 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005031 ErrorFound = NotABinaryOrUnaryExpression;
5032 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5033 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5034 }
5035 } else {
5036 ErrorFound = NotAScalarType;
5037 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5038 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5039 }
5040 } else {
5041 ErrorFound = NotAnExpression;
5042 NoteLoc = ErrorLoc = S->getLocStart();
5043 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5044 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005045 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005046 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5047 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5048 return true;
5049 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005050 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005051 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005052 // Build an update expression of form 'OpaqueValueExpr(x) binop
5053 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5054 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5055 auto *OVEX = new (SemaRef.getASTContext())
5056 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5057 auto *OVEExpr = new (SemaRef.getASTContext())
5058 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5059 auto Update =
5060 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5061 IsXLHSInRHSPart ? OVEExpr : OVEX);
5062 if (Update.isInvalid())
5063 return true;
5064 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5065 Sema::AA_Casting);
5066 if (Update.isInvalid())
5067 return true;
5068 UpdateExpr = Update.get();
5069 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005070 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005071}
5072
Alexey Bataev0162e452014-07-22 10:10:35 +00005073StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5074 Stmt *AStmt,
5075 SourceLocation StartLoc,
5076 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005077 if (!AStmt)
5078 return StmtError();
5079
David Majnemer9d168222016-08-05 17:44:54 +00005080 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005081 // 1.2.2 OpenMP Language Terminology
5082 // Structured block - An executable statement with a single entry at the
5083 // top and a single exit at the bottom.
5084 // The point of exit cannot be a branch out of the structured block.
5085 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005086 OpenMPClauseKind AtomicKind = OMPC_unknown;
5087 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005088 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005089 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005090 C->getClauseKind() == OMPC_update ||
5091 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005092 if (AtomicKind != OMPC_unknown) {
5093 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5094 << SourceRange(C->getLocStart(), C->getLocEnd());
5095 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5096 << getOpenMPClauseName(AtomicKind);
5097 } else {
5098 AtomicKind = C->getClauseKind();
5099 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005100 }
5101 }
5102 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005103
Alexey Bataev459dec02014-07-24 06:46:57 +00005104 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005105 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5106 Body = EWC->getSubExpr();
5107
Alexey Bataev62cec442014-11-18 10:14:22 +00005108 Expr *X = nullptr;
5109 Expr *V = nullptr;
5110 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005111 Expr *UE = nullptr;
5112 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005113 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005114 // OpenMP [2.12.6, atomic Construct]
5115 // In the next expressions:
5116 // * x and v (as applicable) are both l-value expressions with scalar type.
5117 // * During the execution of an atomic region, multiple syntactic
5118 // occurrences of x must designate the same storage location.
5119 // * Neither of v and expr (as applicable) may access the storage location
5120 // designated by x.
5121 // * Neither of x and expr (as applicable) may access the storage location
5122 // designated by v.
5123 // * expr is an expression with scalar type.
5124 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5125 // * binop, binop=, ++, and -- are not overloaded operators.
5126 // * The expression x binop expr must be numerically equivalent to x binop
5127 // (expr). This requirement is satisfied if the operators in expr have
5128 // precedence greater than binop, or by using parentheses around expr or
5129 // subexpressions of expr.
5130 // * The expression expr binop x must be numerically equivalent to (expr)
5131 // binop x. This requirement is satisfied if the operators in expr have
5132 // precedence equal to or greater than binop, or by using parentheses around
5133 // expr or subexpressions of expr.
5134 // * For forms that allow multiple occurrences of x, the number of times
5135 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005136 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005137 enum {
5138 NotAnExpression,
5139 NotAnAssignmentOp,
5140 NotAScalarType,
5141 NotAnLValue,
5142 NoError
5143 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005144 SourceLocation ErrorLoc, NoteLoc;
5145 SourceRange ErrorRange, NoteRange;
5146 // If clause is read:
5147 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005148 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5149 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005150 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5151 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5152 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5153 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5154 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5155 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5156 if (!X->isLValue() || !V->isLValue()) {
5157 auto NotLValueExpr = X->isLValue() ? V : X;
5158 ErrorFound = NotAnLValue;
5159 ErrorLoc = AtomicBinOp->getExprLoc();
5160 ErrorRange = AtomicBinOp->getSourceRange();
5161 NoteLoc = NotLValueExpr->getExprLoc();
5162 NoteRange = NotLValueExpr->getSourceRange();
5163 }
5164 } else if (!X->isInstantiationDependent() ||
5165 !V->isInstantiationDependent()) {
5166 auto NotScalarExpr =
5167 (X->isInstantiationDependent() || X->getType()->isScalarType())
5168 ? V
5169 : X;
5170 ErrorFound = NotAScalarType;
5171 ErrorLoc = AtomicBinOp->getExprLoc();
5172 ErrorRange = AtomicBinOp->getSourceRange();
5173 NoteLoc = NotScalarExpr->getExprLoc();
5174 NoteRange = NotScalarExpr->getSourceRange();
5175 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005176 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005177 ErrorFound = NotAnAssignmentOp;
5178 ErrorLoc = AtomicBody->getExprLoc();
5179 ErrorRange = AtomicBody->getSourceRange();
5180 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5181 : AtomicBody->getExprLoc();
5182 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5183 : AtomicBody->getSourceRange();
5184 }
5185 } else {
5186 ErrorFound = NotAnExpression;
5187 NoteLoc = ErrorLoc = Body->getLocStart();
5188 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005189 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005190 if (ErrorFound != NoError) {
5191 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5192 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005193 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5194 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005195 return StmtError();
5196 } else if (CurContext->isDependentContext())
5197 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005198 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005199 enum {
5200 NotAnExpression,
5201 NotAnAssignmentOp,
5202 NotAScalarType,
5203 NotAnLValue,
5204 NoError
5205 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005206 SourceLocation ErrorLoc, NoteLoc;
5207 SourceRange ErrorRange, NoteRange;
5208 // If clause is write:
5209 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005210 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5211 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005212 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5213 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005214 X = AtomicBinOp->getLHS();
5215 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005216 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5217 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5218 if (!X->isLValue()) {
5219 ErrorFound = NotAnLValue;
5220 ErrorLoc = AtomicBinOp->getExprLoc();
5221 ErrorRange = AtomicBinOp->getSourceRange();
5222 NoteLoc = X->getExprLoc();
5223 NoteRange = X->getSourceRange();
5224 }
5225 } else if (!X->isInstantiationDependent() ||
5226 !E->isInstantiationDependent()) {
5227 auto NotScalarExpr =
5228 (X->isInstantiationDependent() || X->getType()->isScalarType())
5229 ? E
5230 : X;
5231 ErrorFound = NotAScalarType;
5232 ErrorLoc = AtomicBinOp->getExprLoc();
5233 ErrorRange = AtomicBinOp->getSourceRange();
5234 NoteLoc = NotScalarExpr->getExprLoc();
5235 NoteRange = NotScalarExpr->getSourceRange();
5236 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005237 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005238 ErrorFound = NotAnAssignmentOp;
5239 ErrorLoc = AtomicBody->getExprLoc();
5240 ErrorRange = AtomicBody->getSourceRange();
5241 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5242 : AtomicBody->getExprLoc();
5243 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5244 : AtomicBody->getSourceRange();
5245 }
5246 } else {
5247 ErrorFound = NotAnExpression;
5248 NoteLoc = ErrorLoc = Body->getLocStart();
5249 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005250 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005251 if (ErrorFound != NoError) {
5252 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5253 << ErrorRange;
5254 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5255 << NoteRange;
5256 return StmtError();
5257 } else if (CurContext->isDependentContext())
5258 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005259 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005260 // If clause is update:
5261 // x++;
5262 // x--;
5263 // ++x;
5264 // --x;
5265 // x binop= expr;
5266 // x = x binop expr;
5267 // x = expr binop x;
5268 OpenMPAtomicUpdateChecker Checker(*this);
5269 if (Checker.checkStatement(
5270 Body, (AtomicKind == OMPC_update)
5271 ? diag::err_omp_atomic_update_not_expression_statement
5272 : diag::err_omp_atomic_not_expression_statement,
5273 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005274 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005275 if (!CurContext->isDependentContext()) {
5276 E = Checker.getExpr();
5277 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005278 UE = Checker.getUpdateExpr();
5279 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005280 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005281 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005282 enum {
5283 NotAnAssignmentOp,
5284 NotACompoundStatement,
5285 NotTwoSubstatements,
5286 NotASpecificExpression,
5287 NoError
5288 } ErrorFound = NoError;
5289 SourceLocation ErrorLoc, NoteLoc;
5290 SourceRange ErrorRange, NoteRange;
5291 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5292 // If clause is a capture:
5293 // v = x++;
5294 // v = x--;
5295 // v = ++x;
5296 // v = --x;
5297 // v = x binop= expr;
5298 // v = x = x binop expr;
5299 // v = x = expr binop x;
5300 auto *AtomicBinOp =
5301 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5302 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5303 V = AtomicBinOp->getLHS();
5304 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5305 OpenMPAtomicUpdateChecker Checker(*this);
5306 if (Checker.checkStatement(
5307 Body, diag::err_omp_atomic_capture_not_expression_statement,
5308 diag::note_omp_atomic_update))
5309 return StmtError();
5310 E = Checker.getExpr();
5311 X = Checker.getX();
5312 UE = Checker.getUpdateExpr();
5313 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5314 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005315 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005316 ErrorLoc = AtomicBody->getExprLoc();
5317 ErrorRange = AtomicBody->getSourceRange();
5318 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5319 : AtomicBody->getExprLoc();
5320 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5321 : AtomicBody->getSourceRange();
5322 ErrorFound = NotAnAssignmentOp;
5323 }
5324 if (ErrorFound != NoError) {
5325 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5326 << ErrorRange;
5327 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5328 return StmtError();
5329 } else if (CurContext->isDependentContext()) {
5330 UE = V = E = X = nullptr;
5331 }
5332 } else {
5333 // If clause is a capture:
5334 // { v = x; x = expr; }
5335 // { v = x; x++; }
5336 // { v = x; x--; }
5337 // { v = x; ++x; }
5338 // { v = x; --x; }
5339 // { v = x; x binop= expr; }
5340 // { v = x; x = x binop expr; }
5341 // { v = x; x = expr binop x; }
5342 // { x++; v = x; }
5343 // { x--; v = x; }
5344 // { ++x; v = x; }
5345 // { --x; v = x; }
5346 // { x binop= expr; v = x; }
5347 // { x = x binop expr; v = x; }
5348 // { x = expr binop x; v = x; }
5349 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5350 // Check that this is { expr1; expr2; }
5351 if (CS->size() == 2) {
5352 auto *First = CS->body_front();
5353 auto *Second = CS->body_back();
5354 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5355 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5356 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5357 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5358 // Need to find what subexpression is 'v' and what is 'x'.
5359 OpenMPAtomicUpdateChecker Checker(*this);
5360 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5361 BinaryOperator *BinOp = nullptr;
5362 if (IsUpdateExprFound) {
5363 BinOp = dyn_cast<BinaryOperator>(First);
5364 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5365 }
5366 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5367 // { v = x; x++; }
5368 // { v = x; x--; }
5369 // { v = x; ++x; }
5370 // { v = x; --x; }
5371 // { v = x; x binop= expr; }
5372 // { v = x; x = x binop expr; }
5373 // { v = x; x = expr binop x; }
5374 // Check that the first expression has form v = x.
5375 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5376 llvm::FoldingSetNodeID XId, PossibleXId;
5377 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5378 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5379 IsUpdateExprFound = XId == PossibleXId;
5380 if (IsUpdateExprFound) {
5381 V = BinOp->getLHS();
5382 X = Checker.getX();
5383 E = Checker.getExpr();
5384 UE = Checker.getUpdateExpr();
5385 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005386 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005387 }
5388 }
5389 if (!IsUpdateExprFound) {
5390 IsUpdateExprFound = !Checker.checkStatement(First);
5391 BinOp = nullptr;
5392 if (IsUpdateExprFound) {
5393 BinOp = dyn_cast<BinaryOperator>(Second);
5394 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5395 }
5396 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5397 // { x++; v = x; }
5398 // { x--; v = x; }
5399 // { ++x; v = x; }
5400 // { --x; v = x; }
5401 // { x binop= expr; v = x; }
5402 // { x = x binop expr; v = x; }
5403 // { x = expr binop x; v = x; }
5404 // Check that the second expression has form v = x.
5405 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5406 llvm::FoldingSetNodeID XId, PossibleXId;
5407 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5408 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5409 IsUpdateExprFound = XId == PossibleXId;
5410 if (IsUpdateExprFound) {
5411 V = BinOp->getLHS();
5412 X = Checker.getX();
5413 E = Checker.getExpr();
5414 UE = Checker.getUpdateExpr();
5415 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005416 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005417 }
5418 }
5419 }
5420 if (!IsUpdateExprFound) {
5421 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005422 auto *FirstExpr = dyn_cast<Expr>(First);
5423 auto *SecondExpr = dyn_cast<Expr>(Second);
5424 if (!FirstExpr || !SecondExpr ||
5425 !(FirstExpr->isInstantiationDependent() ||
5426 SecondExpr->isInstantiationDependent())) {
5427 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5428 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005429 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005430 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5431 : First->getLocStart();
5432 NoteRange = ErrorRange = FirstBinOp
5433 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005434 : SourceRange(ErrorLoc, ErrorLoc);
5435 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005436 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5437 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5438 ErrorFound = NotAnAssignmentOp;
5439 NoteLoc = ErrorLoc = SecondBinOp
5440 ? SecondBinOp->getOperatorLoc()
5441 : Second->getLocStart();
5442 NoteRange = ErrorRange =
5443 SecondBinOp ? SecondBinOp->getSourceRange()
5444 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005445 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005446 auto *PossibleXRHSInFirst =
5447 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5448 auto *PossibleXLHSInSecond =
5449 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5450 llvm::FoldingSetNodeID X1Id, X2Id;
5451 PossibleXRHSInFirst->Profile(X1Id, Context,
5452 /*Canonical=*/true);
5453 PossibleXLHSInSecond->Profile(X2Id, Context,
5454 /*Canonical=*/true);
5455 IsUpdateExprFound = X1Id == X2Id;
5456 if (IsUpdateExprFound) {
5457 V = FirstBinOp->getLHS();
5458 X = SecondBinOp->getLHS();
5459 E = SecondBinOp->getRHS();
5460 UE = nullptr;
5461 IsXLHSInRHSPart = false;
5462 IsPostfixUpdate = true;
5463 } else {
5464 ErrorFound = NotASpecificExpression;
5465 ErrorLoc = FirstBinOp->getExprLoc();
5466 ErrorRange = FirstBinOp->getSourceRange();
5467 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5468 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5469 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005470 }
5471 }
5472 }
5473 }
5474 } else {
5475 NoteLoc = ErrorLoc = Body->getLocStart();
5476 NoteRange = ErrorRange =
5477 SourceRange(Body->getLocStart(), Body->getLocStart());
5478 ErrorFound = NotTwoSubstatements;
5479 }
5480 } else {
5481 NoteLoc = ErrorLoc = Body->getLocStart();
5482 NoteRange = ErrorRange =
5483 SourceRange(Body->getLocStart(), Body->getLocStart());
5484 ErrorFound = NotACompoundStatement;
5485 }
5486 if (ErrorFound != NoError) {
5487 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5488 << ErrorRange;
5489 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5490 return StmtError();
5491 } else if (CurContext->isDependentContext()) {
5492 UE = V = E = X = nullptr;
5493 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005494 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005495 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005496
5497 getCurFunction()->setHasBranchProtectedScope();
5498
Alexey Bataev62cec442014-11-18 10:14:22 +00005499 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005500 X, V, E, UE, IsXLHSInRHSPart,
5501 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005502}
5503
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005504StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5505 Stmt *AStmt,
5506 SourceLocation StartLoc,
5507 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005508 if (!AStmt)
5509 return StmtError();
5510
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005511 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5512 // 1.2.2 OpenMP Language Terminology
5513 // Structured block - An executable statement with a single entry at the
5514 // top and a single exit at the bottom.
5515 // The point of exit cannot be a branch out of the structured block.
5516 // longjmp() and throw() must not violate the entry/exit criteria.
5517 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005518
Alexey Bataev13314bf2014-10-09 04:18:56 +00005519 // OpenMP [2.16, Nesting of Regions]
5520 // If specified, a teams construct must be contained within a target
5521 // construct. That target construct must contain no statements or directives
5522 // outside of the teams construct.
5523 if (DSAStack->hasInnerTeamsRegion()) {
5524 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5525 bool OMPTeamsFound = true;
5526 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5527 auto I = CS->body_begin();
5528 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005529 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005530 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5531 OMPTeamsFound = false;
5532 break;
5533 }
5534 ++I;
5535 }
5536 assert(I != CS->body_end() && "Not found statement");
5537 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005538 } else {
5539 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5540 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005541 }
5542 if (!OMPTeamsFound) {
5543 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5544 Diag(DSAStack->getInnerTeamsRegionLoc(),
5545 diag::note_omp_nested_teams_construct_here);
5546 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5547 << isa<OMPExecutableDirective>(S);
5548 return StmtError();
5549 }
5550 }
5551
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005552 getCurFunction()->setHasBranchProtectedScope();
5553
5554 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5555}
5556
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005557StmtResult
5558Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5559 Stmt *AStmt, SourceLocation StartLoc,
5560 SourceLocation EndLoc) {
5561 if (!AStmt)
5562 return StmtError();
5563
5564 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5565 // 1.2.2 OpenMP Language Terminology
5566 // Structured block - An executable statement with a single entry at the
5567 // top and a single exit at the bottom.
5568 // The point of exit cannot be a branch out of the structured block.
5569 // longjmp() and throw() must not violate the entry/exit criteria.
5570 CS->getCapturedDecl()->setNothrow();
5571
5572 getCurFunction()->setHasBranchProtectedScope();
5573
5574 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5575 AStmt);
5576}
5577
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005578StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5579 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5580 SourceLocation EndLoc,
5581 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5582 if (!AStmt)
5583 return StmtError();
5584
5585 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5586 // 1.2.2 OpenMP Language Terminology
5587 // Structured block - An executable statement with a single entry at the
5588 // top and a single exit at the bottom.
5589 // The point of exit cannot be a branch out of the structured block.
5590 // longjmp() and throw() must not violate the entry/exit criteria.
5591 CS->getCapturedDecl()->setNothrow();
5592
5593 OMPLoopDirective::HelperExprs B;
5594 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5595 // define the nested loops number.
5596 unsigned NestedLoopCount =
5597 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5598 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5599 VarsWithImplicitDSA, B);
5600 if (NestedLoopCount == 0)
5601 return StmtError();
5602
5603 assert((CurContext->isDependentContext() || B.builtAll()) &&
5604 "omp target parallel for loop exprs were not built");
5605
5606 if (!CurContext->isDependentContext()) {
5607 // Finalize the clauses that need pre-built expressions for CodeGen.
5608 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005609 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005610 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005611 B.NumIterations, *this, CurScope,
5612 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005613 return StmtError();
5614 }
5615 }
5616
5617 getCurFunction()->setHasBranchProtectedScope();
5618 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5619 NestedLoopCount, Clauses, AStmt,
5620 B, DSAStack->isCancelRegion());
5621}
5622
Samuel Antaodf67fc42016-01-19 19:15:56 +00005623/// \brief Check for existence of a map clause in the list of clauses.
5624static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5625 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5626 I != E; ++I) {
5627 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5628 return true;
5629 }
5630 }
5631
5632 return false;
5633}
5634
Michael Wong65f367f2015-07-21 13:44:28 +00005635StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5636 Stmt *AStmt,
5637 SourceLocation StartLoc,
5638 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005639 if (!AStmt)
5640 return StmtError();
5641
5642 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5643
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005644 // OpenMP [2.10.1, Restrictions, p. 97]
5645 // At least one map clause must appear on the directive.
5646 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005647 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5648 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005649 return StmtError();
5650 }
5651
Michael Wong65f367f2015-07-21 13:44:28 +00005652 getCurFunction()->setHasBranchProtectedScope();
5653
5654 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5655 AStmt);
5656}
5657
Samuel Antaodf67fc42016-01-19 19:15:56 +00005658StmtResult
5659Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5660 SourceLocation StartLoc,
5661 SourceLocation EndLoc) {
5662 // OpenMP [2.10.2, Restrictions, p. 99]
5663 // At least one map clause must appear on the directive.
5664 if (!HasMapClause(Clauses)) {
5665 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5666 << getOpenMPDirectiveName(OMPD_target_enter_data);
5667 return StmtError();
5668 }
5669
5670 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5671 Clauses);
5672}
5673
Samuel Antao72590762016-01-19 20:04:50 +00005674StmtResult
5675Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5676 SourceLocation StartLoc,
5677 SourceLocation EndLoc) {
5678 // OpenMP [2.10.3, Restrictions, p. 102]
5679 // At least one map clause must appear on the directive.
5680 if (!HasMapClause(Clauses)) {
5681 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5682 << getOpenMPDirectiveName(OMPD_target_exit_data);
5683 return StmtError();
5684 }
5685
5686 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5687}
5688
Samuel Antao686c70c2016-05-26 17:30:50 +00005689StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5690 SourceLocation StartLoc,
5691 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005692 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005693 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005694 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005695 seenMotionClause = true;
5696 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005697 if (!seenMotionClause) {
5698 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5699 return StmtError();
5700 }
5701 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5702}
5703
Alexey Bataev13314bf2014-10-09 04:18:56 +00005704StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5705 Stmt *AStmt, SourceLocation StartLoc,
5706 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005707 if (!AStmt)
5708 return StmtError();
5709
Alexey Bataev13314bf2014-10-09 04:18:56 +00005710 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5711 // 1.2.2 OpenMP Language Terminology
5712 // Structured block - An executable statement with a single entry at the
5713 // top and a single exit at the bottom.
5714 // The point of exit cannot be a branch out of the structured block.
5715 // longjmp() and throw() must not violate the entry/exit criteria.
5716 CS->getCapturedDecl()->setNothrow();
5717
5718 getCurFunction()->setHasBranchProtectedScope();
5719
5720 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5721}
5722
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005723StmtResult
5724Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5725 SourceLocation EndLoc,
5726 OpenMPDirectiveKind CancelRegion) {
5727 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5728 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5729 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5730 << getOpenMPDirectiveName(CancelRegion);
5731 return StmtError();
5732 }
5733 if (DSAStack->isParentNowaitRegion()) {
5734 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5735 return StmtError();
5736 }
5737 if (DSAStack->isParentOrderedRegion()) {
5738 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5739 return StmtError();
5740 }
5741 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5742 CancelRegion);
5743}
5744
Alexey Bataev87933c72015-09-18 08:07:34 +00005745StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5746 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005747 SourceLocation EndLoc,
5748 OpenMPDirectiveKind CancelRegion) {
5749 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5750 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5751 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5752 << getOpenMPDirectiveName(CancelRegion);
5753 return StmtError();
5754 }
5755 if (DSAStack->isParentNowaitRegion()) {
5756 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5757 return StmtError();
5758 }
5759 if (DSAStack->isParentOrderedRegion()) {
5760 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5761 return StmtError();
5762 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005763 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005764 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5765 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005766}
5767
Alexey Bataev382967a2015-12-08 12:06:20 +00005768static bool checkGrainsizeNumTasksClauses(Sema &S,
5769 ArrayRef<OMPClause *> Clauses) {
5770 OMPClause *PrevClause = nullptr;
5771 bool ErrorFound = false;
5772 for (auto *C : Clauses) {
5773 if (C->getClauseKind() == OMPC_grainsize ||
5774 C->getClauseKind() == OMPC_num_tasks) {
5775 if (!PrevClause)
5776 PrevClause = C;
5777 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5778 S.Diag(C->getLocStart(),
5779 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5780 << getOpenMPClauseName(C->getClauseKind())
5781 << getOpenMPClauseName(PrevClause->getClauseKind());
5782 S.Diag(PrevClause->getLocStart(),
5783 diag::note_omp_previous_grainsize_num_tasks)
5784 << getOpenMPClauseName(PrevClause->getClauseKind());
5785 ErrorFound = true;
5786 }
5787 }
5788 }
5789 return ErrorFound;
5790}
5791
Alexey Bataev49f6e782015-12-01 04:18:41 +00005792StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5793 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5794 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005795 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005796 if (!AStmt)
5797 return StmtError();
5798
5799 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5800 OMPLoopDirective::HelperExprs B;
5801 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5802 // define the nested loops number.
5803 unsigned NestedLoopCount =
5804 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005805 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005806 VarsWithImplicitDSA, B);
5807 if (NestedLoopCount == 0)
5808 return StmtError();
5809
5810 assert((CurContext->isDependentContext() || B.builtAll()) &&
5811 "omp for loop exprs were not built");
5812
Alexey Bataev382967a2015-12-08 12:06:20 +00005813 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5814 // The grainsize clause and num_tasks clause are mutually exclusive and may
5815 // not appear on the same taskloop directive.
5816 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5817 return StmtError();
5818
Alexey Bataev49f6e782015-12-01 04:18:41 +00005819 getCurFunction()->setHasBranchProtectedScope();
5820 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5821 NestedLoopCount, Clauses, AStmt, B);
5822}
5823
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005824StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5825 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5826 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005827 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005828 if (!AStmt)
5829 return StmtError();
5830
5831 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5832 OMPLoopDirective::HelperExprs B;
5833 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5834 // define the nested loops number.
5835 unsigned NestedLoopCount =
5836 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5837 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5838 VarsWithImplicitDSA, B);
5839 if (NestedLoopCount == 0)
5840 return StmtError();
5841
5842 assert((CurContext->isDependentContext() || B.builtAll()) &&
5843 "omp for loop exprs were not built");
5844
Alexey Bataev5a3af132016-03-29 08:58:54 +00005845 if (!CurContext->isDependentContext()) {
5846 // Finalize the clauses that need pre-built expressions for CodeGen.
5847 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005848 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005849 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005850 B.NumIterations, *this, CurScope,
5851 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005852 return StmtError();
5853 }
5854 }
5855
Alexey Bataev382967a2015-12-08 12:06:20 +00005856 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5857 // The grainsize clause and num_tasks clause are mutually exclusive and may
5858 // not appear on the same taskloop directive.
5859 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5860 return StmtError();
5861
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005862 getCurFunction()->setHasBranchProtectedScope();
5863 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5864 NestedLoopCount, Clauses, AStmt, B);
5865}
5866
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005867StmtResult Sema::ActOnOpenMPDistributeDirective(
5868 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5869 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005870 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005871 if (!AStmt)
5872 return StmtError();
5873
5874 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5875 OMPLoopDirective::HelperExprs B;
5876 // In presence of clause 'collapse' with number of loops, it will
5877 // define the nested loops number.
5878 unsigned NestedLoopCount =
5879 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5880 nullptr /*ordered not a clause on distribute*/, AStmt,
5881 *this, *DSAStack, VarsWithImplicitDSA, B);
5882 if (NestedLoopCount == 0)
5883 return StmtError();
5884
5885 assert((CurContext->isDependentContext() || B.builtAll()) &&
5886 "omp for loop exprs were not built");
5887
5888 getCurFunction()->setHasBranchProtectedScope();
5889 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5890 NestedLoopCount, Clauses, AStmt, B);
5891}
5892
Carlo Bertolli9925f152016-06-27 14:55:37 +00005893StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5894 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5895 SourceLocation EndLoc,
5896 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5897 if (!AStmt)
5898 return StmtError();
5899
5900 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5901 // 1.2.2 OpenMP Language Terminology
5902 // Structured block - An executable statement with a single entry at the
5903 // top and a single exit at the bottom.
5904 // The point of exit cannot be a branch out of the structured block.
5905 // longjmp() and throw() must not violate the entry/exit criteria.
5906 CS->getCapturedDecl()->setNothrow();
5907
5908 OMPLoopDirective::HelperExprs B;
5909 // In presence of clause 'collapse' with number of loops, it will
5910 // define the nested loops number.
5911 unsigned NestedLoopCount = CheckOpenMPLoop(
5912 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5913 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5914 VarsWithImplicitDSA, B);
5915 if (NestedLoopCount == 0)
5916 return StmtError();
5917
5918 assert((CurContext->isDependentContext() || B.builtAll()) &&
5919 "omp for loop exprs were not built");
5920
5921 getCurFunction()->setHasBranchProtectedScope();
5922 return OMPDistributeParallelForDirective::Create(
5923 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5924}
5925
Kelvin Li4a39add2016-07-05 05:00:15 +00005926StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5927 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5928 SourceLocation EndLoc,
5929 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5930 if (!AStmt)
5931 return StmtError();
5932
5933 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5934 // 1.2.2 OpenMP Language Terminology
5935 // Structured block - An executable statement with a single entry at the
5936 // top and a single exit at the bottom.
5937 // The point of exit cannot be a branch out of the structured block.
5938 // longjmp() and throw() must not violate the entry/exit criteria.
5939 CS->getCapturedDecl()->setNothrow();
5940
5941 OMPLoopDirective::HelperExprs B;
5942 // In presence of clause 'collapse' with number of loops, it will
5943 // define the nested loops number.
5944 unsigned NestedLoopCount = CheckOpenMPLoop(
5945 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5946 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5947 VarsWithImplicitDSA, B);
5948 if (NestedLoopCount == 0)
5949 return StmtError();
5950
5951 assert((CurContext->isDependentContext() || B.builtAll()) &&
5952 "omp for loop exprs were not built");
5953
Kelvin Lic5609492016-07-15 04:39:07 +00005954 if (checkSimdlenSafelenSpecified(*this, Clauses))
5955 return StmtError();
5956
Kelvin Li4a39add2016-07-05 05:00:15 +00005957 getCurFunction()->setHasBranchProtectedScope();
5958 return OMPDistributeParallelForSimdDirective::Create(
5959 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5960}
5961
Kelvin Li787f3fc2016-07-06 04:45:38 +00005962StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5963 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5964 SourceLocation EndLoc,
5965 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5966 if (!AStmt)
5967 return StmtError();
5968
5969 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5970 // 1.2.2 OpenMP Language Terminology
5971 // Structured block - An executable statement with a single entry at the
5972 // top and a single exit at the bottom.
5973 // The point of exit cannot be a branch out of the structured block.
5974 // longjmp() and throw() must not violate the entry/exit criteria.
5975 CS->getCapturedDecl()->setNothrow();
5976
5977 OMPLoopDirective::HelperExprs B;
5978 // In presence of clause 'collapse' with number of loops, it will
5979 // define the nested loops number.
5980 unsigned NestedLoopCount =
5981 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5982 nullptr /*ordered not a clause on distribute*/, AStmt,
5983 *this, *DSAStack, VarsWithImplicitDSA, B);
5984 if (NestedLoopCount == 0)
5985 return StmtError();
5986
5987 assert((CurContext->isDependentContext() || B.builtAll()) &&
5988 "omp for loop exprs were not built");
5989
Kelvin Lic5609492016-07-15 04:39:07 +00005990 if (checkSimdlenSafelenSpecified(*this, Clauses))
5991 return StmtError();
5992
Kelvin Li787f3fc2016-07-06 04:45:38 +00005993 getCurFunction()->setHasBranchProtectedScope();
5994 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
5995 NestedLoopCount, Clauses, AStmt, B);
5996}
5997
Kelvin Lia579b912016-07-14 02:54:56 +00005998StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
5999 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6000 SourceLocation EndLoc,
6001 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6002 if (!AStmt)
6003 return StmtError();
6004
6005 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6006 // 1.2.2 OpenMP Language Terminology
6007 // Structured block - An executable statement with a single entry at the
6008 // top and a single exit at the bottom.
6009 // The point of exit cannot be a branch out of the structured block.
6010 // longjmp() and throw() must not violate the entry/exit criteria.
6011 CS->getCapturedDecl()->setNothrow();
6012
6013 OMPLoopDirective::HelperExprs B;
6014 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6015 // define the nested loops number.
6016 unsigned NestedLoopCount = CheckOpenMPLoop(
6017 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6018 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6019 VarsWithImplicitDSA, B);
6020 if (NestedLoopCount == 0)
6021 return StmtError();
6022
6023 assert((CurContext->isDependentContext() || B.builtAll()) &&
6024 "omp target parallel for simd loop exprs were not built");
6025
6026 if (!CurContext->isDependentContext()) {
6027 // Finalize the clauses that need pre-built expressions for CodeGen.
6028 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006029 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006030 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6031 B.NumIterations, *this, CurScope,
6032 DSAStack))
6033 return StmtError();
6034 }
6035 }
Kelvin Lic5609492016-07-15 04:39:07 +00006036 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006037 return StmtError();
6038
6039 getCurFunction()->setHasBranchProtectedScope();
6040 return OMPTargetParallelForSimdDirective::Create(
6041 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6042}
6043
Kelvin Li986330c2016-07-20 22:57:10 +00006044StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6045 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6046 SourceLocation EndLoc,
6047 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6048 if (!AStmt)
6049 return StmtError();
6050
6051 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6052 // 1.2.2 OpenMP Language Terminology
6053 // Structured block - An executable statement with a single entry at the
6054 // top and a single exit at the bottom.
6055 // The point of exit cannot be a branch out of the structured block.
6056 // longjmp() and throw() must not violate the entry/exit criteria.
6057 CS->getCapturedDecl()->setNothrow();
6058
6059 OMPLoopDirective::HelperExprs B;
6060 // In presence of clause 'collapse' with number of loops, it will define the
6061 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006062 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006063 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6064 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6065 VarsWithImplicitDSA, B);
6066 if (NestedLoopCount == 0)
6067 return StmtError();
6068
6069 assert((CurContext->isDependentContext() || B.builtAll()) &&
6070 "omp target simd loop exprs were not built");
6071
6072 if (!CurContext->isDependentContext()) {
6073 // Finalize the clauses that need pre-built expressions for CodeGen.
6074 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006075 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006076 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6077 B.NumIterations, *this, CurScope,
6078 DSAStack))
6079 return StmtError();
6080 }
6081 }
6082
6083 if (checkSimdlenSafelenSpecified(*this, Clauses))
6084 return StmtError();
6085
6086 getCurFunction()->setHasBranchProtectedScope();
6087 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6088 NestedLoopCount, Clauses, AStmt, B);
6089}
6090
Kelvin Li02532872016-08-05 14:37:37 +00006091StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6092 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6093 SourceLocation EndLoc,
6094 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6095 if (!AStmt)
6096 return StmtError();
6097
6098 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6099 // 1.2.2 OpenMP Language Terminology
6100 // Structured block - An executable statement with a single entry at the
6101 // top and a single exit at the bottom.
6102 // The point of exit cannot be a branch out of the structured block.
6103 // longjmp() and throw() must not violate the entry/exit criteria.
6104 CS->getCapturedDecl()->setNothrow();
6105
6106 OMPLoopDirective::HelperExprs B;
6107 // In presence of clause 'collapse' with number of loops, it will
6108 // define the nested loops number.
6109 unsigned NestedLoopCount =
6110 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6111 nullptr /*ordered not a clause on distribute*/, AStmt,
6112 *this, *DSAStack, VarsWithImplicitDSA, B);
6113 if (NestedLoopCount == 0)
6114 return StmtError();
6115
6116 assert((CurContext->isDependentContext() || B.builtAll()) &&
6117 "omp teams distribute loop exprs were not built");
6118
6119 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006120 return OMPTeamsDistributeDirective::Create(
6121 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006122}
6123
Kelvin Li4e325f72016-10-25 12:50:55 +00006124StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6125 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6126 SourceLocation EndLoc,
6127 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6128 if (!AStmt)
6129 return StmtError();
6130
6131 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6132 // 1.2.2 OpenMP Language Terminology
6133 // Structured block - An executable statement with a single entry at the
6134 // top and a single exit at the bottom.
6135 // The point of exit cannot be a branch out of the structured block.
6136 // longjmp() and throw() must not violate the entry/exit criteria.
6137 CS->getCapturedDecl()->setNothrow();
6138
6139 OMPLoopDirective::HelperExprs B;
6140 // In presence of clause 'collapse' with number of loops, it will
6141 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006142 unsigned NestedLoopCount = CheckOpenMPLoop(
6143 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6144 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6145 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006146
6147 if (NestedLoopCount == 0)
6148 return StmtError();
6149
6150 assert((CurContext->isDependentContext() || B.builtAll()) &&
6151 "omp teams distribute simd loop exprs were not built");
6152
6153 if (!CurContext->isDependentContext()) {
6154 // Finalize the clauses that need pre-built expressions for CodeGen.
6155 for (auto C : Clauses) {
6156 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6157 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6158 B.NumIterations, *this, CurScope,
6159 DSAStack))
6160 return StmtError();
6161 }
6162 }
6163
6164 if (checkSimdlenSafelenSpecified(*this, Clauses))
6165 return StmtError();
6166
6167 getCurFunction()->setHasBranchProtectedScope();
6168 return OMPTeamsDistributeSimdDirective::Create(
6169 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6170}
6171
Kelvin Li579e41c2016-11-30 23:51:03 +00006172StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6173 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6174 SourceLocation EndLoc,
6175 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6176 if (!AStmt)
6177 return StmtError();
6178
6179 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6180 // 1.2.2 OpenMP Language Terminology
6181 // Structured block - An executable statement with a single entry at the
6182 // top and a single exit at the bottom.
6183 // The point of exit cannot be a branch out of the structured block.
6184 // longjmp() and throw() must not violate the entry/exit criteria.
6185 CS->getCapturedDecl()->setNothrow();
6186
6187 OMPLoopDirective::HelperExprs B;
6188 // In presence of clause 'collapse' with number of loops, it will
6189 // define the nested loops number.
6190 auto NestedLoopCount = CheckOpenMPLoop(
6191 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6192 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6193 VarsWithImplicitDSA, B);
6194
6195 if (NestedLoopCount == 0)
6196 return StmtError();
6197
6198 assert((CurContext->isDependentContext() || B.builtAll()) &&
6199 "omp for loop exprs were not built");
6200
6201 if (!CurContext->isDependentContext()) {
6202 // Finalize the clauses that need pre-built expressions for CodeGen.
6203 for (auto C : Clauses) {
6204 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6205 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6206 B.NumIterations, *this, CurScope,
6207 DSAStack))
6208 return StmtError();
6209 }
6210 }
6211
6212 if (checkSimdlenSafelenSpecified(*this, Clauses))
6213 return StmtError();
6214
6215 getCurFunction()->setHasBranchProtectedScope();
6216 return OMPTeamsDistributeParallelForSimdDirective::Create(
6217 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6218}
6219
Kelvin Li7ade93f2016-12-09 03:24:30 +00006220StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6221 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6222 SourceLocation EndLoc,
6223 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6224 if (!AStmt)
6225 return StmtError();
6226
6227 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6228 // 1.2.2 OpenMP Language Terminology
6229 // Structured block - An executable statement with a single entry at the
6230 // top and a single exit at the bottom.
6231 // The point of exit cannot be a branch out of the structured block.
6232 // longjmp() and throw() must not violate the entry/exit criteria.
6233 CS->getCapturedDecl()->setNothrow();
6234
6235 OMPLoopDirective::HelperExprs B;
6236 // In presence of clause 'collapse' with number of loops, it will
6237 // define the nested loops number.
6238 unsigned NestedLoopCount = CheckOpenMPLoop(
6239 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6240 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6241 VarsWithImplicitDSA, B);
6242
6243 if (NestedLoopCount == 0)
6244 return StmtError();
6245
6246 assert((CurContext->isDependentContext() || B.builtAll()) &&
6247 "omp for loop exprs were not built");
6248
6249 if (!CurContext->isDependentContext()) {
6250 // Finalize the clauses that need pre-built expressions for CodeGen.
6251 for (auto C : Clauses) {
6252 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6253 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6254 B.NumIterations, *this, CurScope,
6255 DSAStack))
6256 return StmtError();
6257 }
6258 }
6259
6260 getCurFunction()->setHasBranchProtectedScope();
6261 return OMPTeamsDistributeParallelForDirective::Create(
6262 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6263}
6264
Kelvin Libf594a52016-12-17 05:48:59 +00006265StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6266 Stmt *AStmt,
6267 SourceLocation StartLoc,
6268 SourceLocation EndLoc) {
6269 if (!AStmt)
6270 return StmtError();
6271
6272 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6273 // 1.2.2 OpenMP Language Terminology
6274 // Structured block - An executable statement with a single entry at the
6275 // top and a single exit at the bottom.
6276 // The point of exit cannot be a branch out of the structured block.
6277 // longjmp() and throw() must not violate the entry/exit criteria.
6278 CS->getCapturedDecl()->setNothrow();
6279
6280 getCurFunction()->setHasBranchProtectedScope();
6281
6282 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6283 AStmt);
6284}
6285
Alexey Bataeved09d242014-05-28 05:53:51 +00006286OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006287 SourceLocation StartLoc,
6288 SourceLocation LParenLoc,
6289 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006290 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006291 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006292 case OMPC_final:
6293 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6294 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006295 case OMPC_num_threads:
6296 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6297 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006298 case OMPC_safelen:
6299 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6300 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006301 case OMPC_simdlen:
6302 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6303 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006304 case OMPC_collapse:
6305 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6306 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006307 case OMPC_ordered:
6308 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6309 break;
Michael Wonge710d542015-08-07 16:16:36 +00006310 case OMPC_device:
6311 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6312 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006313 case OMPC_num_teams:
6314 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6315 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006316 case OMPC_thread_limit:
6317 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6318 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006319 case OMPC_priority:
6320 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6321 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006322 case OMPC_grainsize:
6323 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6324 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006325 case OMPC_num_tasks:
6326 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6327 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006328 case OMPC_hint:
6329 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6330 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006331 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006332 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006333 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006334 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006335 case OMPC_private:
6336 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006337 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006338 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006339 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006340 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006341 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006342 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006343 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006344 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006345 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006346 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006347 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006348 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006349 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006350 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006351 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006352 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006353 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006354 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006355 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006356 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006357 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006358 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006359 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006360 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006361 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006362 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006363 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006364 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006365 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006366 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006367 llvm_unreachable("Clause is not allowed.");
6368 }
6369 return Res;
6370}
6371
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006372OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6373 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006374 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006375 SourceLocation NameModifierLoc,
6376 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006377 SourceLocation EndLoc) {
6378 Expr *ValExpr = Condition;
6379 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6380 !Condition->isInstantiationDependent() &&
6381 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006382 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006383 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006384 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006385
Richard Smith03a4aa32016-06-23 19:02:52 +00006386 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006387 }
6388
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006389 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6390 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006391}
6392
Alexey Bataev3778b602014-07-17 07:32:53 +00006393OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6394 SourceLocation StartLoc,
6395 SourceLocation LParenLoc,
6396 SourceLocation EndLoc) {
6397 Expr *ValExpr = Condition;
6398 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6399 !Condition->isInstantiationDependent() &&
6400 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006401 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006402 if (Val.isInvalid())
6403 return nullptr;
6404
Richard Smith03a4aa32016-06-23 19:02:52 +00006405 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006406 }
6407
6408 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6409}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006410ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6411 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006412 if (!Op)
6413 return ExprError();
6414
6415 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6416 public:
6417 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006418 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006419 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6420 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006421 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6422 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006423 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6424 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006425 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6426 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006427 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6428 QualType T,
6429 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006430 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6431 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006432 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6433 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006434 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006435 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006436 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006437 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6438 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006439 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6440 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006441 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6442 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006443 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006444 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006445 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006446 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6447 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006448 llvm_unreachable("conversion functions are permitted");
6449 }
6450 } ConvertDiagnoser;
6451 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6452}
6453
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006454static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006455 OpenMPClauseKind CKind,
6456 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006457 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6458 !ValExpr->isInstantiationDependent()) {
6459 SourceLocation Loc = ValExpr->getExprLoc();
6460 ExprResult Value =
6461 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6462 if (Value.isInvalid())
6463 return false;
6464
6465 ValExpr = Value.get();
6466 // The expression must evaluate to a non-negative integer value.
6467 llvm::APSInt Result;
6468 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006469 Result.isSigned() &&
6470 !((!StrictlyPositive && Result.isNonNegative()) ||
6471 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006472 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006473 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6474 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006475 return false;
6476 }
6477 }
6478 return true;
6479}
6480
Alexey Bataev568a8332014-03-06 06:15:19 +00006481OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6482 SourceLocation StartLoc,
6483 SourceLocation LParenLoc,
6484 SourceLocation EndLoc) {
6485 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006486
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006487 // OpenMP [2.5, Restrictions]
6488 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006489 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6490 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006491 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006492
Alexey Bataeved09d242014-05-28 05:53:51 +00006493 return new (Context)
6494 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006495}
6496
Alexey Bataev62c87d22014-03-21 04:51:18 +00006497ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006498 OpenMPClauseKind CKind,
6499 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006500 if (!E)
6501 return ExprError();
6502 if (E->isValueDependent() || E->isTypeDependent() ||
6503 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006504 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006505 llvm::APSInt Result;
6506 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6507 if (ICE.isInvalid())
6508 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006509 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6510 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006511 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006512 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6513 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006514 return ExprError();
6515 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006516 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6517 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6518 << E->getSourceRange();
6519 return ExprError();
6520 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006521 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6522 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006523 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006524 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006525 return ICE;
6526}
6527
6528OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6529 SourceLocation LParenLoc,
6530 SourceLocation EndLoc) {
6531 // OpenMP [2.8.1, simd construct, Description]
6532 // The parameter of the safelen clause must be a constant
6533 // positive integer expression.
6534 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6535 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006536 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006537 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006538 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006539}
6540
Alexey Bataev66b15b52015-08-21 11:14:16 +00006541OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6542 SourceLocation LParenLoc,
6543 SourceLocation EndLoc) {
6544 // OpenMP [2.8.1, simd construct, Description]
6545 // The parameter of the simdlen clause must be a constant
6546 // positive integer expression.
6547 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6548 if (Simdlen.isInvalid())
6549 return nullptr;
6550 return new (Context)
6551 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6552}
6553
Alexander Musman64d33f12014-06-04 07:53:32 +00006554OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6555 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006556 SourceLocation LParenLoc,
6557 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006558 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006559 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006560 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006561 // The parameter of the collapse clause must be a constant
6562 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006563 ExprResult NumForLoopsResult =
6564 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6565 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006566 return nullptr;
6567 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006568 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006569}
6570
Alexey Bataev10e775f2015-07-30 11:36:16 +00006571OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6572 SourceLocation EndLoc,
6573 SourceLocation LParenLoc,
6574 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006575 // OpenMP [2.7.1, loop construct, Description]
6576 // OpenMP [2.8.1, simd construct, Description]
6577 // OpenMP [2.9.6, distribute construct, Description]
6578 // The parameter of the ordered clause must be a constant
6579 // positive integer expression if any.
6580 if (NumForLoops && LParenLoc.isValid()) {
6581 ExprResult NumForLoopsResult =
6582 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6583 if (NumForLoopsResult.isInvalid())
6584 return nullptr;
6585 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006586 } else
6587 NumForLoops = nullptr;
6588 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006589 return new (Context)
6590 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6591}
6592
Alexey Bataeved09d242014-05-28 05:53:51 +00006593OMPClause *Sema::ActOnOpenMPSimpleClause(
6594 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6595 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006596 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006597 switch (Kind) {
6598 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006599 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006600 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6601 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006602 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006603 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006604 Res = ActOnOpenMPProcBindClause(
6605 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6606 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006607 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006608 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006609 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006610 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006611 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006612 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006613 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006614 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006615 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006616 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006617 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006618 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006619 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006620 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006621 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006622 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006623 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006624 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006625 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006626 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006627 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006628 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006629 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006630 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006631 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006632 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006633 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006634 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006635 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006636 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006637 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006638 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006639 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006640 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006641 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006642 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006643 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006644 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006645 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006646 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006647 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006648 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006649 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006650 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006651 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006652 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006653 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006654 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006655 llvm_unreachable("Clause is not allowed.");
6656 }
6657 return Res;
6658}
6659
Alexey Bataev6402bca2015-12-28 07:25:51 +00006660static std::string
6661getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6662 ArrayRef<unsigned> Exclude = llvm::None) {
6663 std::string Values;
6664 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6665 unsigned Skipped = Exclude.size();
6666 auto S = Exclude.begin(), E = Exclude.end();
6667 for (unsigned i = First; i < Last; ++i) {
6668 if (std::find(S, E, i) != E) {
6669 --Skipped;
6670 continue;
6671 }
6672 Values += "'";
6673 Values += getOpenMPSimpleClauseTypeName(K, i);
6674 Values += "'";
6675 if (i == Bound - Skipped)
6676 Values += " or ";
6677 else if (i != Bound + 1 - Skipped)
6678 Values += ", ";
6679 }
6680 return Values;
6681}
6682
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006683OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6684 SourceLocation KindKwLoc,
6685 SourceLocation StartLoc,
6686 SourceLocation LParenLoc,
6687 SourceLocation EndLoc) {
6688 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006689 static_assert(OMPC_DEFAULT_unknown > 0,
6690 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006691 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006692 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6693 /*Last=*/OMPC_DEFAULT_unknown)
6694 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006695 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006696 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006697 switch (Kind) {
6698 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006699 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006700 break;
6701 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006702 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006703 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006704 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006705 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006706 break;
6707 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006708 return new (Context)
6709 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006710}
6711
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006712OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6713 SourceLocation KindKwLoc,
6714 SourceLocation StartLoc,
6715 SourceLocation LParenLoc,
6716 SourceLocation EndLoc) {
6717 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006718 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006719 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6720 /*Last=*/OMPC_PROC_BIND_unknown)
6721 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006722 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006723 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006724 return new (Context)
6725 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006726}
6727
Alexey Bataev56dafe82014-06-20 07:16:17 +00006728OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006729 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006730 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006731 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006732 SourceLocation EndLoc) {
6733 OMPClause *Res = nullptr;
6734 switch (Kind) {
6735 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006736 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6737 assert(Argument.size() == NumberOfElements &&
6738 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006739 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006740 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6741 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6742 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6743 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6744 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006745 break;
6746 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006747 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6748 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6749 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6750 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006751 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006752 case OMPC_dist_schedule:
6753 Res = ActOnOpenMPDistScheduleClause(
6754 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6755 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6756 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006757 case OMPC_defaultmap:
6758 enum { Modifier, DefaultmapKind };
6759 Res = ActOnOpenMPDefaultmapClause(
6760 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6761 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006762 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6763 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006764 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006765 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006766 case OMPC_num_threads:
6767 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006768 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006769 case OMPC_collapse:
6770 case OMPC_default:
6771 case OMPC_proc_bind:
6772 case OMPC_private:
6773 case OMPC_firstprivate:
6774 case OMPC_lastprivate:
6775 case OMPC_shared:
6776 case OMPC_reduction:
6777 case OMPC_linear:
6778 case OMPC_aligned:
6779 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006780 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006781 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006782 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006783 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006784 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006785 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006786 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006787 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006788 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006789 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006790 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006791 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006792 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006793 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006794 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006795 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006796 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006797 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006798 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006799 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006800 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006801 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006802 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006803 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006804 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006805 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006806 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006807 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006808 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006809 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006810 llvm_unreachable("Clause is not allowed.");
6811 }
6812 return Res;
6813}
6814
Alexey Bataev6402bca2015-12-28 07:25:51 +00006815static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6816 OpenMPScheduleClauseModifier M2,
6817 SourceLocation M1Loc, SourceLocation M2Loc) {
6818 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6819 SmallVector<unsigned, 2> Excluded;
6820 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6821 Excluded.push_back(M2);
6822 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6823 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6824 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6825 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6826 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6827 << getListOfPossibleValues(OMPC_schedule,
6828 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6829 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6830 Excluded)
6831 << getOpenMPClauseName(OMPC_schedule);
6832 return true;
6833 }
6834 return false;
6835}
6836
Alexey Bataev56dafe82014-06-20 07:16:17 +00006837OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006838 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006839 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006840 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6841 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6842 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6843 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6844 return nullptr;
6845 // OpenMP, 2.7.1, Loop Construct, Restrictions
6846 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6847 // but not both.
6848 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6849 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6850 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6851 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6852 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6853 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6854 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6855 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6856 return nullptr;
6857 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006858 if (Kind == OMPC_SCHEDULE_unknown) {
6859 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00006860 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6861 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6862 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6863 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6864 Exclude);
6865 } else {
6866 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6867 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006868 }
6869 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6870 << Values << getOpenMPClauseName(OMPC_schedule);
6871 return nullptr;
6872 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00006873 // OpenMP, 2.7.1, Loop Construct, Restrictions
6874 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6875 // schedule(guided).
6876 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6877 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6878 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6879 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6880 diag::err_omp_schedule_nonmonotonic_static);
6881 return nullptr;
6882 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006883 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00006884 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00006885 if (ChunkSize) {
6886 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6887 !ChunkSize->isInstantiationDependent() &&
6888 !ChunkSize->containsUnexpandedParameterPack()) {
6889 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6890 ExprResult Val =
6891 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6892 if (Val.isInvalid())
6893 return nullptr;
6894
6895 ValExpr = Val.get();
6896
6897 // OpenMP [2.7.1, Restrictions]
6898 // chunk_size must be a loop invariant integer expression with a positive
6899 // value.
6900 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00006901 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6902 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6903 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006904 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00006905 return nullptr;
6906 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00006907 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
6908 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006909 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6910 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6911 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006912 }
6913 }
6914 }
6915
Alexey Bataev6402bca2015-12-28 07:25:51 +00006916 return new (Context)
6917 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00006918 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006919}
6920
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006921OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6922 SourceLocation StartLoc,
6923 SourceLocation EndLoc) {
6924 OMPClause *Res = nullptr;
6925 switch (Kind) {
6926 case OMPC_ordered:
6927 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6928 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00006929 case OMPC_nowait:
6930 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6931 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006932 case OMPC_untied:
6933 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6934 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006935 case OMPC_mergeable:
6936 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6937 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006938 case OMPC_read:
6939 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6940 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00006941 case OMPC_write:
6942 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6943 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006944 case OMPC_update:
6945 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6946 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00006947 case OMPC_capture:
6948 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6949 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006950 case OMPC_seq_cst:
6951 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6952 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00006953 case OMPC_threads:
6954 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6955 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006956 case OMPC_simd:
6957 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6958 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00006959 case OMPC_nogroup:
6960 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6961 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006962 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006963 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006964 case OMPC_num_threads:
6965 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006966 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006967 case OMPC_collapse:
6968 case OMPC_schedule:
6969 case OMPC_private:
6970 case OMPC_firstprivate:
6971 case OMPC_lastprivate:
6972 case OMPC_shared:
6973 case OMPC_reduction:
6974 case OMPC_linear:
6975 case OMPC_aligned:
6976 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006977 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006978 case OMPC_default:
6979 case OMPC_proc_bind:
6980 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006981 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006982 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006983 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006984 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006985 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006986 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006987 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006988 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00006989 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006990 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006991 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006992 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006993 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006994 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006995 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006996 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006997 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006998 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006999 llvm_unreachable("Clause is not allowed.");
7000 }
7001 return Res;
7002}
7003
Alexey Bataev236070f2014-06-20 11:19:47 +00007004OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7005 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007006 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007007 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7008}
7009
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007010OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7011 SourceLocation EndLoc) {
7012 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7013}
7014
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007015OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7016 SourceLocation EndLoc) {
7017 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7018}
7019
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007020OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7021 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007022 return new (Context) OMPReadClause(StartLoc, EndLoc);
7023}
7024
Alexey Bataevdea47612014-07-23 07:46:59 +00007025OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7026 SourceLocation EndLoc) {
7027 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7028}
7029
Alexey Bataev67a4f222014-07-23 10:25:33 +00007030OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7031 SourceLocation EndLoc) {
7032 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7033}
7034
Alexey Bataev459dec02014-07-24 06:46:57 +00007035OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7036 SourceLocation EndLoc) {
7037 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7038}
7039
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007040OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7041 SourceLocation EndLoc) {
7042 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7043}
7044
Alexey Bataev346265e2015-09-25 10:37:12 +00007045OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7046 SourceLocation EndLoc) {
7047 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7048}
7049
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007050OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7051 SourceLocation EndLoc) {
7052 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7053}
7054
Alexey Bataevb825de12015-12-07 10:51:44 +00007055OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7056 SourceLocation EndLoc) {
7057 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7058}
7059
Alexey Bataevc5e02582014-06-16 07:08:35 +00007060OMPClause *Sema::ActOnOpenMPVarListClause(
7061 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7062 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7063 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007064 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007065 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7066 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7067 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007068 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007069 switch (Kind) {
7070 case OMPC_private:
7071 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7072 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007073 case OMPC_firstprivate:
7074 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7075 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007076 case OMPC_lastprivate:
7077 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7078 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007079 case OMPC_shared:
7080 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7081 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007082 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007083 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7084 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007085 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007086 case OMPC_linear:
7087 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007088 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007089 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007090 case OMPC_aligned:
7091 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7092 ColonLoc, EndLoc);
7093 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007094 case OMPC_copyin:
7095 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7096 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007097 case OMPC_copyprivate:
7098 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7099 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007100 case OMPC_flush:
7101 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7102 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007103 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007104 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007105 StartLoc, LParenLoc, EndLoc);
7106 break;
7107 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007108 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7109 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7110 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007111 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007112 case OMPC_to:
7113 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7114 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007115 case OMPC_from:
7116 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7117 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007118 case OMPC_use_device_ptr:
7119 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7120 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007121 case OMPC_is_device_ptr:
7122 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7123 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007124 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007125 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007126 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007127 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007128 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007129 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007130 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007131 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007132 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007133 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007134 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007135 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007136 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007137 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007138 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007139 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007140 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007141 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007142 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007143 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007144 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007145 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007146 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007147 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007148 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007149 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007150 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007151 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007152 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007153 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007154 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007155 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007156 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007157 llvm_unreachable("Clause is not allowed.");
7158 }
7159 return Res;
7160}
7161
Alexey Bataev90c228f2016-02-08 09:29:13 +00007162ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007163 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007164 ExprResult Res = BuildDeclRefExpr(
7165 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7166 if (!Res.isUsable())
7167 return ExprError();
7168 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7169 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7170 if (!Res.isUsable())
7171 return ExprError();
7172 }
7173 if (VK != VK_LValue && Res.get()->isGLValue()) {
7174 Res = DefaultLvalueConversion(Res.get());
7175 if (!Res.isUsable())
7176 return ExprError();
7177 }
7178 return Res;
7179}
7180
Alexey Bataev60da77e2016-02-29 05:54:20 +00007181static std::pair<ValueDecl *, bool>
7182getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7183 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007184 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7185 RefExpr->containsUnexpandedParameterPack())
7186 return std::make_pair(nullptr, true);
7187
Alexey Bataevd985eda2016-02-10 11:29:16 +00007188 // OpenMP [3.1, C/C++]
7189 // A list item is a variable name.
7190 // OpenMP [2.9.3.3, Restrictions, p.1]
7191 // A variable that is part of another variable (as an array or
7192 // structure element) cannot appear in a private clause.
7193 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007194 enum {
7195 NoArrayExpr = -1,
7196 ArraySubscript = 0,
7197 OMPArraySection = 1
7198 } IsArrayExpr = NoArrayExpr;
7199 if (AllowArraySection) {
7200 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7201 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7202 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7203 Base = TempASE->getBase()->IgnoreParenImpCasts();
7204 RefExpr = Base;
7205 IsArrayExpr = ArraySubscript;
7206 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7207 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7208 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7209 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7210 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7211 Base = TempASE->getBase()->IgnoreParenImpCasts();
7212 RefExpr = Base;
7213 IsArrayExpr = OMPArraySection;
7214 }
7215 }
7216 ELoc = RefExpr->getExprLoc();
7217 ERange = RefExpr->getSourceRange();
7218 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007219 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7220 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7221 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7222 (S.getCurrentThisType().isNull() || !ME ||
7223 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7224 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007225 if (IsArrayExpr != NoArrayExpr)
7226 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7227 << ERange;
7228 else {
7229 S.Diag(ELoc,
7230 AllowArraySection
7231 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7232 : diag::err_omp_expected_var_name_member_expr)
7233 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7234 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007235 return std::make_pair(nullptr, false);
7236 }
7237 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7238}
7239
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007240OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7241 SourceLocation StartLoc,
7242 SourceLocation LParenLoc,
7243 SourceLocation EndLoc) {
7244 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007245 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007246 for (auto &RefExpr : VarList) {
7247 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007248 SourceLocation ELoc;
7249 SourceRange ERange;
7250 Expr *SimpleRefExpr = RefExpr;
7251 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007252 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007253 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007254 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007255 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007256 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007257 ValueDecl *D = Res.first;
7258 if (!D)
7259 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007260
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007261 QualType Type = D->getType();
7262 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007263
7264 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7265 // A variable that appears in a private clause must not have an incomplete
7266 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007267 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007268 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007269 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007270
Alexey Bataev758e55e2013-09-06 18:03:48 +00007271 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7272 // in a Construct]
7273 // Variables with the predetermined data-sharing attributes may not be
7274 // listed in data-sharing attributes clauses, except for the cases
7275 // listed below. For these exceptions only, listing a predetermined
7276 // variable in a data-sharing attribute clause is allowed and overrides
7277 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007278 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007279 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007280 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7281 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007282 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007283 continue;
7284 }
7285
Kelvin Libf594a52016-12-17 05:48:59 +00007286 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007287 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007288 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007289 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007290 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7291 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007292 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007293 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007294 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007295 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007296 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007297 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007298 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007299 continue;
7300 }
7301
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007302 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7303 // A list item cannot appear in both a map clause and a data-sharing
7304 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007305 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7306 CurrDir == OMPD_target_teams) {
Samuel Antao6890b092016-07-28 14:25:09 +00007307 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007308 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007309 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007310 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7311 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7312 ConflictKind = WhereFoundClauseKind;
7313 return true;
7314 })) {
7315 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007316 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007317 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007318 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007319 ReportOriginalDSA(*this, DSAStack, D, DVar);
7320 continue;
7321 }
7322 }
7323
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007324 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7325 // A variable of class type (or array thereof) that appears in a private
7326 // clause requires an accessible, unambiguous default constructor for the
7327 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007328 // Generate helper private variable and initialize it with the default
7329 // value. The address of the original variable is replaced by the address of
7330 // the new private variable in CodeGen. This new variable is not added to
7331 // IdResolver, so the code in the OpenMP region uses original variable for
7332 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007333 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007334 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7335 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007336 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007337 if (VDPrivate->isInvalidDecl())
7338 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007339 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007340 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007341
Alexey Bataev90c228f2016-02-08 09:29:13 +00007342 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007343 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007344 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007345 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007346 Vars.push_back((VD || CurContext->isDependentContext())
7347 ? RefExpr->IgnoreParens()
7348 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007349 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007350 }
7351
Alexey Bataeved09d242014-05-28 05:53:51 +00007352 if (Vars.empty())
7353 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007354
Alexey Bataev03b340a2014-10-21 03:16:40 +00007355 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7356 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007357}
7358
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007359namespace {
7360class DiagsUninitializedSeveretyRAII {
7361private:
7362 DiagnosticsEngine &Diags;
7363 SourceLocation SavedLoc;
7364 bool IsIgnored;
7365
7366public:
7367 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7368 bool IsIgnored)
7369 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7370 if (!IsIgnored) {
7371 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7372 /*Map*/ diag::Severity::Ignored, Loc);
7373 }
7374 }
7375 ~DiagsUninitializedSeveretyRAII() {
7376 if (!IsIgnored)
7377 Diags.popMappings(SavedLoc);
7378 }
7379};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007380}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007381
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007382OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7383 SourceLocation StartLoc,
7384 SourceLocation LParenLoc,
7385 SourceLocation EndLoc) {
7386 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007387 SmallVector<Expr *, 8> PrivateCopies;
7388 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007389 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007390 bool IsImplicitClause =
7391 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7392 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7393
Alexey Bataeved09d242014-05-28 05:53:51 +00007394 for (auto &RefExpr : VarList) {
7395 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007396 SourceLocation ELoc;
7397 SourceRange ERange;
7398 Expr *SimpleRefExpr = RefExpr;
7399 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007400 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007401 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007402 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007403 PrivateCopies.push_back(nullptr);
7404 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007405 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007406 ValueDecl *D = Res.first;
7407 if (!D)
7408 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007409
Alexey Bataev60da77e2016-02-29 05:54:20 +00007410 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007411 QualType Type = D->getType();
7412 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007413
7414 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7415 // A variable that appears in a private clause must not have an incomplete
7416 // type or a reference type.
7417 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007418 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007419 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007420 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007421
7422 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7423 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007424 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007425 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007426 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007427
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007428 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007429 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007430 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007431 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007432 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007433 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007434 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7435 // A list item that specifies a given variable may not appear in more
7436 // than one clause on the same directive, except that a variable may be
7437 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007438 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007439 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007440 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007441 << getOpenMPClauseName(DVar.CKind)
7442 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007443 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007444 continue;
7445 }
7446
7447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7448 // in a Construct]
7449 // Variables with the predetermined data-sharing attributes may not be
7450 // listed in data-sharing attributes clauses, except for the cases
7451 // listed below. For these exceptions only, listing a predetermined
7452 // variable in a data-sharing attribute clause is allowed and overrides
7453 // the variable's predetermined data-sharing attributes.
7454 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7455 // in a Construct, C/C++, p.2]
7456 // Variables with const-qualified type having no mutable member may be
7457 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007458 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007459 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7460 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007461 << getOpenMPClauseName(DVar.CKind)
7462 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007463 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007464 continue;
7465 }
7466
Alexey Bataevf29276e2014-06-18 04:14:57 +00007467 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007468 // OpenMP [2.9.3.4, Restrictions, p.2]
7469 // A list item that is private within a parallel region must not appear
7470 // in a firstprivate clause on a worksharing construct if any of the
7471 // worksharing regions arising from the worksharing construct ever bind
7472 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007473 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007474 !isOpenMPParallelDirective(CurrDir) &&
7475 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007476 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007477 if (DVar.CKind != OMPC_shared &&
7478 (isOpenMPParallelDirective(DVar.DKind) ||
7479 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007480 Diag(ELoc, diag::err_omp_required_access)
7481 << getOpenMPClauseName(OMPC_firstprivate)
7482 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007483 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007484 continue;
7485 }
7486 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007487 // OpenMP [2.9.3.4, Restrictions, p.3]
7488 // A list item that appears in a reduction clause of a parallel construct
7489 // must not appear in a firstprivate clause on a worksharing or task
7490 // construct if any of the worksharing or task regions arising from the
7491 // worksharing or task construct ever bind to any of the parallel regions
7492 // arising from the parallel construct.
7493 // OpenMP [2.9.3.4, Restrictions, p.4]
7494 // A list item that appears in a reduction clause in worksharing
7495 // construct must not appear in a firstprivate clause in a task construct
7496 // encountered during execution of any of the worksharing regions arising
7497 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007498 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007499 DVar = DSAStack->hasInnermostDSA(
7500 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7501 [](OpenMPDirectiveKind K) -> bool {
7502 return isOpenMPParallelDirective(K) ||
7503 isOpenMPWorksharingDirective(K);
7504 },
7505 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007506 if (DVar.CKind == OMPC_reduction &&
7507 (isOpenMPParallelDirective(DVar.DKind) ||
7508 isOpenMPWorksharingDirective(DVar.DKind))) {
7509 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7510 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007511 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007512 continue;
7513 }
7514 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007515
7516 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7517 // A list item that is private within a teams region must not appear in a
7518 // firstprivate clause on a distribute construct if any of the distribute
7519 // regions arising from the distribute construct ever bind to any of the
7520 // teams regions arising from the teams construct.
7521 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7522 // A list item that appears in a reduction clause of a teams construct
7523 // must not appear in a firstprivate clause on a distribute construct if
7524 // any of the distribute regions arising from the distribute construct
7525 // ever bind to any of the teams regions arising from the teams construct.
7526 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7527 // A list item may appear in a firstprivate or lastprivate clause but not
7528 // both.
7529 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007530 DVar = DSAStack->hasInnermostDSA(
7531 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7532 [](OpenMPDirectiveKind K) -> bool {
7533 return isOpenMPTeamsDirective(K);
7534 },
7535 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007536 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7537 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007538 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007539 continue;
7540 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007541 DVar = DSAStack->hasInnermostDSA(
7542 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7543 [](OpenMPDirectiveKind K) -> bool {
7544 return isOpenMPTeamsDirective(K);
7545 },
7546 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007547 if (DVar.CKind == OMPC_reduction &&
7548 isOpenMPTeamsDirective(DVar.DKind)) {
7549 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007550 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007551 continue;
7552 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007553 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007554 if (DVar.CKind == OMPC_lastprivate) {
7555 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007556 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007557 continue;
7558 }
7559 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007560 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7561 // A list item cannot appear in both a map clause and a data-sharing
7562 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007563 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7564 CurrDir == OMPD_target_teams) {
Samuel Antao6890b092016-07-28 14:25:09 +00007565 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007566 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007567 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007568 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7569 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7570 ConflictKind = WhereFoundClauseKind;
7571 return true;
7572 })) {
7573 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007574 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007575 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007576 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7577 ReportOriginalDSA(*this, DSAStack, D, DVar);
7578 continue;
7579 }
7580 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007581 }
7582
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007583 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007584 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007585 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007586 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7587 << getOpenMPClauseName(OMPC_firstprivate) << Type
7588 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7589 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007590 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007591 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007592 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007593 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007594 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007595 continue;
7596 }
7597
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007598 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007599 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7600 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007601 // Generate helper private variable and initialize it with the value of the
7602 // original variable. The address of the original variable is replaced by
7603 // the address of the new private variable in the CodeGen. This new variable
7604 // is not added to IdResolver, so the code in the OpenMP region uses
7605 // original variable for proper diagnostics and variable capturing.
7606 Expr *VDInitRefExpr = nullptr;
7607 // For arrays generate initializer for single element and replace it by the
7608 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007609 if (Type->isArrayType()) {
7610 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007611 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007612 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007613 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007614 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007615 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007616 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007617 InitializedEntity Entity =
7618 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007619 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7620
7621 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7622 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7623 if (Result.isInvalid())
7624 VDPrivate->setInvalidDecl();
7625 else
7626 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007627 // Remove temp variable declaration.
7628 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007629 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007630 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7631 ".firstprivate.temp");
7632 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7633 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007634 AddInitializerToDecl(VDPrivate,
7635 DefaultLvalueConversion(VDInitRefExpr).get(),
7636 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007637 }
7638 if (VDPrivate->isInvalidDecl()) {
7639 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007640 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007641 diag::note_omp_task_predetermined_firstprivate_here);
7642 }
7643 continue;
7644 }
7645 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007646 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007647 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7648 RefExpr->getExprLoc());
7649 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007650 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007651 if (TopDVar.CKind == OMPC_lastprivate)
7652 Ref = TopDVar.PrivateCopy;
7653 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007654 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007655 if (!IsOpenMPCapturedDecl(D))
7656 ExprCaptures.push_back(Ref->getDecl());
7657 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007658 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007659 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007660 Vars.push_back((VD || CurContext->isDependentContext())
7661 ? RefExpr->IgnoreParens()
7662 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007663 PrivateCopies.push_back(VDPrivateRefExpr);
7664 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007665 }
7666
Alexey Bataeved09d242014-05-28 05:53:51 +00007667 if (Vars.empty())
7668 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007669
7670 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007671 Vars, PrivateCopies, Inits,
7672 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007673}
7674
Alexander Musman1bb328c2014-06-04 13:06:39 +00007675OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7676 SourceLocation StartLoc,
7677 SourceLocation LParenLoc,
7678 SourceLocation EndLoc) {
7679 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007680 SmallVector<Expr *, 8> SrcExprs;
7681 SmallVector<Expr *, 8> DstExprs;
7682 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007683 SmallVector<Decl *, 4> ExprCaptures;
7684 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007685 for (auto &RefExpr : VarList) {
7686 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007687 SourceLocation ELoc;
7688 SourceRange ERange;
7689 Expr *SimpleRefExpr = RefExpr;
7690 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007691 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007692 // It will be analyzed later.
7693 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007694 SrcExprs.push_back(nullptr);
7695 DstExprs.push_back(nullptr);
7696 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007697 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007698 ValueDecl *D = Res.first;
7699 if (!D)
7700 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007701
Alexey Bataev74caaf22016-02-20 04:09:36 +00007702 QualType Type = D->getType();
7703 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007704
7705 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7706 // A variable that appears in a lastprivate clause must not have an
7707 // incomplete type or a reference type.
7708 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007709 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007710 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007711 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007712
7713 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7714 // in a Construct]
7715 // Variables with the predetermined data-sharing attributes may not be
7716 // listed in data-sharing attributes clauses, except for the cases
7717 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007718 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007719 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7720 DVar.CKind != OMPC_firstprivate &&
7721 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7722 Diag(ELoc, diag::err_omp_wrong_dsa)
7723 << getOpenMPClauseName(DVar.CKind)
7724 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007725 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007726 continue;
7727 }
7728
Alexey Bataevf29276e2014-06-18 04:14:57 +00007729 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7730 // OpenMP [2.14.3.5, Restrictions, p.2]
7731 // A list item that is private within a parallel region, or that appears in
7732 // the reduction clause of a parallel construct, must not appear in a
7733 // lastprivate clause on a worksharing construct if any of the corresponding
7734 // worksharing regions ever binds to any of the corresponding parallel
7735 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007736 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007737 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007738 !isOpenMPParallelDirective(CurrDir) &&
7739 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007740 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007741 if (DVar.CKind != OMPC_shared) {
7742 Diag(ELoc, diag::err_omp_required_access)
7743 << getOpenMPClauseName(OMPC_lastprivate)
7744 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007745 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007746 continue;
7747 }
7748 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007749
7750 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7751 // A list item may appear in a firstprivate or lastprivate clause but not
7752 // both.
7753 if (CurrDir == OMPD_distribute) {
7754 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7755 if (DVar.CKind == OMPC_firstprivate) {
7756 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7757 ReportOriginalDSA(*this, DSAStack, D, DVar);
7758 continue;
7759 }
7760 }
7761
Alexander Musman1bb328c2014-06-04 13:06:39 +00007762 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007763 // A variable of class type (or array thereof) that appears in a
7764 // lastprivate clause requires an accessible, unambiguous default
7765 // constructor for the class type, unless the list item is also specified
7766 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007767 // A variable of class type (or array thereof) that appears in a
7768 // lastprivate clause requires an accessible, unambiguous copy assignment
7769 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007770 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007771 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007772 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007773 D->hasAttrs() ? &D->getAttrs() : nullptr);
7774 auto *PseudoSrcExpr =
7775 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007776 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007777 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007778 D->hasAttrs() ? &D->getAttrs() : nullptr);
7779 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007780 // For arrays generate assignment operation for single element and replace
7781 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007782 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007783 PseudoDstExpr, PseudoSrcExpr);
7784 if (AssignmentOp.isInvalid())
7785 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007786 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007787 /*DiscardedValue=*/true);
7788 if (AssignmentOp.isInvalid())
7789 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007790
Alexey Bataev74caaf22016-02-20 04:09:36 +00007791 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007792 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007793 if (TopDVar.CKind == OMPC_firstprivate)
7794 Ref = TopDVar.PrivateCopy;
7795 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007796 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007797 if (!IsOpenMPCapturedDecl(D))
7798 ExprCaptures.push_back(Ref->getDecl());
7799 }
7800 if (TopDVar.CKind == OMPC_firstprivate ||
7801 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007802 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007803 ExprResult RefRes = DefaultLvalueConversion(Ref);
7804 if (!RefRes.isUsable())
7805 continue;
7806 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007807 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7808 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007809 if (!PostUpdateRes.isUsable())
7810 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00007811 ExprPostUpdates.push_back(
7812 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007813 }
7814 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007815 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007816 Vars.push_back((VD || CurContext->isDependentContext())
7817 ? RefExpr->IgnoreParens()
7818 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00007819 SrcExprs.push_back(PseudoSrcExpr);
7820 DstExprs.push_back(PseudoDstExpr);
7821 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00007822 }
7823
7824 if (Vars.empty())
7825 return nullptr;
7826
7827 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00007828 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007829 buildPreInits(Context, ExprCaptures),
7830 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00007831}
7832
Alexey Bataev758e55e2013-09-06 18:03:48 +00007833OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7834 SourceLocation StartLoc,
7835 SourceLocation LParenLoc,
7836 SourceLocation EndLoc) {
7837 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00007838 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007839 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007840 SourceLocation ELoc;
7841 SourceRange ERange;
7842 Expr *SimpleRefExpr = RefExpr;
7843 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007844 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00007845 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007846 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007847 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007848 ValueDecl *D = Res.first;
7849 if (!D)
7850 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007851
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007852 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007853 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7854 // in a Construct]
7855 // Variables with the predetermined data-sharing attributes may not be
7856 // listed in data-sharing attributes clauses, except for the cases
7857 // listed below. For these exceptions only, listing a predetermined
7858 // variable in a data-sharing attribute clause is allowed and overrides
7859 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007860 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00007861 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7862 DVar.RefExpr) {
7863 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7864 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007865 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007866 continue;
7867 }
7868
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007869 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007870 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007871 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007872 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007873 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7874 ? RefExpr->IgnoreParens()
7875 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007876 }
7877
Alexey Bataeved09d242014-05-28 05:53:51 +00007878 if (Vars.empty())
7879 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007880
7881 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7882}
7883
Alexey Bataevc5e02582014-06-16 07:08:35 +00007884namespace {
7885class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7886 DSAStackTy *Stack;
7887
7888public:
7889 bool VisitDeclRefExpr(DeclRefExpr *E) {
7890 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007891 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007892 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7893 return false;
7894 if (DVar.CKind != OMPC_unknown)
7895 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007896 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7897 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7898 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007899 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00007900 return true;
7901 return false;
7902 }
7903 return false;
7904 }
7905 bool VisitStmt(Stmt *S) {
7906 for (auto Child : S->children()) {
7907 if (Child && Visit(Child))
7908 return true;
7909 }
7910 return false;
7911 }
Alexey Bataev23b69422014-06-18 07:08:49 +00007912 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00007913};
Alexey Bataev23b69422014-06-18 07:08:49 +00007914} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00007915
Alexey Bataev60da77e2016-02-29 05:54:20 +00007916namespace {
7917// Transform MemberExpression for specified FieldDecl of current class to
7918// DeclRefExpr to specified OMPCapturedExprDecl.
7919class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
7920 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
7921 ValueDecl *Field;
7922 DeclRefExpr *CapturedExpr;
7923
7924public:
7925 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
7926 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
7927
7928 ExprResult TransformMemberExpr(MemberExpr *E) {
7929 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
7930 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00007931 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00007932 return CapturedExpr;
7933 }
7934 return BaseTransform::TransformMemberExpr(E);
7935 }
7936 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
7937};
7938} // namespace
7939
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007940template <typename T>
7941static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
7942 const llvm::function_ref<T(ValueDecl *)> &Gen) {
7943 for (auto &Set : Lookups) {
7944 for (auto *D : Set) {
7945 if (auto Res = Gen(cast<ValueDecl>(D)))
7946 return Res;
7947 }
7948 }
7949 return T();
7950}
7951
7952static ExprResult
7953buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
7954 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
7955 const DeclarationNameInfo &ReductionId, QualType Ty,
7956 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
7957 if (ReductionIdScopeSpec.isInvalid())
7958 return ExprError();
7959 SmallVector<UnresolvedSet<8>, 4> Lookups;
7960 if (S) {
7961 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
7962 Lookup.suppressDiagnostics();
7963 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
7964 auto *D = Lookup.getRepresentativeDecl();
7965 do {
7966 S = S->getParent();
7967 } while (S && !S->isDeclScope(D));
7968 if (S)
7969 S = S->getParent();
7970 Lookups.push_back(UnresolvedSet<8>());
7971 Lookups.back().append(Lookup.begin(), Lookup.end());
7972 Lookup.clear();
7973 }
7974 } else if (auto *ULE =
7975 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
7976 Lookups.push_back(UnresolvedSet<8>());
7977 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00007978 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007979 if (D == PrevD)
7980 Lookups.push_back(UnresolvedSet<8>());
7981 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
7982 Lookups.back().addDecl(DRD);
7983 PrevD = D;
7984 }
7985 }
7986 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
7987 Ty->containsUnexpandedParameterPack() ||
7988 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
7989 return !D->isInvalidDecl() &&
7990 (D->getType()->isDependentType() ||
7991 D->getType()->isInstantiationDependentType() ||
7992 D->getType()->containsUnexpandedParameterPack());
7993 })) {
7994 UnresolvedSet<8> ResSet;
7995 for (auto &Set : Lookups) {
7996 ResSet.append(Set.begin(), Set.end());
7997 // The last item marks the end of all declarations at the specified scope.
7998 ResSet.addDecl(Set[Set.size() - 1]);
7999 }
8000 return UnresolvedLookupExpr::Create(
8001 SemaRef.Context, /*NamingClass=*/nullptr,
8002 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8003 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8004 }
8005 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8006 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8007 if (!D->isInvalidDecl() &&
8008 SemaRef.Context.hasSameType(D->getType(), Ty))
8009 return D;
8010 return nullptr;
8011 }))
8012 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8013 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8014 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8015 if (!D->isInvalidDecl() &&
8016 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8017 !Ty.isMoreQualifiedThan(D->getType()))
8018 return D;
8019 return nullptr;
8020 })) {
8021 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8022 /*DetectVirtual=*/false);
8023 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8024 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8025 VD->getType().getUnqualifiedType()))) {
8026 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8027 /*DiagID=*/0) !=
8028 Sema::AR_inaccessible) {
8029 SemaRef.BuildBasePathArray(Paths, BasePath);
8030 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8031 }
8032 }
8033 }
8034 }
8035 if (ReductionIdScopeSpec.isSet()) {
8036 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8037 return ExprError();
8038 }
8039 return ExprEmpty();
8040}
8041
Alexey Bataevc5e02582014-06-16 07:08:35 +00008042OMPClause *Sema::ActOnOpenMPReductionClause(
8043 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8044 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008045 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8046 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008047 auto DN = ReductionId.getName();
8048 auto OOK = DN.getCXXOverloadedOperator();
8049 BinaryOperatorKind BOK = BO_Comma;
8050
8051 // OpenMP [2.14.3.6, reduction clause]
8052 // C
8053 // reduction-identifier is either an identifier or one of the following
8054 // operators: +, -, *, &, |, ^, && and ||
8055 // C++
8056 // reduction-identifier is either an id-expression or one of the following
8057 // operators: +, -, *, &, |, ^, && and ||
8058 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8059 switch (OOK) {
8060 case OO_Plus:
8061 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008062 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008063 break;
8064 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008065 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008066 break;
8067 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008068 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008069 break;
8070 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008071 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008072 break;
8073 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008074 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008075 break;
8076 case OO_AmpAmp:
8077 BOK = BO_LAnd;
8078 break;
8079 case OO_PipePipe:
8080 BOK = BO_LOr;
8081 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008082 case OO_New:
8083 case OO_Delete:
8084 case OO_Array_New:
8085 case OO_Array_Delete:
8086 case OO_Slash:
8087 case OO_Percent:
8088 case OO_Tilde:
8089 case OO_Exclaim:
8090 case OO_Equal:
8091 case OO_Less:
8092 case OO_Greater:
8093 case OO_LessEqual:
8094 case OO_GreaterEqual:
8095 case OO_PlusEqual:
8096 case OO_MinusEqual:
8097 case OO_StarEqual:
8098 case OO_SlashEqual:
8099 case OO_PercentEqual:
8100 case OO_CaretEqual:
8101 case OO_AmpEqual:
8102 case OO_PipeEqual:
8103 case OO_LessLess:
8104 case OO_GreaterGreater:
8105 case OO_LessLessEqual:
8106 case OO_GreaterGreaterEqual:
8107 case OO_EqualEqual:
8108 case OO_ExclaimEqual:
8109 case OO_PlusPlus:
8110 case OO_MinusMinus:
8111 case OO_Comma:
8112 case OO_ArrowStar:
8113 case OO_Arrow:
8114 case OO_Call:
8115 case OO_Subscript:
8116 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008117 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008118 case NUM_OVERLOADED_OPERATORS:
8119 llvm_unreachable("Unexpected reduction identifier");
8120 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008121 if (auto II = DN.getAsIdentifierInfo()) {
8122 if (II->isStr("max"))
8123 BOK = BO_GT;
8124 else if (II->isStr("min"))
8125 BOK = BO_LT;
8126 }
8127 break;
8128 }
8129 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008130 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008131 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008132 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008133
8134 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008135 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008136 SmallVector<Expr *, 8> LHSs;
8137 SmallVector<Expr *, 8> RHSs;
8138 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008139 SmallVector<Decl *, 4> ExprCaptures;
8140 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008141 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8142 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008143 for (auto RefExpr : VarList) {
8144 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008145 // OpenMP [2.1, C/C++]
8146 // A list item is a variable or array section, subject to the restrictions
8147 // specified in Section 2.4 on page 42 and in each of the sections
8148 // describing clauses and directives for which a list appears.
8149 // OpenMP [2.14.3.3, Restrictions, p.1]
8150 // A variable that is part of another variable (as an array or
8151 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008152 if (!FirstIter && IR != ER)
8153 ++IR;
8154 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008155 SourceLocation ELoc;
8156 SourceRange ERange;
8157 Expr *SimpleRefExpr = RefExpr;
8158 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8159 /*AllowArraySection=*/true);
8160 if (Res.second) {
8161 // It will be analyzed later.
8162 Vars.push_back(RefExpr);
8163 Privates.push_back(nullptr);
8164 LHSs.push_back(nullptr);
8165 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008166 // Try to find 'declare reduction' corresponding construct before using
8167 // builtin/overloaded operators.
8168 QualType Type = Context.DependentTy;
8169 CXXCastPath BasePath;
8170 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8171 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8172 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8173 if (CurContext->isDependentContext() &&
8174 (DeclareReductionRef.isUnset() ||
8175 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8176 ReductionOps.push_back(DeclareReductionRef.get());
8177 else
8178 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008179 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008180 ValueDecl *D = Res.first;
8181 if (!D)
8182 continue;
8183
Alexey Bataeva1764212015-09-30 09:22:36 +00008184 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008185 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8186 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8187 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008188 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008189 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008190 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8191 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8192 Type = ATy->getElementType();
8193 else
8194 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008195 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008196 } else
8197 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8198 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008199
Alexey Bataevc5e02582014-06-16 07:08:35 +00008200 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8201 // A variable that appears in a private clause must not have an incomplete
8202 // type or a reference type.
8203 if (RequireCompleteType(ELoc, Type,
8204 diag::err_omp_reduction_incomplete_type))
8205 continue;
8206 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008207 // A list item that appears in a reduction clause must not be
8208 // const-qualified.
8209 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008210 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008211 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008212 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008213 bool IsDecl = !VD ||
8214 VD->isThisDeclarationADefinition(Context) ==
8215 VarDecl::DeclarationOnly;
8216 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008217 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008218 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008219 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008220 continue;
8221 }
8222 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8223 // If a list-item is a reference type then it must bind to the same object
8224 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008225 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008226 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008227 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008228 DSARefChecker Check(DSAStack);
8229 if (Check.Visit(VDDef->getInit())) {
8230 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8231 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8232 continue;
8233 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008234 }
8235 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008236
Alexey Bataevc5e02582014-06-16 07:08:35 +00008237 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8238 // in a Construct]
8239 // Variables with the predetermined data-sharing attributes may not be
8240 // listed in data-sharing attributes clauses, except for the cases
8241 // listed below. For these exceptions only, listing a predetermined
8242 // variable in a data-sharing attribute clause is allowed and overrides
8243 // the variable's predetermined data-sharing attributes.
8244 // OpenMP [2.14.3.6, Restrictions, p.3]
8245 // Any number of reduction clauses can be specified on the directive,
8246 // but a list item can appear only once in the reduction clauses for that
8247 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008248 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008249 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008250 if (DVar.CKind == OMPC_reduction) {
8251 Diag(ELoc, diag::err_omp_once_referenced)
8252 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008253 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008254 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008255 } else if (DVar.CKind != OMPC_unknown) {
8256 Diag(ELoc, diag::err_omp_wrong_dsa)
8257 << getOpenMPClauseName(DVar.CKind)
8258 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008259 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008260 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008261 }
8262
8263 // OpenMP [2.14.3.6, Restrictions, p.1]
8264 // A list item that appears in a reduction clause of a worksharing
8265 // construct must be shared in the parallel regions to which any of the
8266 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008267 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8268 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008269 !isOpenMPParallelDirective(CurrDir) &&
8270 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008271 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008272 if (DVar.CKind != OMPC_shared) {
8273 Diag(ELoc, diag::err_omp_required_access)
8274 << getOpenMPClauseName(OMPC_reduction)
8275 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008276 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008277 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008278 }
8279 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008280
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008281 // Try to find 'declare reduction' corresponding construct before using
8282 // builtin/overloaded operators.
8283 CXXCastPath BasePath;
8284 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8285 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8286 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8287 if (DeclareReductionRef.isInvalid())
8288 continue;
8289 if (CurContext->isDependentContext() &&
8290 (DeclareReductionRef.isUnset() ||
8291 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8292 Vars.push_back(RefExpr);
8293 Privates.push_back(nullptr);
8294 LHSs.push_back(nullptr);
8295 RHSs.push_back(nullptr);
8296 ReductionOps.push_back(DeclareReductionRef.get());
8297 continue;
8298 }
8299 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8300 // Not allowed reduction identifier is found.
8301 Diag(ReductionId.getLocStart(),
8302 diag::err_omp_unknown_reduction_identifier)
8303 << Type << ReductionIdRange;
8304 continue;
8305 }
8306
8307 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8308 // The type of a list item that appears in a reduction clause must be valid
8309 // for the reduction-identifier. For a max or min reduction in C, the type
8310 // of the list item must be an allowed arithmetic data type: char, int,
8311 // float, double, or _Bool, possibly modified with long, short, signed, or
8312 // unsigned. For a max or min reduction in C++, the type of the list item
8313 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8314 // double, or bool, possibly modified with long, short, signed, or unsigned.
8315 if (DeclareReductionRef.isUnset()) {
8316 if ((BOK == BO_GT || BOK == BO_LT) &&
8317 !(Type->isScalarType() ||
8318 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8319 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8320 << getLangOpts().CPlusPlus;
8321 if (!ASE && !OASE) {
8322 bool IsDecl = !VD ||
8323 VD->isThisDeclarationADefinition(Context) ==
8324 VarDecl::DeclarationOnly;
8325 Diag(D->getLocation(),
8326 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8327 << D;
8328 }
8329 continue;
8330 }
8331 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8332 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8333 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8334 if (!ASE && !OASE) {
8335 bool IsDecl = !VD ||
8336 VD->isThisDeclarationADefinition(Context) ==
8337 VarDecl::DeclarationOnly;
8338 Diag(D->getLocation(),
8339 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8340 << D;
8341 }
8342 continue;
8343 }
8344 }
8345
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008346 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008347 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008348 D->hasAttrs() ? &D->getAttrs() : nullptr);
8349 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8350 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008351 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008352 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008353 (!ASE &&
8354 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008355 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008356 // Create pseudo array type for private copy. The size for this array will
8357 // be generated during codegen.
8358 // For array subscripts or single variables Private Ty is the same as Type
8359 // (type of the variable or single array element).
8360 PrivateTy = Context.getVariableArrayType(
8361 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8362 Context.getSizeType(), VK_RValue),
8363 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008364 } else if (!ASE && !OASE &&
8365 Context.getAsArrayType(D->getType().getNonReferenceType()))
8366 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008367 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008368 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8369 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008370 // Add initializer for private variable.
8371 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008372 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8373 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8374 if (DeclareReductionRef.isUsable()) {
8375 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8376 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8377 if (DRD->getInitializer()) {
8378 Init = DRDRef;
8379 RHSVD->setInit(DRDRef);
8380 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008381 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008382 } else {
8383 switch (BOK) {
8384 case BO_Add:
8385 case BO_Xor:
8386 case BO_Or:
8387 case BO_LOr:
8388 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8389 if (Type->isScalarType() || Type->isAnyComplexType())
8390 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8391 break;
8392 case BO_Mul:
8393 case BO_LAnd:
8394 if (Type->isScalarType() || Type->isAnyComplexType()) {
8395 // '*' and '&&' reduction ops - initializer is '1'.
8396 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008397 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008398 break;
8399 case BO_And: {
8400 // '&' reduction op - initializer is '~0'.
8401 QualType OrigType = Type;
8402 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8403 Type = ComplexTy->getElementType();
8404 if (Type->isRealFloatingType()) {
8405 llvm::APFloat InitValue =
8406 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8407 /*isIEEE=*/true);
8408 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8409 Type, ELoc);
8410 } else if (Type->isScalarType()) {
8411 auto Size = Context.getTypeSize(Type);
8412 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8413 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8414 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8415 }
8416 if (Init && OrigType->isAnyComplexType()) {
8417 // Init = 0xFFFF + 0xFFFFi;
8418 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8419 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8420 }
8421 Type = OrigType;
8422 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008423 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008424 case BO_LT:
8425 case BO_GT: {
8426 // 'min' reduction op - initializer is 'Largest representable number in
8427 // the reduction list item type'.
8428 // 'max' reduction op - initializer is 'Least representable number in
8429 // the reduction list item type'.
8430 if (Type->isIntegerType() || Type->isPointerType()) {
8431 bool IsSigned = Type->hasSignedIntegerRepresentation();
8432 auto Size = Context.getTypeSize(Type);
8433 QualType IntTy =
8434 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8435 llvm::APInt InitValue =
8436 (BOK != BO_LT)
8437 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8438 : llvm::APInt::getMinValue(Size)
8439 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8440 : llvm::APInt::getMaxValue(Size);
8441 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8442 if (Type->isPointerType()) {
8443 // Cast to pointer type.
8444 auto CastExpr = BuildCStyleCastExpr(
8445 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8446 SourceLocation(), Init);
8447 if (CastExpr.isInvalid())
8448 continue;
8449 Init = CastExpr.get();
8450 }
8451 } else if (Type->isRealFloatingType()) {
8452 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8453 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8454 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8455 Type, ELoc);
8456 }
8457 break;
8458 }
8459 case BO_PtrMemD:
8460 case BO_PtrMemI:
8461 case BO_MulAssign:
8462 case BO_Div:
8463 case BO_Rem:
8464 case BO_Sub:
8465 case BO_Shl:
8466 case BO_Shr:
8467 case BO_LE:
8468 case BO_GE:
8469 case BO_EQ:
8470 case BO_NE:
8471 case BO_AndAssign:
8472 case BO_XorAssign:
8473 case BO_OrAssign:
8474 case BO_Assign:
8475 case BO_AddAssign:
8476 case BO_SubAssign:
8477 case BO_DivAssign:
8478 case BO_RemAssign:
8479 case BO_ShlAssign:
8480 case BO_ShrAssign:
8481 case BO_Comma:
8482 llvm_unreachable("Unexpected reduction operation");
8483 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008484 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008485 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008486 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8487 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008488 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008489 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008490 if (RHSVD->isInvalidDecl())
8491 continue;
8492 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008493 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8494 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008495 bool IsDecl =
8496 !VD ||
8497 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8498 Diag(D->getLocation(),
8499 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8500 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008501 continue;
8502 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008503 // Store initializer for single element in private copy. Will be used during
8504 // codegen.
8505 PrivateVD->setInit(RHSVD->getInit());
8506 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008507 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008508 ExprResult ReductionOp;
8509 if (DeclareReductionRef.isUsable()) {
8510 QualType RedTy = DeclareReductionRef.get()->getType();
8511 QualType PtrRedTy = Context.getPointerType(RedTy);
8512 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8513 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8514 if (!BasePath.empty()) {
8515 LHS = DefaultLvalueConversion(LHS.get());
8516 RHS = DefaultLvalueConversion(RHS.get());
8517 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8518 CK_UncheckedDerivedToBase, LHS.get(),
8519 &BasePath, LHS.get()->getValueKind());
8520 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8521 CK_UncheckedDerivedToBase, RHS.get(),
8522 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008523 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008524 FunctionProtoType::ExtProtoInfo EPI;
8525 QualType Params[] = {PtrRedTy, PtrRedTy};
8526 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8527 auto *OVE = new (Context) OpaqueValueExpr(
8528 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8529 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8530 Expr *Args[] = {LHS.get(), RHS.get()};
8531 ReductionOp = new (Context)
8532 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8533 } else {
8534 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8535 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8536 if (ReductionOp.isUsable()) {
8537 if (BOK != BO_LT && BOK != BO_GT) {
8538 ReductionOp =
8539 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8540 BO_Assign, LHSDRE, ReductionOp.get());
8541 } else {
8542 auto *ConditionalOp = new (Context) ConditionalOperator(
8543 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8544 RHSDRE, Type, VK_LValue, OK_Ordinary);
8545 ReductionOp =
8546 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8547 BO_Assign, LHSDRE, ConditionalOp);
8548 }
8549 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8550 }
8551 if (ReductionOp.isInvalid())
8552 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008553 }
8554
Alexey Bataev60da77e2016-02-29 05:54:20 +00008555 DeclRefExpr *Ref = nullptr;
8556 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008557 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008558 if (ASE || OASE) {
8559 TransformExprToCaptures RebuildToCapture(*this, D);
8560 VarsExpr =
8561 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8562 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008563 } else {
8564 VarsExpr = Ref =
8565 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008566 }
8567 if (!IsOpenMPCapturedDecl(D)) {
8568 ExprCaptures.push_back(Ref->getDecl());
8569 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8570 ExprResult RefRes = DefaultLvalueConversion(Ref);
8571 if (!RefRes.isUsable())
8572 continue;
8573 ExprResult PostUpdateRes =
8574 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8575 SimpleRefExpr, RefRes.get());
8576 if (!PostUpdateRes.isUsable())
8577 continue;
8578 ExprPostUpdates.push_back(
8579 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008580 }
8581 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008582 }
8583 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8584 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008585 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008586 LHSs.push_back(LHSDRE);
8587 RHSs.push_back(RHSDRE);
8588 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008589 }
8590
8591 if (Vars.empty())
8592 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008593
Alexey Bataevc5e02582014-06-16 07:08:35 +00008594 return OMPReductionClause::Create(
8595 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008596 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008597 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8598 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008599}
8600
Alexey Bataevecba70f2016-04-12 11:02:11 +00008601bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8602 SourceLocation LinLoc) {
8603 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8604 LinKind == OMPC_LINEAR_unknown) {
8605 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8606 return true;
8607 }
8608 return false;
8609}
8610
8611bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8612 OpenMPLinearClauseKind LinKind,
8613 QualType Type) {
8614 auto *VD = dyn_cast_or_null<VarDecl>(D);
8615 // A variable must not have an incomplete type or a reference type.
8616 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8617 return true;
8618 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8619 !Type->isReferenceType()) {
8620 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8621 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8622 return true;
8623 }
8624 Type = Type.getNonReferenceType();
8625
8626 // A list item must not be const-qualified.
8627 if (Type.isConstant(Context)) {
8628 Diag(ELoc, diag::err_omp_const_variable)
8629 << getOpenMPClauseName(OMPC_linear);
8630 if (D) {
8631 bool IsDecl =
8632 !VD ||
8633 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8634 Diag(D->getLocation(),
8635 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8636 << D;
8637 }
8638 return true;
8639 }
8640
8641 // A list item must be of integral or pointer type.
8642 Type = Type.getUnqualifiedType().getCanonicalType();
8643 const auto *Ty = Type.getTypePtrOrNull();
8644 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8645 !Ty->isPointerType())) {
8646 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8647 if (D) {
8648 bool IsDecl =
8649 !VD ||
8650 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8651 Diag(D->getLocation(),
8652 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8653 << D;
8654 }
8655 return true;
8656 }
8657 return false;
8658}
8659
Alexey Bataev182227b2015-08-20 10:54:39 +00008660OMPClause *Sema::ActOnOpenMPLinearClause(
8661 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8662 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8663 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008664 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008665 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008666 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008667 SmallVector<Decl *, 4> ExprCaptures;
8668 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008669 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008670 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008671 for (auto &RefExpr : VarList) {
8672 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008673 SourceLocation ELoc;
8674 SourceRange ERange;
8675 Expr *SimpleRefExpr = RefExpr;
8676 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8677 /*AllowArraySection=*/false);
8678 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008679 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008680 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008681 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008682 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008683 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008684 ValueDecl *D = Res.first;
8685 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008686 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008687
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008688 QualType Type = D->getType();
8689 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008690
8691 // OpenMP [2.14.3.7, linear clause]
8692 // A list-item cannot appear in more than one linear clause.
8693 // A list-item that appears in a linear clause cannot appear in any
8694 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008695 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008696 if (DVar.RefExpr) {
8697 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8698 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008699 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008700 continue;
8701 }
8702
Alexey Bataevecba70f2016-04-12 11:02:11 +00008703 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008704 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008705 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008706
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008707 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008708 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8709 D->hasAttrs() ? &D->getAttrs() : nullptr);
8710 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008711 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008712 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008713 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008714 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008715 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008716 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8717 if (!IsOpenMPCapturedDecl(D)) {
8718 ExprCaptures.push_back(Ref->getDecl());
8719 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8720 ExprResult RefRes = DefaultLvalueConversion(Ref);
8721 if (!RefRes.isUsable())
8722 continue;
8723 ExprResult PostUpdateRes =
8724 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8725 SimpleRefExpr, RefRes.get());
8726 if (!PostUpdateRes.isUsable())
8727 continue;
8728 ExprPostUpdates.push_back(
8729 IgnoredValueConversions(PostUpdateRes.get()).get());
8730 }
8731 }
8732 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008733 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008734 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008735 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008736 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008737 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008738 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8739 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8740
8741 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008742 Vars.push_back((VD || CurContext->isDependentContext())
8743 ? RefExpr->IgnoreParens()
8744 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008745 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008746 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008747 }
8748
8749 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008750 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008751
8752 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008753 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008754 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8755 !Step->isInstantiationDependent() &&
8756 !Step->containsUnexpandedParameterPack()) {
8757 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008758 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008759 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008760 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008761 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008762
Alexander Musman3276a272015-03-21 10:12:56 +00008763 // Build var to save the step value.
8764 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008765 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008766 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008767 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008768 ExprResult CalcStep =
8769 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008770 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008771
Alexander Musman8dba6642014-04-22 13:09:42 +00008772 // Warn about zero linear step (it would be probably better specified as
8773 // making corresponding variables 'const').
8774 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008775 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8776 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008777 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8778 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008779 if (!IsConstant && CalcStep.isUsable()) {
8780 // Calculate the step beforehand instead of doing this on each iteration.
8781 // (This is not used if the number of iterations may be kfold-ed).
8782 CalcStepExpr = CalcStep.get();
8783 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008784 }
8785
Alexey Bataev182227b2015-08-20 10:54:39 +00008786 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8787 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008788 StepExpr, CalcStepExpr,
8789 buildPreInits(Context, ExprCaptures),
8790 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008791}
8792
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008793static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8794 Expr *NumIterations, Sema &SemaRef,
8795 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008796 // Walk the vars and build update/final expressions for the CodeGen.
8797 SmallVector<Expr *, 8> Updates;
8798 SmallVector<Expr *, 8> Finals;
8799 Expr *Step = Clause.getStep();
8800 Expr *CalcStep = Clause.getCalcStep();
8801 // OpenMP [2.14.3.7, linear clause]
8802 // If linear-step is not specified it is assumed to be 1.
8803 if (Step == nullptr)
8804 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008805 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00008806 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008807 }
Alexander Musman3276a272015-03-21 10:12:56 +00008808 bool HasErrors = false;
8809 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008810 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008811 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00008812 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008813 SourceLocation ELoc;
8814 SourceRange ERange;
8815 Expr *SimpleRefExpr = RefExpr;
8816 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8817 /*AllowArraySection=*/false);
8818 ValueDecl *D = Res.first;
8819 if (Res.second || !D) {
8820 Updates.push_back(nullptr);
8821 Finals.push_back(nullptr);
8822 HasErrors = true;
8823 continue;
8824 }
8825 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8826 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8827 ->getMemberDecl();
8828 }
8829 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00008830 Expr *InitExpr = *CurInit;
8831
8832 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00008833 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008834 Expr *CapturedRef;
8835 if (LinKind == OMPC_LINEAR_uval)
8836 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8837 else
8838 CapturedRef =
8839 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8840 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8841 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008842
8843 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008844 ExprResult Update;
8845 if (!Info.first) {
8846 Update =
8847 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8848 InitExpr, IV, Step, /* Subtract */ false);
8849 } else
8850 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008851 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8852 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008853
8854 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008855 ExprResult Final;
8856 if (!Info.first) {
8857 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8858 InitExpr, NumIterations, Step,
8859 /* Subtract */ false);
8860 } else
8861 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008862 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8863 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008864
Alexander Musman3276a272015-03-21 10:12:56 +00008865 if (!Update.isUsable() || !Final.isUsable()) {
8866 Updates.push_back(nullptr);
8867 Finals.push_back(nullptr);
8868 HasErrors = true;
8869 } else {
8870 Updates.push_back(Update.get());
8871 Finals.push_back(Final.get());
8872 }
Richard Trieucc3949d2016-02-18 22:34:54 +00008873 ++CurInit;
8874 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00008875 }
8876 Clause.setUpdates(Updates);
8877 Clause.setFinals(Finals);
8878 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00008879}
8880
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008881OMPClause *Sema::ActOnOpenMPAlignedClause(
8882 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8883 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8884
8885 SmallVector<Expr *, 8> Vars;
8886 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00008887 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8888 SourceLocation ELoc;
8889 SourceRange ERange;
8890 Expr *SimpleRefExpr = RefExpr;
8891 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8892 /*AllowArraySection=*/false);
8893 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008894 // It will be analyzed later.
8895 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008896 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00008897 ValueDecl *D = Res.first;
8898 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008899 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008900
Alexey Bataev1efd1662016-03-29 10:59:56 +00008901 QualType QType = D->getType();
8902 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008903
8904 // OpenMP [2.8.1, simd construct, Restrictions]
8905 // The type of list items appearing in the aligned clause must be
8906 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008907 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008908 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00008909 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008910 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008911 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008912 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00008913 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008914 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00008915 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008916 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008917 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008918 continue;
8919 }
8920
8921 // OpenMP [2.8.1, simd construct, Restrictions]
8922 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00008923 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00008924 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008925 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8926 << getOpenMPClauseName(OMPC_aligned);
8927 continue;
8928 }
8929
Alexey Bataev1efd1662016-03-29 10:59:56 +00008930 DeclRefExpr *Ref = nullptr;
8931 if (!VD && IsOpenMPCapturedDecl(D))
8932 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8933 Vars.push_back(DefaultFunctionArrayConversion(
8934 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
8935 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008936 }
8937
8938 // OpenMP [2.8.1, simd construct, Description]
8939 // The parameter of the aligned clause, alignment, must be a constant
8940 // positive integer expression.
8941 // If no optional parameter is specified, implementation-defined default
8942 // alignments for SIMD instructions on the target platforms are assumed.
8943 if (Alignment != nullptr) {
8944 ExprResult AlignResult =
8945 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8946 if (AlignResult.isInvalid())
8947 return nullptr;
8948 Alignment = AlignResult.get();
8949 }
8950 if (Vars.empty())
8951 return nullptr;
8952
8953 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8954 EndLoc, Vars, Alignment);
8955}
8956
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008957OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8958 SourceLocation StartLoc,
8959 SourceLocation LParenLoc,
8960 SourceLocation EndLoc) {
8961 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008962 SmallVector<Expr *, 8> SrcExprs;
8963 SmallVector<Expr *, 8> DstExprs;
8964 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00008965 for (auto &RefExpr : VarList) {
8966 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
8967 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008968 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008969 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008970 SrcExprs.push_back(nullptr);
8971 DstExprs.push_back(nullptr);
8972 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008973 continue;
8974 }
8975
Alexey Bataeved09d242014-05-28 05:53:51 +00008976 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008977 // OpenMP [2.1, C/C++]
8978 // A list item is a variable name.
8979 // OpenMP [2.14.4.1, Restrictions, p.1]
8980 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00008981 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008982 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008983 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8984 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008985 continue;
8986 }
8987
8988 Decl *D = DE->getDecl();
8989 VarDecl *VD = cast<VarDecl>(D);
8990
8991 QualType Type = VD->getType();
8992 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8993 // It will be analyzed later.
8994 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008995 SrcExprs.push_back(nullptr);
8996 DstExprs.push_back(nullptr);
8997 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008998 continue;
8999 }
9000
9001 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9002 // A list item that appears in a copyin clause must be threadprivate.
9003 if (!DSAStack->isThreadPrivate(VD)) {
9004 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009005 << getOpenMPClauseName(OMPC_copyin)
9006 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009007 continue;
9008 }
9009
9010 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9011 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009012 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009013 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009014 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009015 auto *SrcVD =
9016 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9017 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009018 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009019 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9020 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009021 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9022 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009023 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009024 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009025 // For arrays generate assignment operation for single element and replace
9026 // it by the original array element in CodeGen.
9027 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9028 PseudoDstExpr, PseudoSrcExpr);
9029 if (AssignmentOp.isInvalid())
9030 continue;
9031 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9032 /*DiscardedValue=*/true);
9033 if (AssignmentOp.isInvalid())
9034 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009035
9036 DSAStack->addDSA(VD, DE, OMPC_copyin);
9037 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009038 SrcExprs.push_back(PseudoSrcExpr);
9039 DstExprs.push_back(PseudoDstExpr);
9040 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009041 }
9042
Alexey Bataeved09d242014-05-28 05:53:51 +00009043 if (Vars.empty())
9044 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009045
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009046 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9047 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009048}
9049
Alexey Bataevbae9a792014-06-27 10:37:06 +00009050OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9051 SourceLocation StartLoc,
9052 SourceLocation LParenLoc,
9053 SourceLocation EndLoc) {
9054 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009055 SmallVector<Expr *, 8> SrcExprs;
9056 SmallVector<Expr *, 8> DstExprs;
9057 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009058 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009059 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9060 SourceLocation ELoc;
9061 SourceRange ERange;
9062 Expr *SimpleRefExpr = RefExpr;
9063 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9064 /*AllowArraySection=*/false);
9065 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009066 // It will be analyzed later.
9067 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009068 SrcExprs.push_back(nullptr);
9069 DstExprs.push_back(nullptr);
9070 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009071 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009072 ValueDecl *D = Res.first;
9073 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009074 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009075
Alexey Bataeve122da12016-03-17 10:50:17 +00009076 QualType Type = D->getType();
9077 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009078
9079 // OpenMP [2.14.4.2, Restrictions, p.2]
9080 // A list item that appears in a copyprivate clause may not appear in a
9081 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009082 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9083 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009084 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9085 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009086 Diag(ELoc, diag::err_omp_wrong_dsa)
9087 << getOpenMPClauseName(DVar.CKind)
9088 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009089 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009090 continue;
9091 }
9092
9093 // OpenMP [2.11.4.2, Restrictions, p.1]
9094 // All list items that appear in a copyprivate clause must be either
9095 // threadprivate or private in the enclosing context.
9096 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009097 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009098 if (DVar.CKind == OMPC_shared) {
9099 Diag(ELoc, diag::err_omp_required_access)
9100 << getOpenMPClauseName(OMPC_copyprivate)
9101 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009102 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009103 continue;
9104 }
9105 }
9106 }
9107
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009108 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009109 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009110 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009111 << getOpenMPClauseName(OMPC_copyprivate) << Type
9112 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009113 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009114 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009115 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009116 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009117 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009118 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009119 continue;
9120 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009121
Alexey Bataevbae9a792014-06-27 10:37:06 +00009122 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9123 // A variable of class type (or array thereof) that appears in a
9124 // copyin clause requires an accessible, unambiguous copy assignment
9125 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009126 Type = Context.getBaseElementType(Type.getNonReferenceType())
9127 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009128 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009129 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9130 D->hasAttrs() ? &D->getAttrs() : nullptr);
9131 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009132 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009133 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9134 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009135 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009136 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009137 PseudoDstExpr, PseudoSrcExpr);
9138 if (AssignmentOp.isInvalid())
9139 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009140 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009141 /*DiscardedValue=*/true);
9142 if (AssignmentOp.isInvalid())
9143 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009144
9145 // No need to mark vars as copyprivate, they are already threadprivate or
9146 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009147 assert(VD || IsOpenMPCapturedDecl(D));
9148 Vars.push_back(
9149 VD ? RefExpr->IgnoreParens()
9150 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009151 SrcExprs.push_back(PseudoSrcExpr);
9152 DstExprs.push_back(PseudoDstExpr);
9153 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009154 }
9155
9156 if (Vars.empty())
9157 return nullptr;
9158
Alexey Bataeva63048e2015-03-23 06:18:07 +00009159 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9160 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009161}
9162
Alexey Bataev6125da92014-07-21 11:26:11 +00009163OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9164 SourceLocation StartLoc,
9165 SourceLocation LParenLoc,
9166 SourceLocation EndLoc) {
9167 if (VarList.empty())
9168 return nullptr;
9169
9170 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9171}
Alexey Bataevdea47612014-07-23 07:46:59 +00009172
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009173OMPClause *
9174Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9175 SourceLocation DepLoc, SourceLocation ColonLoc,
9176 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9177 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009178 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009179 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009180 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009181 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009182 return nullptr;
9183 }
9184 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009185 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9186 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009187 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009188 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009189 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9190 /*Last=*/OMPC_DEPEND_unknown, Except)
9191 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009192 return nullptr;
9193 }
9194 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009195 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009196 llvm::APSInt DepCounter(/*BitWidth=*/32);
9197 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9198 if (DepKind == OMPC_DEPEND_sink) {
9199 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9200 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9201 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009202 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009203 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009204 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9205 DSAStack->getParentOrderedRegionParam()) {
9206 for (auto &RefExpr : VarList) {
9207 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009208 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009209 // It will be analyzed later.
9210 Vars.push_back(RefExpr);
9211 continue;
9212 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009213
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009214 SourceLocation ELoc = RefExpr->getExprLoc();
9215 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9216 if (DepKind == OMPC_DEPEND_sink) {
9217 if (DepCounter >= TotalDepCount) {
9218 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9219 continue;
9220 }
9221 ++DepCounter;
9222 // OpenMP [2.13.9, Summary]
9223 // depend(dependence-type : vec), where dependence-type is:
9224 // 'sink' and where vec is the iteration vector, which has the form:
9225 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9226 // where n is the value specified by the ordered clause in the loop
9227 // directive, xi denotes the loop iteration variable of the i-th nested
9228 // loop associated with the loop directive, and di is a constant
9229 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009230 if (CurContext->isDependentContext()) {
9231 // It will be analyzed later.
9232 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009233 continue;
9234 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009235 SimpleExpr = SimpleExpr->IgnoreImplicit();
9236 OverloadedOperatorKind OOK = OO_None;
9237 SourceLocation OOLoc;
9238 Expr *LHS = SimpleExpr;
9239 Expr *RHS = nullptr;
9240 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9241 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9242 OOLoc = BO->getOperatorLoc();
9243 LHS = BO->getLHS()->IgnoreParenImpCasts();
9244 RHS = BO->getRHS()->IgnoreParenImpCasts();
9245 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9246 OOK = OCE->getOperator();
9247 OOLoc = OCE->getOperatorLoc();
9248 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9249 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9250 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9251 OOK = MCE->getMethodDecl()
9252 ->getNameInfo()
9253 .getName()
9254 .getCXXOverloadedOperator();
9255 OOLoc = MCE->getCallee()->getExprLoc();
9256 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9257 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9258 }
9259 SourceLocation ELoc;
9260 SourceRange ERange;
9261 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9262 /*AllowArraySection=*/false);
9263 if (Res.second) {
9264 // It will be analyzed later.
9265 Vars.push_back(RefExpr);
9266 }
9267 ValueDecl *D = Res.first;
9268 if (!D)
9269 continue;
9270
9271 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9272 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9273 continue;
9274 }
9275 if (RHS) {
9276 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9277 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9278 if (RHSRes.isInvalid())
9279 continue;
9280 }
9281 if (!CurContext->isDependentContext() &&
9282 DSAStack->getParentOrderedRegionParam() &&
9283 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9284 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9285 << DSAStack->getParentLoopControlVariable(
9286 DepCounter.getZExtValue());
9287 continue;
9288 }
9289 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009290 } else {
9291 // OpenMP [2.11.1.1, Restrictions, p.3]
9292 // A variable that is part of another variable (such as a field of a
9293 // structure) but is not an array element or an array section cannot
9294 // appear in a depend clause.
9295 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9296 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9297 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9298 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9299 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009300 (ASE &&
9301 !ASE->getBase()
9302 ->getType()
9303 .getNonReferenceType()
9304 ->isPointerType() &&
9305 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009306 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9307 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009308 continue;
9309 }
9310 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009311 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9312 }
9313
9314 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9315 TotalDepCount > VarList.size() &&
9316 DSAStack->getParentOrderedRegionParam()) {
9317 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9318 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9319 }
9320 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9321 Vars.empty())
9322 return nullptr;
9323 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009324 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9325 DepKind, DepLoc, ColonLoc, Vars);
9326 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9327 DSAStack->addDoacrossDependClause(C, OpsOffs);
9328 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009329}
Michael Wonge710d542015-08-07 16:16:36 +00009330
9331OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9332 SourceLocation LParenLoc,
9333 SourceLocation EndLoc) {
9334 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009335
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009336 // OpenMP [2.9.1, Restrictions]
9337 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009338 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9339 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009340 return nullptr;
9341
Michael Wonge710d542015-08-07 16:16:36 +00009342 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9343}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009344
9345static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9346 DSAStackTy *Stack, CXXRecordDecl *RD) {
9347 if (!RD || RD->isInvalidDecl())
9348 return true;
9349
9350 auto QTy = SemaRef.Context.getRecordType(RD);
9351 if (RD->isDynamicClass()) {
9352 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9353 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9354 return false;
9355 }
9356 auto *DC = RD;
9357 bool IsCorrect = true;
9358 for (auto *I : DC->decls()) {
9359 if (I) {
9360 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9361 if (MD->isStatic()) {
9362 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9363 SemaRef.Diag(MD->getLocation(),
9364 diag::note_omp_static_member_in_target);
9365 IsCorrect = false;
9366 }
9367 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9368 if (VD->isStaticDataMember()) {
9369 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9370 SemaRef.Diag(VD->getLocation(),
9371 diag::note_omp_static_member_in_target);
9372 IsCorrect = false;
9373 }
9374 }
9375 }
9376 }
9377
9378 for (auto &I : RD->bases()) {
9379 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9380 I.getType()->getAsCXXRecordDecl()))
9381 IsCorrect = false;
9382 }
9383 return IsCorrect;
9384}
9385
9386static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9387 DSAStackTy *Stack, QualType QTy) {
9388 NamedDecl *ND;
9389 if (QTy->isIncompleteType(&ND)) {
9390 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9391 return false;
9392 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009393 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009394 return false;
9395 }
9396 return true;
9397}
9398
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009399/// \brief Return true if it can be proven that the provided array expression
9400/// (array section or array subscript) does NOT specify the whole size of the
9401/// array whose base type is \a BaseQTy.
9402static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9403 const Expr *E,
9404 QualType BaseQTy) {
9405 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9406
9407 // If this is an array subscript, it refers to the whole size if the size of
9408 // the dimension is constant and equals 1. Also, an array section assumes the
9409 // format of an array subscript if no colon is used.
9410 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9411 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9412 return ATy->getSize().getSExtValue() != 1;
9413 // Size can't be evaluated statically.
9414 return false;
9415 }
9416
9417 assert(OASE && "Expecting array section if not an array subscript.");
9418 auto *LowerBound = OASE->getLowerBound();
9419 auto *Length = OASE->getLength();
9420
9421 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009422 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009423 if (LowerBound) {
9424 llvm::APSInt ConstLowerBound;
9425 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9426 return false; // Can't get the integer value as a constant.
9427 if (ConstLowerBound.getSExtValue())
9428 return true;
9429 }
9430
9431 // If we don't have a length we covering the whole dimension.
9432 if (!Length)
9433 return false;
9434
9435 // If the base is a pointer, we don't have a way to get the size of the
9436 // pointee.
9437 if (BaseQTy->isPointerType())
9438 return false;
9439
9440 // We can only check if the length is the same as the size of the dimension
9441 // if we have a constant array.
9442 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9443 if (!CATy)
9444 return false;
9445
9446 llvm::APSInt ConstLength;
9447 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9448 return false; // Can't get the integer value as a constant.
9449
9450 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9451}
9452
9453// Return true if it can be proven that the provided array expression (array
9454// section or array subscript) does NOT specify a single element of the array
9455// whose base type is \a BaseQTy.
9456static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009457 const Expr *E,
9458 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009459 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9460
9461 // An array subscript always refer to a single element. Also, an array section
9462 // assumes the format of an array subscript if no colon is used.
9463 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9464 return false;
9465
9466 assert(OASE && "Expecting array section if not an array subscript.");
9467 auto *Length = OASE->getLength();
9468
9469 // If we don't have a length we have to check if the array has unitary size
9470 // for this dimension. Also, we should always expect a length if the base type
9471 // is pointer.
9472 if (!Length) {
9473 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9474 return ATy->getSize().getSExtValue() != 1;
9475 // We cannot assume anything.
9476 return false;
9477 }
9478
9479 // Check if the length evaluates to 1.
9480 llvm::APSInt ConstLength;
9481 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9482 return false; // Can't get the integer value as a constant.
9483
9484 return ConstLength.getSExtValue() != 1;
9485}
9486
Samuel Antao661c0902016-05-26 17:39:58 +00009487// Return the expression of the base of the mappable expression or null if it
9488// cannot be determined and do all the necessary checks to see if the expression
9489// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009490// components of the expression.
9491static Expr *CheckMapClauseExpressionBase(
9492 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009493 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9494 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009495 SourceLocation ELoc = E->getExprLoc();
9496 SourceRange ERange = E->getSourceRange();
9497
9498 // The base of elements of list in a map clause have to be either:
9499 // - a reference to variable or field.
9500 // - a member expression.
9501 // - an array expression.
9502 //
9503 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9504 // reference to 'r'.
9505 //
9506 // If we have:
9507 //
9508 // struct SS {
9509 // Bla S;
9510 // foo() {
9511 // #pragma omp target map (S.Arr[:12]);
9512 // }
9513 // }
9514 //
9515 // We want to retrieve the member expression 'this->S';
9516
9517 Expr *RelevantExpr = nullptr;
9518
Samuel Antao5de996e2016-01-22 20:21:36 +00009519 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9520 // If a list item is an array section, it must specify contiguous storage.
9521 //
9522 // For this restriction it is sufficient that we make sure only references
9523 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009524 // exist except in the rightmost expression (unless they cover the whole
9525 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009526 //
9527 // r.ArrS[3:5].Arr[6:7]
9528 //
9529 // r.ArrS[3:5].x
9530 //
9531 // but these would be valid:
9532 // r.ArrS[3].Arr[6:7]
9533 //
9534 // r.ArrS[3].x
9535
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009536 bool AllowUnitySizeArraySection = true;
9537 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009538
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009539 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009540 E = E->IgnoreParenImpCasts();
9541
9542 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9543 if (!isa<VarDecl>(CurE->getDecl()))
9544 break;
9545
9546 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009547
9548 // If we got a reference to a declaration, we should not expect any array
9549 // section before that.
9550 AllowUnitySizeArraySection = false;
9551 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009552
9553 // Record the component.
9554 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9555 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009556 continue;
9557 }
9558
9559 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9560 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9561
9562 if (isa<CXXThisExpr>(BaseE))
9563 // We found a base expression: this->Val.
9564 RelevantExpr = CurE;
9565 else
9566 E = BaseE;
9567
9568 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9569 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9570 << CurE->getSourceRange();
9571 break;
9572 }
9573
9574 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9575
9576 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9577 // A bit-field cannot appear in a map clause.
9578 //
9579 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009580 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9581 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009582 break;
9583 }
9584
9585 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9586 // If the type of a list item is a reference to a type T then the type
9587 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009588 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009589
9590 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9591 // A list item cannot be a variable that is a member of a structure with
9592 // a union type.
9593 //
9594 if (auto *RT = CurType->getAs<RecordType>())
9595 if (RT->isUnionType()) {
9596 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9597 << CurE->getSourceRange();
9598 break;
9599 }
9600
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009601 // If we got a member expression, we should not expect any array section
9602 // before that:
9603 //
9604 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9605 // If a list item is an element of a structure, only the rightmost symbol
9606 // of the variable reference can be an array section.
9607 //
9608 AllowUnitySizeArraySection = false;
9609 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009610
9611 // Record the component.
9612 CurComponents.push_back(
9613 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009614 continue;
9615 }
9616
9617 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9618 E = CurE->getBase()->IgnoreParenImpCasts();
9619
9620 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9621 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9622 << 0 << CurE->getSourceRange();
9623 break;
9624 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009625
9626 // If we got an array subscript that express the whole dimension we
9627 // can have any array expressions before. If it only expressing part of
9628 // the dimension, we can only have unitary-size array expressions.
9629 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9630 E->getType()))
9631 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009632
9633 // Record the component - we don't have any declaration associated.
9634 CurComponents.push_back(
9635 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009636 continue;
9637 }
9638
9639 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009640 E = CurE->getBase()->IgnoreParenImpCasts();
9641
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009642 auto CurType =
9643 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9644
Samuel Antao5de996e2016-01-22 20:21:36 +00009645 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9646 // If the type of a list item is a reference to a type T then the type
9647 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009648 if (CurType->isReferenceType())
9649 CurType = CurType->getPointeeType();
9650
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009651 bool IsPointer = CurType->isAnyPointerType();
9652
9653 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009654 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9655 << 0 << CurE->getSourceRange();
9656 break;
9657 }
9658
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009659 bool NotWhole =
9660 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9661 bool NotUnity =
9662 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9663
Samuel Antaodab51bb2016-07-18 23:22:11 +00009664 if (AllowWholeSizeArraySection) {
9665 // Any array section is currently allowed. Allowing a whole size array
9666 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009667 //
9668 // If this array section refers to the whole dimension we can still
9669 // accept other array sections before this one, except if the base is a
9670 // pointer. Otherwise, only unitary sections are accepted.
9671 if (NotWhole || IsPointer)
9672 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009673 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009674 // A unity or whole array section is not allowed and that is not
9675 // compatible with the properties of the current array section.
9676 SemaRef.Diag(
9677 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9678 << CurE->getSourceRange();
9679 break;
9680 }
Samuel Antao90927002016-04-26 14:54:23 +00009681
9682 // Record the component - we don't have any declaration associated.
9683 CurComponents.push_back(
9684 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009685 continue;
9686 }
9687
9688 // If nothing else worked, this is not a valid map clause expression.
9689 SemaRef.Diag(ELoc,
9690 diag::err_omp_expected_named_var_member_or_array_expression)
9691 << ERange;
9692 break;
9693 }
9694
9695 return RelevantExpr;
9696}
9697
9698// Return true if expression E associated with value VD has conflicts with other
9699// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009700static bool CheckMapConflicts(
9701 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9702 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009703 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9704 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009705 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009706 SourceLocation ELoc = E->getExprLoc();
9707 SourceRange ERange = E->getSourceRange();
9708
9709 // In order to easily check the conflicts we need to match each component of
9710 // the expression under test with the components of the expressions that are
9711 // already in the stack.
9712
Samuel Antao5de996e2016-01-22 20:21:36 +00009713 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009714 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009715 "Map clause expression with unexpected base!");
9716
9717 // Variables to help detecting enclosing problems in data environment nests.
9718 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009719 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009720
Samuel Antao90927002016-04-26 14:54:23 +00009721 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9722 VD, CurrentRegionOnly,
9723 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009724 StackComponents,
9725 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009726
Samuel Antao5de996e2016-01-22 20:21:36 +00009727 assert(!StackComponents.empty() &&
9728 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009729 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009730 "Map clause expression with unexpected base!");
9731
Samuel Antao90927002016-04-26 14:54:23 +00009732 // The whole expression in the stack.
9733 auto *RE = StackComponents.front().getAssociatedExpression();
9734
Samuel Antao5de996e2016-01-22 20:21:36 +00009735 // Expressions must start from the same base. Here we detect at which
9736 // point both expressions diverge from each other and see if we can
9737 // detect if the memory referred to both expressions is contiguous and
9738 // do not overlap.
9739 auto CI = CurComponents.rbegin();
9740 auto CE = CurComponents.rend();
9741 auto SI = StackComponents.rbegin();
9742 auto SE = StackComponents.rend();
9743 for (; CI != CE && SI != SE; ++CI, ++SI) {
9744
9745 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9746 // At most one list item can be an array item derived from a given
9747 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009748 if (CurrentRegionOnly &&
9749 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9750 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9751 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9752 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9753 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009754 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009755 << CI->getAssociatedExpression()->getSourceRange();
9756 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9757 diag::note_used_here)
9758 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009759 return true;
9760 }
9761
9762 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009763 if (CI->getAssociatedExpression()->getStmtClass() !=
9764 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009765 break;
9766
9767 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009768 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009769 break;
9770 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009771 // Check if the extra components of the expressions in the enclosing
9772 // data environment are redundant for the current base declaration.
9773 // If they are, the maps completely overlap, which is legal.
9774 for (; SI != SE; ++SI) {
9775 QualType Type;
9776 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009777 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009778 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009779 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9780 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009781 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9782 Type =
9783 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9784 }
9785 if (Type.isNull() || Type->isAnyPointerType() ||
9786 CheckArrayExpressionDoesNotReferToWholeSize(
9787 SemaRef, SI->getAssociatedExpression(), Type))
9788 break;
9789 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009790
9791 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9792 // List items of map clauses in the same construct must not share
9793 // original storage.
9794 //
9795 // If the expressions are exactly the same or one is a subset of the
9796 // other, it means they are sharing storage.
9797 if (CI == CE && SI == SE) {
9798 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009799 if (CKind == OMPC_map)
9800 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9801 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009802 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009803 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9804 << ERange;
9805 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009806 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9807 << RE->getSourceRange();
9808 return true;
9809 } else {
9810 // If we find the same expression in the enclosing data environment,
9811 // that is legal.
9812 IsEnclosedByDataEnvironmentExpr = true;
9813 return false;
9814 }
9815 }
9816
Samuel Antao90927002016-04-26 14:54:23 +00009817 QualType DerivedType =
9818 std::prev(CI)->getAssociatedDeclaration()->getType();
9819 SourceLocation DerivedLoc =
9820 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +00009821
9822 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9823 // If the type of a list item is a reference to a type T then the type
9824 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009825 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009826
9827 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9828 // A variable for which the type is pointer and an array section
9829 // derived from that variable must not appear as list items of map
9830 // clauses of the same construct.
9831 //
9832 // Also, cover one of the cases in:
9833 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9834 // If any part of the original storage of a list item has corresponding
9835 // storage in the device data environment, all of the original storage
9836 // must have corresponding storage in the device data environment.
9837 //
9838 if (DerivedType->isAnyPointerType()) {
9839 if (CI == CE || SI == SE) {
9840 SemaRef.Diag(
9841 DerivedLoc,
9842 diag::err_omp_pointer_mapped_along_with_derived_section)
9843 << DerivedLoc;
9844 } else {
9845 assert(CI != CE && SI != SE);
9846 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9847 << DerivedLoc;
9848 }
9849 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9850 << RE->getSourceRange();
9851 return true;
9852 }
9853
9854 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9855 // List items of map clauses in the same construct must not share
9856 // original storage.
9857 //
9858 // An expression is a subset of the other.
9859 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +00009860 if (CKind == OMPC_map)
9861 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9862 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009863 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009864 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9865 << ERange;
9866 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009867 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9868 << RE->getSourceRange();
9869 return true;
9870 }
9871
9872 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +00009873 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +00009874 if (!CurrentRegionOnly && SI != SE)
9875 EnclosingExpr = RE;
9876
9877 // The current expression is a subset of the expression in the data
9878 // environment.
9879 IsEnclosedByDataEnvironmentExpr |=
9880 (!CurrentRegionOnly && CI != CE && SI == SE);
9881
9882 return false;
9883 });
9884
9885 if (CurrentRegionOnly)
9886 return FoundError;
9887
9888 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9889 // If any part of the original storage of a list item has corresponding
9890 // storage in the device data environment, all of the original storage must
9891 // have corresponding storage in the device data environment.
9892 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9893 // If a list item is an element of a structure, and a different element of
9894 // the structure has a corresponding list item in the device data environment
9895 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +00009896 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +00009897 // data environment prior to the task encountering the construct.
9898 //
9899 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9900 SemaRef.Diag(ELoc,
9901 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9902 << ERange;
9903 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9904 << EnclosingExpr->getSourceRange();
9905 return true;
9906 }
9907
9908 return FoundError;
9909}
9910
Samuel Antao661c0902016-05-26 17:39:58 +00009911namespace {
9912// Utility struct that gathers all the related lists associated with a mappable
9913// expression.
9914struct MappableVarListInfo final {
9915 // The list of expressions.
9916 ArrayRef<Expr *> VarList;
9917 // The list of processed expressions.
9918 SmallVector<Expr *, 16> ProcessedVarList;
9919 // The mappble components for each expression.
9920 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
9921 // The base declaration of the variable.
9922 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
9923
9924 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
9925 // We have a list of components and base declarations for each entry in the
9926 // variable list.
9927 VarComponents.reserve(VarList.size());
9928 VarBaseDeclarations.reserve(VarList.size());
9929 }
9930};
9931}
9932
9933// Check the validity of the provided variable list for the provided clause kind
9934// \a CKind. In the check process the valid expressions, and mappable expression
9935// components and variables are extracted and used to fill \a Vars,
9936// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
9937// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
9938static void
9939checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
9940 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
9941 SourceLocation StartLoc,
9942 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
9943 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009944 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
9945 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +00009946 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009947
Samuel Antao90927002016-04-26 14:54:23 +00009948 // Keep track of the mappable components and base declarations in this clause.
9949 // Each entry in the list is going to have a list of components associated. We
9950 // record each set of the components so that we can build the clause later on.
9951 // In the end we should have the same amount of declarations and component
9952 // lists.
Samuel Antao90927002016-04-26 14:54:23 +00009953
Samuel Antao661c0902016-05-26 17:39:58 +00009954 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009955 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009956 SourceLocation ELoc = RE->getExprLoc();
9957
Kelvin Li0bff7af2015-11-23 05:32:03 +00009958 auto *VE = RE->IgnoreParenLValueCasts();
9959
9960 if (VE->isValueDependent() || VE->isTypeDependent() ||
9961 VE->isInstantiationDependent() ||
9962 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009963 // We can only analyze this information once the missing information is
9964 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +00009965 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009966 continue;
9967 }
9968
9969 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009970
Samuel Antao5de996e2016-01-22 20:21:36 +00009971 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009972 SemaRef.Diag(ELoc,
9973 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +00009974 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009975 continue;
9976 }
9977
Samuel Antao90927002016-04-26 14:54:23 +00009978 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
9979 ValueDecl *CurDeclaration = nullptr;
9980
9981 // Obtain the array or member expression bases if required. Also, fill the
9982 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +00009983 auto *BE =
9984 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009985 if (!BE)
9986 continue;
9987
Samuel Antao90927002016-04-26 14:54:23 +00009988 assert(!CurComponents.empty() &&
9989 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009990
Samuel Antao90927002016-04-26 14:54:23 +00009991 // For the following checks, we rely on the base declaration which is
9992 // expected to be associated with the last component. The declaration is
9993 // expected to be a variable or a field (if 'this' is being mapped).
9994 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
9995 assert(CurDeclaration && "Null decl on map clause.");
9996 assert(
9997 CurDeclaration->isCanonicalDecl() &&
9998 "Expecting components to have associated only canonical declarations.");
9999
10000 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10001 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010002
10003 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010004 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010005
10006 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010007 // threadprivate variables cannot appear in a map clause.
10008 // OpenMP 4.5 [2.10.5, target update Construct]
10009 // threadprivate variables cannot appear in a from clause.
10010 if (VD && DSAS->isThreadPrivate(VD)) {
10011 auto DVar = DSAS->getTopDSA(VD, false);
10012 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10013 << getOpenMPClauseName(CKind);
10014 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010015 continue;
10016 }
10017
Samuel Antao5de996e2016-01-22 20:21:36 +000010018 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10019 // A list item cannot appear in both a map clause and a data-sharing
10020 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010021
Samuel Antao5de996e2016-01-22 20:21:36 +000010022 // Check conflicts with other map clause expressions. We check the conflicts
10023 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010024 // environment, because the restrictions are different. We only have to
10025 // check conflicts across regions for the map clauses.
10026 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10027 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010028 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010029 if (CKind == OMPC_map &&
10030 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10031 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010032 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010033
Samuel Antao661c0902016-05-26 17:39:58 +000010034 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010035 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10036 // If the type of a list item is a reference to a type T then the type will
10037 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010038 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010039
Samuel Antao661c0902016-05-26 17:39:58 +000010040 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10041 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010042 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010043 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010044 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10045 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010046 continue;
10047
Samuel Antao661c0902016-05-26 17:39:58 +000010048 if (CKind == OMPC_map) {
10049 // target enter data
10050 // OpenMP [2.10.2, Restrictions, p. 99]
10051 // A map-type must be specified in all map clauses and must be either
10052 // to or alloc.
10053 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10054 if (DKind == OMPD_target_enter_data &&
10055 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10056 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10057 << (IsMapTypeImplicit ? 1 : 0)
10058 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10059 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010060 continue;
10061 }
Samuel Antao661c0902016-05-26 17:39:58 +000010062
10063 // target exit_data
10064 // OpenMP [2.10.3, Restrictions, p. 102]
10065 // A map-type must be specified in all map clauses and must be either
10066 // from, release, or delete.
10067 if (DKind == OMPD_target_exit_data &&
10068 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10069 MapType == OMPC_MAP_delete)) {
10070 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10071 << (IsMapTypeImplicit ? 1 : 0)
10072 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10073 << getOpenMPDirectiveName(DKind);
10074 continue;
10075 }
10076
10077 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10078 // A list item cannot appear in both a map clause and a data-sharing
10079 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +000010080 if ((DKind == OMPD_target || DKind == OMPD_target_teams) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010081 auto DVar = DSAS->getTopDSA(VD, false);
10082 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010083 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010084 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010085 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010086 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10087 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10088 continue;
10089 }
10090 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010091 }
10092
Samuel Antao90927002016-04-26 14:54:23 +000010093 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010094 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010095
10096 // Store the components in the stack so that they can be used to check
10097 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010098 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10099 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010100
10101 // Save the components and declaration to create the clause. For purposes of
10102 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010103 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010104 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10105 MVLI.VarComponents.back().append(CurComponents.begin(),
10106 CurComponents.end());
10107 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10108 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010109 }
Samuel Antao661c0902016-05-26 17:39:58 +000010110}
10111
10112OMPClause *
10113Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10114 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10115 SourceLocation MapLoc, SourceLocation ColonLoc,
10116 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10117 SourceLocation LParenLoc, SourceLocation EndLoc) {
10118 MappableVarListInfo MVLI(VarList);
10119 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10120 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010121
Samuel Antao5de996e2016-01-22 20:21:36 +000010122 // We need to produce a map clause even if we don't have variables so that
10123 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010124 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10125 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10126 MVLI.VarComponents, MapTypeModifier, MapType,
10127 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010128}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010129
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010130QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10131 TypeResult ParsedType) {
10132 assert(ParsedType.isUsable());
10133
10134 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10135 if (ReductionType.isNull())
10136 return QualType();
10137
10138 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10139 // A type name in a declare reduction directive cannot be a function type, an
10140 // array type, a reference type, or a type qualified with const, volatile or
10141 // restrict.
10142 if (ReductionType.hasQualifiers()) {
10143 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10144 return QualType();
10145 }
10146
10147 if (ReductionType->isFunctionType()) {
10148 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10149 return QualType();
10150 }
10151 if (ReductionType->isReferenceType()) {
10152 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10153 return QualType();
10154 }
10155 if (ReductionType->isArrayType()) {
10156 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10157 return QualType();
10158 }
10159 return ReductionType;
10160}
10161
10162Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10163 Scope *S, DeclContext *DC, DeclarationName Name,
10164 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10165 AccessSpecifier AS, Decl *PrevDeclInScope) {
10166 SmallVector<Decl *, 8> Decls;
10167 Decls.reserve(ReductionTypes.size());
10168
10169 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10170 ForRedeclaration);
10171 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10172 // A reduction-identifier may not be re-declared in the current scope for the
10173 // same type or for a type that is compatible according to the base language
10174 // rules.
10175 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10176 OMPDeclareReductionDecl *PrevDRD = nullptr;
10177 bool InCompoundScope = true;
10178 if (S != nullptr) {
10179 // Find previous declaration with the same name not referenced in other
10180 // declarations.
10181 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10182 InCompoundScope =
10183 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10184 LookupName(Lookup, S);
10185 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10186 /*AllowInlineNamespace=*/false);
10187 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10188 auto Filter = Lookup.makeFilter();
10189 while (Filter.hasNext()) {
10190 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10191 if (InCompoundScope) {
10192 auto I = UsedAsPrevious.find(PrevDecl);
10193 if (I == UsedAsPrevious.end())
10194 UsedAsPrevious[PrevDecl] = false;
10195 if (auto *D = PrevDecl->getPrevDeclInScope())
10196 UsedAsPrevious[D] = true;
10197 }
10198 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10199 PrevDecl->getLocation();
10200 }
10201 Filter.done();
10202 if (InCompoundScope) {
10203 for (auto &PrevData : UsedAsPrevious) {
10204 if (!PrevData.second) {
10205 PrevDRD = PrevData.first;
10206 break;
10207 }
10208 }
10209 }
10210 } else if (PrevDeclInScope != nullptr) {
10211 auto *PrevDRDInScope = PrevDRD =
10212 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10213 do {
10214 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10215 PrevDRDInScope->getLocation();
10216 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10217 } while (PrevDRDInScope != nullptr);
10218 }
10219 for (auto &TyData : ReductionTypes) {
10220 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10221 bool Invalid = false;
10222 if (I != PreviousRedeclTypes.end()) {
10223 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10224 << TyData.first;
10225 Diag(I->second, diag::note_previous_definition);
10226 Invalid = true;
10227 }
10228 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10229 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10230 Name, TyData.first, PrevDRD);
10231 DC->addDecl(DRD);
10232 DRD->setAccess(AS);
10233 Decls.push_back(DRD);
10234 if (Invalid)
10235 DRD->setInvalidDecl();
10236 else
10237 PrevDRD = DRD;
10238 }
10239
10240 return DeclGroupPtrTy::make(
10241 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10242}
10243
10244void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10245 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10246
10247 // Enter new function scope.
10248 PushFunctionScope();
10249 getCurFunction()->setHasBranchProtectedScope();
10250 getCurFunction()->setHasOMPDeclareReductionCombiner();
10251
10252 if (S != nullptr)
10253 PushDeclContext(S, DRD);
10254 else
10255 CurContext = DRD;
10256
10257 PushExpressionEvaluationContext(PotentiallyEvaluated);
10258
10259 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010260 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10261 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10262 // uses semantics of argument handles by value, but it should be passed by
10263 // reference. C lang does not support references, so pass all parameters as
10264 // pointers.
10265 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010266 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010267 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010268 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10269 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10270 // uses semantics of argument handles by value, but it should be passed by
10271 // reference. C lang does not support references, so pass all parameters as
10272 // pointers.
10273 // Create 'T omp_out;' variable.
10274 auto *OmpOutParm =
10275 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10276 if (S != nullptr) {
10277 PushOnScopeChains(OmpInParm, S);
10278 PushOnScopeChains(OmpOutParm, S);
10279 } else {
10280 DRD->addDecl(OmpInParm);
10281 DRD->addDecl(OmpOutParm);
10282 }
10283}
10284
10285void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10286 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10287 DiscardCleanupsInEvaluationContext();
10288 PopExpressionEvaluationContext();
10289
10290 PopDeclContext();
10291 PopFunctionScopeInfo();
10292
10293 if (Combiner != nullptr)
10294 DRD->setCombiner(Combiner);
10295 else
10296 DRD->setInvalidDecl();
10297}
10298
10299void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10300 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10301
10302 // Enter new function scope.
10303 PushFunctionScope();
10304 getCurFunction()->setHasBranchProtectedScope();
10305
10306 if (S != nullptr)
10307 PushDeclContext(S, DRD);
10308 else
10309 CurContext = DRD;
10310
10311 PushExpressionEvaluationContext(PotentiallyEvaluated);
10312
10313 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010314 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10315 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10316 // uses semantics of argument handles by value, but it should be passed by
10317 // reference. C lang does not support references, so pass all parameters as
10318 // pointers.
10319 // Create 'T omp_priv;' variable.
10320 auto *OmpPrivParm =
10321 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010322 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10323 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10324 // uses semantics of argument handles by value, but it should be passed by
10325 // reference. C lang does not support references, so pass all parameters as
10326 // pointers.
10327 // Create 'T omp_orig;' variable.
10328 auto *OmpOrigParm =
10329 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010330 if (S != nullptr) {
10331 PushOnScopeChains(OmpPrivParm, S);
10332 PushOnScopeChains(OmpOrigParm, S);
10333 } else {
10334 DRD->addDecl(OmpPrivParm);
10335 DRD->addDecl(OmpOrigParm);
10336 }
10337}
10338
10339void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10340 Expr *Initializer) {
10341 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10342 DiscardCleanupsInEvaluationContext();
10343 PopExpressionEvaluationContext();
10344
10345 PopDeclContext();
10346 PopFunctionScopeInfo();
10347
10348 if (Initializer != nullptr)
10349 DRD->setInitializer(Initializer);
10350 else
10351 DRD->setInvalidDecl();
10352}
10353
10354Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10355 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10356 for (auto *D : DeclReductions.get()) {
10357 if (IsValid) {
10358 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10359 if (S != nullptr)
10360 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10361 } else
10362 D->setInvalidDecl();
10363 }
10364 return DeclReductions;
10365}
10366
David Majnemer9d168222016-08-05 17:44:54 +000010367OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010368 SourceLocation StartLoc,
10369 SourceLocation LParenLoc,
10370 SourceLocation EndLoc) {
10371 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010372
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010373 // OpenMP [teams Constrcut, Restrictions]
10374 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010375 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10376 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010377 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010378
10379 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10380}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010381
10382OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10383 SourceLocation StartLoc,
10384 SourceLocation LParenLoc,
10385 SourceLocation EndLoc) {
10386 Expr *ValExpr = ThreadLimit;
10387
10388 // OpenMP [teams Constrcut, Restrictions]
10389 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010390 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10391 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010392 return nullptr;
10393
David Majnemer9d168222016-08-05 17:44:54 +000010394 return new (Context)
10395 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010396}
Alexey Bataeva0569352015-12-01 10:17:31 +000010397
10398OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10399 SourceLocation StartLoc,
10400 SourceLocation LParenLoc,
10401 SourceLocation EndLoc) {
10402 Expr *ValExpr = Priority;
10403
10404 // OpenMP [2.9.1, task Constrcut]
10405 // The priority-value is a non-negative numerical scalar expression.
10406 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10407 /*StrictlyPositive=*/false))
10408 return nullptr;
10409
10410 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10411}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010412
10413OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10414 SourceLocation StartLoc,
10415 SourceLocation LParenLoc,
10416 SourceLocation EndLoc) {
10417 Expr *ValExpr = Grainsize;
10418
10419 // OpenMP [2.9.2, taskloop Constrcut]
10420 // The parameter of the grainsize clause must be a positive integer
10421 // expression.
10422 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10423 /*StrictlyPositive=*/true))
10424 return nullptr;
10425
10426 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10427}
Alexey Bataev382967a2015-12-08 12:06:20 +000010428
10429OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10430 SourceLocation StartLoc,
10431 SourceLocation LParenLoc,
10432 SourceLocation EndLoc) {
10433 Expr *ValExpr = NumTasks;
10434
10435 // OpenMP [2.9.2, taskloop Constrcut]
10436 // The parameter of the num_tasks clause must be a positive integer
10437 // expression.
10438 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10439 /*StrictlyPositive=*/true))
10440 return nullptr;
10441
10442 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10443}
10444
Alexey Bataev28c75412015-12-15 08:19:24 +000010445OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10446 SourceLocation LParenLoc,
10447 SourceLocation EndLoc) {
10448 // OpenMP [2.13.2, critical construct, Description]
10449 // ... where hint-expression is an integer constant expression that evaluates
10450 // to a valid lock hint.
10451 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10452 if (HintExpr.isInvalid())
10453 return nullptr;
10454 return new (Context)
10455 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10456}
10457
Carlo Bertollib4adf552016-01-15 18:50:31 +000010458OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10459 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10460 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10461 SourceLocation EndLoc) {
10462 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10463 std::string Values;
10464 Values += "'";
10465 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10466 Values += "'";
10467 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10468 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10469 return nullptr;
10470 }
10471 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010472 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010473 if (ChunkSize) {
10474 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10475 !ChunkSize->isInstantiationDependent() &&
10476 !ChunkSize->containsUnexpandedParameterPack()) {
10477 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10478 ExprResult Val =
10479 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10480 if (Val.isInvalid())
10481 return nullptr;
10482
10483 ValExpr = Val.get();
10484
10485 // OpenMP [2.7.1, Restrictions]
10486 // chunk_size must be a loop invariant integer expression with a positive
10487 // value.
10488 llvm::APSInt Result;
10489 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10490 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10491 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10492 << "dist_schedule" << ChunkSize->getSourceRange();
10493 return nullptr;
10494 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010495 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10496 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010497 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10498 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10499 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010500 }
10501 }
10502 }
10503
10504 return new (Context)
10505 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010506 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010507}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010508
10509OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10510 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10511 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10512 SourceLocation KindLoc, SourceLocation EndLoc) {
10513 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010514 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010515 std::string Value;
10516 SourceLocation Loc;
10517 Value += "'";
10518 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10519 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010520 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010521 Loc = MLoc;
10522 } else {
10523 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010524 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010525 Loc = KindLoc;
10526 }
10527 Value += "'";
10528 Diag(Loc, diag::err_omp_unexpected_clause_value)
10529 << Value << getOpenMPClauseName(OMPC_defaultmap);
10530 return nullptr;
10531 }
10532
10533 return new (Context)
10534 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10535}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010536
10537bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10538 DeclContext *CurLexicalContext = getCurLexicalContext();
10539 if (!CurLexicalContext->isFileContext() &&
10540 !CurLexicalContext->isExternCContext() &&
10541 !CurLexicalContext->isExternCXXContext()) {
10542 Diag(Loc, diag::err_omp_region_not_file_context);
10543 return false;
10544 }
10545 if (IsInOpenMPDeclareTargetContext) {
10546 Diag(Loc, diag::err_omp_enclosed_declare_target);
10547 return false;
10548 }
10549
10550 IsInOpenMPDeclareTargetContext = true;
10551 return true;
10552}
10553
10554void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10555 assert(IsInOpenMPDeclareTargetContext &&
10556 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10557
10558 IsInOpenMPDeclareTargetContext = false;
10559}
10560
David Majnemer9d168222016-08-05 17:44:54 +000010561void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10562 CXXScopeSpec &ScopeSpec,
10563 const DeclarationNameInfo &Id,
10564 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10565 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010566 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10567 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10568
10569 if (Lookup.isAmbiguous())
10570 return;
10571 Lookup.suppressDiagnostics();
10572
10573 if (!Lookup.isSingleResult()) {
10574 if (TypoCorrection Corrected =
10575 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10576 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10577 CTK_ErrorRecovery)) {
10578 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10579 << Id.getName());
10580 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10581 return;
10582 }
10583
10584 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10585 return;
10586 }
10587
10588 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10589 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10590 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10591 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10592
10593 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10594 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10595 ND->addAttr(A);
10596 if (ASTMutationListener *ML = Context.getASTMutationListener())
10597 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10598 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10599 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10600 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10601 << Id.getName();
10602 }
10603 } else
10604 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10605}
10606
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010607static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10608 Sema &SemaRef, Decl *D) {
10609 if (!D)
10610 return;
10611 Decl *LD = nullptr;
10612 if (isa<TagDecl>(D)) {
10613 LD = cast<TagDecl>(D)->getDefinition();
10614 } else if (isa<VarDecl>(D)) {
10615 LD = cast<VarDecl>(D)->getDefinition();
10616
10617 // If this is an implicit variable that is legal and we do not need to do
10618 // anything.
10619 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010620 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10621 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10622 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010623 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010624 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010625 return;
10626 }
10627
10628 } else if (isa<FunctionDecl>(D)) {
10629 const FunctionDecl *FD = nullptr;
10630 if (cast<FunctionDecl>(D)->hasBody(FD))
10631 LD = const_cast<FunctionDecl *>(FD);
10632
10633 // If the definition is associated with the current declaration in the
10634 // target region (it can be e.g. a lambda) that is legal and we do not need
10635 // to do anything else.
10636 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010637 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10638 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10639 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010640 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010641 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010642 return;
10643 }
10644 }
10645 if (!LD)
10646 LD = D;
10647 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10648 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10649 // Outlined declaration is not declared target.
10650 if (LD->isOutOfLine()) {
10651 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10652 SemaRef.Diag(SL, diag::note_used_here) << SR;
10653 } else {
10654 DeclContext *DC = LD->getDeclContext();
10655 while (DC) {
10656 if (isa<FunctionDecl>(DC) &&
10657 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10658 break;
10659 DC = DC->getParent();
10660 }
10661 if (DC)
10662 return;
10663
10664 // Is not declared in target context.
10665 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10666 SemaRef.Diag(SL, diag::note_used_here) << SR;
10667 }
10668 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010669 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10670 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10671 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010672 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010673 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010674 }
10675}
10676
10677static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10678 Sema &SemaRef, DSAStackTy *Stack,
10679 ValueDecl *VD) {
10680 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10681 return true;
10682 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10683 return false;
10684 return true;
10685}
10686
10687void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10688 if (!D || D->isInvalidDecl())
10689 return;
10690 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10691 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10692 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10693 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10694 if (DSAStack->isThreadPrivate(VD)) {
10695 Diag(SL, diag::err_omp_threadprivate_in_target);
10696 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10697 return;
10698 }
10699 }
10700 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10701 // Problem if any with var declared with incomplete type will be reported
10702 // as normal, so no need to check it here.
10703 if ((E || !VD->getType()->isIncompleteType()) &&
10704 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10705 // Mark decl as declared target to prevent further diagnostic.
10706 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010707 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10708 Context, OMPDeclareTargetDeclAttr::MT_To);
10709 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010710 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010711 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010712 }
10713 return;
10714 }
10715 }
10716 if (!E) {
10717 // Checking declaration inside declare target region.
10718 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10719 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010720 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10721 Context, OMPDeclareTargetDeclAttr::MT_To);
10722 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010723 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010724 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010725 }
10726 return;
10727 }
10728 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10729}
Samuel Antao661c0902016-05-26 17:39:58 +000010730
10731OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10732 SourceLocation StartLoc,
10733 SourceLocation LParenLoc,
10734 SourceLocation EndLoc) {
10735 MappableVarListInfo MVLI(VarList);
10736 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10737 if (MVLI.ProcessedVarList.empty())
10738 return nullptr;
10739
10740 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10741 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10742 MVLI.VarComponents);
10743}
Samuel Antaoec172c62016-05-26 17:49:04 +000010744
10745OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10746 SourceLocation StartLoc,
10747 SourceLocation LParenLoc,
10748 SourceLocation EndLoc) {
10749 MappableVarListInfo MVLI(VarList);
10750 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10751 if (MVLI.ProcessedVarList.empty())
10752 return nullptr;
10753
10754 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10755 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10756 MVLI.VarComponents);
10757}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010758
10759OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10760 SourceLocation StartLoc,
10761 SourceLocation LParenLoc,
10762 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010763 MappableVarListInfo MVLI(VarList);
10764 SmallVector<Expr *, 8> PrivateCopies;
10765 SmallVector<Expr *, 8> Inits;
10766
Carlo Bertolli2404b172016-07-13 15:37:16 +000010767 for (auto &RefExpr : VarList) {
10768 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10769 SourceLocation ELoc;
10770 SourceRange ERange;
10771 Expr *SimpleRefExpr = RefExpr;
10772 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10773 if (Res.second) {
10774 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010775 MVLI.ProcessedVarList.push_back(RefExpr);
10776 PrivateCopies.push_back(nullptr);
10777 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010778 }
10779 ValueDecl *D = Res.first;
10780 if (!D)
10781 continue;
10782
10783 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010784 Type = Type.getNonReferenceType().getUnqualifiedType();
10785
10786 auto *VD = dyn_cast<VarDecl>(D);
10787
10788 // Item should be a pointer or reference to pointer.
10789 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010790 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10791 << 0 << RefExpr->getSourceRange();
10792 continue;
10793 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010794
10795 // Build the private variable and the expression that refers to it.
10796 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10797 D->hasAttrs() ? &D->getAttrs() : nullptr);
10798 if (VDPrivate->isInvalidDecl())
10799 continue;
10800
10801 CurContext->addDecl(VDPrivate);
10802 auto VDPrivateRefExpr = buildDeclRefExpr(
10803 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10804
10805 // Add temporary variable to initialize the private copy of the pointer.
10806 auto *VDInit =
10807 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10808 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10809 RefExpr->getExprLoc());
10810 AddInitializerToDecl(VDPrivate,
10811 DefaultLvalueConversion(VDInitRefExpr).get(),
10812 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10813
10814 // If required, build a capture to implement the privatization initialized
10815 // with the current list item value.
10816 DeclRefExpr *Ref = nullptr;
10817 if (!VD)
10818 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10819 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10820 PrivateCopies.push_back(VDPrivateRefExpr);
10821 Inits.push_back(VDInitRefExpr);
10822
10823 // We need to add a data sharing attribute for this variable to make sure it
10824 // is correctly captured. A variable that shows up in a use_device_ptr has
10825 // similar properties of a first private variable.
10826 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10827
10828 // Create a mappable component for the list item. List items in this clause
10829 // only need a component.
10830 MVLI.VarBaseDeclarations.push_back(D);
10831 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10832 MVLI.VarComponents.back().push_back(
10833 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000010834 }
10835
Samuel Antaocc10b852016-07-28 14:23:26 +000010836 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000010837 return nullptr;
10838
Samuel Antaocc10b852016-07-28 14:23:26 +000010839 return OMPUseDevicePtrClause::Create(
10840 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10841 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010842}
Carlo Bertolli70594e92016-07-13 17:16:49 +000010843
10844OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10845 SourceLocation StartLoc,
10846 SourceLocation LParenLoc,
10847 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000010848 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010849 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000010850 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000010851 SourceLocation ELoc;
10852 SourceRange ERange;
10853 Expr *SimpleRefExpr = RefExpr;
10854 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10855 if (Res.second) {
10856 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000010857 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010858 }
10859 ValueDecl *D = Res.first;
10860 if (!D)
10861 continue;
10862
10863 QualType Type = D->getType();
10864 // item should be a pointer or array or reference to pointer or array
10865 if (!Type.getNonReferenceType()->isPointerType() &&
10866 !Type.getNonReferenceType()->isArrayType()) {
10867 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10868 << 0 << RefExpr->getSourceRange();
10869 continue;
10870 }
Samuel Antao6890b092016-07-28 14:25:09 +000010871
10872 // Check if the declaration in the clause does not show up in any data
10873 // sharing attribute.
10874 auto DVar = DSAStack->getTopDSA(D, false);
10875 if (isOpenMPPrivate(DVar.CKind)) {
10876 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10877 << getOpenMPClauseName(DVar.CKind)
10878 << getOpenMPClauseName(OMPC_is_device_ptr)
10879 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10880 ReportOriginalDSA(*this, DSAStack, D, DVar);
10881 continue;
10882 }
10883
10884 Expr *ConflictExpr;
10885 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010886 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010887 [&ConflictExpr](
10888 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10889 OpenMPClauseKind) -> bool {
10890 ConflictExpr = R.front().getAssociatedExpression();
10891 return true;
10892 })) {
10893 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10894 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10895 << ConflictExpr->getSourceRange();
10896 continue;
10897 }
10898
10899 // Store the components in the stack so that they can be used to check
10900 // against other clauses later on.
10901 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
10902 DSAStack->addMappableExpressionComponents(
10903 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
10904
10905 // Record the expression we've just processed.
10906 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
10907
10908 // Create a mappable component for the list item. List items in this clause
10909 // only need a component. We use a null declaration to signal fields in
10910 // 'this'.
10911 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
10912 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
10913 "Unexpected device pointer expression!");
10914 MVLI.VarBaseDeclarations.push_back(
10915 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
10916 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10917 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010918 }
10919
Samuel Antao6890b092016-07-28 14:25:09 +000010920 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000010921 return nullptr;
10922
Samuel Antao6890b092016-07-28 14:25:09 +000010923 return OMPIsDevicePtrClause::Create(
10924 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10925 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010926}