blob: f92b99713f2edf62977551c5a878ed35557621ad [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 Antao90927002016-04-26 14:54:23 +0000329 // Do the check specified in \a Check to all component lists and return true
330 // if any issue is found.
331 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 Antao90927002016-04-26 14:54:23 +0000358 // Create a new mappable expression component list associated with a given
359 // declaration and initialize it with the provided list of components.
360 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
922 // behaviour.
923 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:
1597 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001599 QualType KmpInt32PtrTy =
1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001601 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001602 std::make_pair(".global_tid.", KmpInt32PtrTy),
1603 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1604 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1607 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001608 break;
1609 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001610 case OMPD_simd:
1611 case OMPD_for:
1612 case OMPD_for_simd:
1613 case OMPD_sections:
1614 case OMPD_section:
1615 case OMPD_single:
1616 case OMPD_master:
1617 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001618 case OMPD_taskgroup:
1619 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001620 case OMPD_ordered:
1621 case OMPD_atomic:
1622 case OMPD_target_data:
1623 case OMPD_target:
1624 case OMPD_target_parallel:
1625 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001626 case OMPD_target_parallel_for_simd:
1627 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001628 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001629 std::make_pair(StringRef(), QualType()) // __context with shared vars
1630 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001631 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1632 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001633 break;
1634 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001635 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001636 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001637 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1638 FunctionProtoType::ExtProtoInfo EPI;
1639 EPI.Variadic = true;
1640 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001641 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001642 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001643 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1644 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1645 std::make_pair(".copy_fn.",
1646 Context.getPointerType(CopyFnType).withConst()),
1647 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001648 std::make_pair(StringRef(), QualType()) // __context with shared vars
1649 };
1650 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1651 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001652 // Mark this captured region as inlined, because we don't use outlined
1653 // function directly.
1654 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1655 AlwaysInlineAttr::CreateImplicit(
1656 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001657 break;
1658 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001659 case OMPD_taskloop:
1660 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001661 QualType KmpInt32Ty =
1662 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1663 QualType KmpUInt64Ty =
1664 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1665 QualType KmpInt64Ty =
1666 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1667 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1668 FunctionProtoType::ExtProtoInfo EPI;
1669 EPI.Variadic = true;
1670 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001671 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001672 std::make_pair(".global_tid.", KmpInt32Ty),
1673 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1674 std::make_pair(".privates.",
1675 Context.VoidPtrTy.withConst().withRestrict()),
1676 std::make_pair(
1677 ".copy_fn.",
1678 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1679 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1680 std::make_pair(".lb.", KmpUInt64Ty),
1681 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1682 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001683 std::make_pair(StringRef(), QualType()) // __context with shared vars
1684 };
1685 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1686 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001687 // Mark this captured region as inlined, because we don't use outlined
1688 // function directly.
1689 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1690 AlwaysInlineAttr::CreateImplicit(
1691 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001692 break;
1693 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001694 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001695 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001696 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001697 case OMPD_teams_distribute:
1698 case OMPD_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001699 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1700 QualType KmpInt32PtrTy =
1701 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1702 Sema::CapturedParamNameType Params[] = {
1703 std::make_pair(".global_tid.", KmpInt32PtrTy),
1704 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1705 std::make_pair(".previous.lb.", Context.getSizeType()),
1706 std::make_pair(".previous.ub.", Context.getSizeType()),
1707 std::make_pair(StringRef(), QualType()) // __context with shared vars
1708 };
1709 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1710 Params);
1711 break;
1712 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001713 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001714 case OMPD_taskyield:
1715 case OMPD_barrier:
1716 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001717 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001718 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001719 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001720 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001721 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001722 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001723 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001724 case OMPD_declare_target:
1725 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001726 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001727 llvm_unreachable("OpenMP Directive is not allowed");
1728 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001729 llvm_unreachable("Unknown OpenMP directive");
1730 }
1731}
1732
Alexey Bataev3392d762016-02-16 11:18:12 +00001733static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001734 Expr *CaptureExpr, bool WithInit,
1735 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001736 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001737 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001738 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001739 QualType Ty = Init->getType();
1740 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1741 if (S.getLangOpts().CPlusPlus)
1742 Ty = C.getLValueReferenceType(Ty);
1743 else {
1744 Ty = C.getPointerType(Ty);
1745 ExprResult Res =
1746 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1747 if (!Res.isUsable())
1748 return nullptr;
1749 Init = Res.get();
1750 }
Alexey Bataev61205072016-03-02 04:57:40 +00001751 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001752 }
1753 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001754 if (!WithInit)
1755 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001756 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001757 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1758 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001759 return CED;
1760}
1761
Alexey Bataev61205072016-03-02 04:57:40 +00001762static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1763 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001764 OMPCapturedExprDecl *CD;
1765 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1766 CD = cast<OMPCapturedExprDecl>(VD);
1767 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001768 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1769 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001770 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001771 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001772}
1773
Alexey Bataev5a3af132016-03-29 08:58:54 +00001774static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1775 if (!Ref) {
1776 auto *CD =
1777 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1778 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1779 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1780 CaptureExpr->getExprLoc());
1781 }
1782 ExprResult Res = Ref;
1783 if (!S.getLangOpts().CPlusPlus &&
1784 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1785 Ref->getType()->isPointerType())
1786 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1787 if (!Res.isUsable())
1788 return ExprError();
1789 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001790}
1791
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001792StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1793 ArrayRef<OMPClause *> Clauses) {
1794 if (!S.isUsable()) {
1795 ActOnCapturedRegionError();
1796 return StmtError();
1797 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001798
1799 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001800 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001801 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001802 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001803 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001804 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001805 Clause->getClauseKind() == OMPC_copyprivate ||
1806 (getLangOpts().OpenMPUseTLS &&
1807 getASTContext().getTargetInfo().isTLSSupported() &&
1808 Clause->getClauseKind() == OMPC_copyin)) {
1809 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001810 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001811 for (auto *VarRef : Clause->children()) {
1812 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001813 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001814 }
1815 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001816 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001817 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001818 // Mark all variables in private list clauses as used in inner region.
1819 // Required for proper codegen of combined directives.
1820 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001821 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001822 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1823 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001824 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1825 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001826 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001827 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1828 if (auto *E = C->getPostUpdateExpr())
1829 MarkDeclarationsReferencedInExpr(E);
1830 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001831 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001832 if (Clause->getClauseKind() == OMPC_schedule)
1833 SC = cast<OMPScheduleClause>(Clause);
1834 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001835 OC = cast<OMPOrderedClause>(Clause);
1836 else if (Clause->getClauseKind() == OMPC_linear)
1837 LCs.push_back(cast<OMPLinearClause>(Clause));
1838 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001839 bool ErrorFound = false;
1840 // OpenMP, 2.7.1 Loop Construct, Restrictions
1841 // The nonmonotonic modifier cannot be specified if an ordered clause is
1842 // specified.
1843 if (SC &&
1844 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1845 SC->getSecondScheduleModifier() ==
1846 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1847 OC) {
1848 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1849 ? SC->getFirstScheduleModifierLoc()
1850 : SC->getSecondScheduleModifierLoc(),
1851 diag::err_omp_schedule_nonmonotonic_ordered)
1852 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1853 ErrorFound = true;
1854 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001855 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1856 for (auto *C : LCs) {
1857 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1858 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1859 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001860 ErrorFound = true;
1861 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001862 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1863 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1864 OC->getNumForLoops()) {
1865 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1866 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1867 ErrorFound = true;
1868 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001869 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001870 ActOnCapturedRegionError();
1871 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001872 }
1873 return ActOnCapturedRegionEnd(S.get());
1874}
1875
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001876static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1877 OpenMPDirectiveKind CurrentRegion,
1878 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001879 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001880 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001881 if (Stack->getCurScope()) {
1882 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001883 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001884 bool NestingProhibited = false;
1885 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001886 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001887 enum {
1888 NoRecommend,
1889 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001890 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001891 ShouldBeInTargetRegion,
1892 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001893 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001894 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001895 // OpenMP [2.16, Nesting of Regions]
1896 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001897 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001898 // An ordered construct with the simd clause is the only OpenMP
1899 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001900 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001901 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1902 // message.
1903 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1904 ? diag::err_omp_prohibited_region_simd
1905 : diag::warn_omp_nesting_simd);
1906 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001907 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001908 if (ParentRegion == OMPD_atomic) {
1909 // OpenMP [2.16, Nesting of Regions]
1910 // OpenMP constructs may not be nested inside an atomic region.
1911 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1912 return true;
1913 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001914 if (CurrentRegion == OMPD_section) {
1915 // OpenMP [2.7.2, sections Construct, Restrictions]
1916 // Orphaned section directives are prohibited. That is, the section
1917 // directives must appear within the sections construct and must not be
1918 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001919 if (ParentRegion != OMPD_sections &&
1920 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001921 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1922 << (ParentRegion != OMPD_unknown)
1923 << getOpenMPDirectiveName(ParentRegion);
1924 return true;
1925 }
1926 return false;
1927 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001928 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001929 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001930 // preconditions).
1931 if (ParentRegion == OMPD_unknown && !isOpenMPTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001932 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001933 if (CurrentRegion == OMPD_cancellation_point ||
1934 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001935 // OpenMP [2.16, Nesting of Regions]
1936 // A cancellation point construct for which construct-type-clause is
1937 // taskgroup must be nested inside a task construct. A cancellation
1938 // point construct for which construct-type-clause is not taskgroup must
1939 // be closely nested inside an OpenMP construct that matches the type
1940 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001941 // A cancel construct for which construct-type-clause is taskgroup must be
1942 // nested inside a task construct. A cancel construct for which
1943 // construct-type-clause is not taskgroup must be closely nested inside an
1944 // OpenMP construct that matches the type specified in
1945 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001946 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001947 !((CancelRegion == OMPD_parallel &&
1948 (ParentRegion == OMPD_parallel ||
1949 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001950 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001951 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1952 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001953 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1954 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001955 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1956 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001957 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001958 // OpenMP [2.16, Nesting of Regions]
1959 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001960 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001961 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001962 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001963 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1964 // OpenMP [2.16, Nesting of Regions]
1965 // A critical region may not be nested (closely or otherwise) inside a
1966 // critical region with the same name. Note that this restriction is not
1967 // sufficient to prevent deadlock.
1968 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001969 bool DeadLock = Stack->hasDirective(
1970 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1971 const DeclarationNameInfo &DNI,
1972 SourceLocation Loc) -> bool {
1973 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1974 PreviousCriticalLoc = Loc;
1975 return true;
1976 } else
1977 return false;
1978 },
1979 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001980 if (DeadLock) {
1981 SemaRef.Diag(StartLoc,
1982 diag::err_omp_prohibited_region_critical_same_name)
1983 << CurrentName.getName();
1984 if (PreviousCriticalLoc.isValid())
1985 SemaRef.Diag(PreviousCriticalLoc,
1986 diag::note_omp_previous_critical_region);
1987 return true;
1988 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001989 } else if (CurrentRegion == OMPD_barrier) {
1990 // OpenMP [2.16, Nesting of Regions]
1991 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001992 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001993 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1994 isOpenMPTaskingDirective(ParentRegion) ||
1995 ParentRegion == OMPD_master ||
1996 ParentRegion == OMPD_critical ||
1997 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001998 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001999 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002000 // OpenMP [2.16, Nesting of Regions]
2001 // A worksharing region may not be closely nested inside a worksharing,
2002 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002003 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2004 isOpenMPTaskingDirective(ParentRegion) ||
2005 ParentRegion == OMPD_master ||
2006 ParentRegion == OMPD_critical ||
2007 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002008 Recommend = ShouldBeInParallelRegion;
2009 } else if (CurrentRegion == OMPD_ordered) {
2010 // OpenMP [2.16, Nesting of Regions]
2011 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002012 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002013 // An ordered region must be closely nested inside a loop region (or
2014 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002015 // OpenMP [2.8.1,simd Construct, Restrictions]
2016 // An ordered construct with the simd clause is the only OpenMP construct
2017 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002018 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002019 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002020 !(isOpenMPSimdDirective(ParentRegion) ||
2021 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002022 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002023 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2024 // OpenMP [2.16, Nesting of Regions]
2025 // If specified, a teams construct must be contained within a target
2026 // construct.
2027 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002028 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002029 Recommend = ShouldBeInTargetRegion;
2030 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2031 }
Kelvin Li02532872016-08-05 14:37:37 +00002032 if (!NestingProhibited && ParentRegion == OMPD_teams) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002033 // OpenMP [2.16, Nesting of Regions]
2034 // distribute, parallel, parallel sections, parallel workshare, and the
2035 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2036 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002037 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2038 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002039 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002040 }
David Majnemer9d168222016-08-05 17:44:54 +00002041 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002042 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002043 // OpenMP 4.5 [2.17 Nesting of Regions]
2044 // The region associated with the distribute construct must be strictly
2045 // nested inside a teams region
Kelvin Li02532872016-08-05 14:37:37 +00002046 NestingProhibited = ParentRegion != OMPD_teams;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002047 Recommend = ShouldBeInTeamsRegion;
2048 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002049 if (!NestingProhibited &&
2050 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2051 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2052 // OpenMP 4.5 [2.17 Nesting of Regions]
2053 // If a target, target update, target data, target enter data, or
2054 // target exit data construct is encountered during execution of a
2055 // target region, the behavior is unspecified.
2056 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002057 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2058 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002059 if (isOpenMPTargetExecutionDirective(K)) {
2060 OffendingRegion = K;
2061 return true;
2062 } else
2063 return false;
2064 },
2065 false /* don't skip top directive */);
2066 CloseNesting = false;
2067 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002068 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002069 if (OrphanSeen) {
2070 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2071 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2072 } else {
2073 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2074 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2075 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2076 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002077 return true;
2078 }
2079 }
2080 return false;
2081}
2082
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002083static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2084 ArrayRef<OMPClause *> Clauses,
2085 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2086 bool ErrorFound = false;
2087 unsigned NamedModifiersNumber = 0;
2088 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2089 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002090 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002091 for (const auto *C : Clauses) {
2092 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2093 // At most one if clause without a directive-name-modifier can appear on
2094 // the directive.
2095 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2096 if (FoundNameModifiers[CurNM]) {
2097 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2098 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2099 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2100 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002101 } else if (CurNM != OMPD_unknown) {
2102 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002103 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002104 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002105 FoundNameModifiers[CurNM] = IC;
2106 if (CurNM == OMPD_unknown)
2107 continue;
2108 // Check if the specified name modifier is allowed for the current
2109 // directive.
2110 // At most one if clause with the particular directive-name-modifier can
2111 // appear on the directive.
2112 bool MatchFound = false;
2113 for (auto NM : AllowedNameModifiers) {
2114 if (CurNM == NM) {
2115 MatchFound = true;
2116 break;
2117 }
2118 }
2119 if (!MatchFound) {
2120 S.Diag(IC->getNameModifierLoc(),
2121 diag::err_omp_wrong_if_directive_name_modifier)
2122 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2123 ErrorFound = true;
2124 }
2125 }
2126 }
2127 // If any if clause on the directive includes a directive-name-modifier then
2128 // all if clauses on the directive must include a directive-name-modifier.
2129 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2130 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2131 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2132 diag::err_omp_no_more_if_clause);
2133 } else {
2134 std::string Values;
2135 std::string Sep(", ");
2136 unsigned AllowedCnt = 0;
2137 unsigned TotalAllowedNum =
2138 AllowedNameModifiers.size() - NamedModifiersNumber;
2139 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2140 ++Cnt) {
2141 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2142 if (!FoundNameModifiers[NM]) {
2143 Values += "'";
2144 Values += getOpenMPDirectiveName(NM);
2145 Values += "'";
2146 if (AllowedCnt + 2 == TotalAllowedNum)
2147 Values += " or ";
2148 else if (AllowedCnt + 1 != TotalAllowedNum)
2149 Values += Sep;
2150 ++AllowedCnt;
2151 }
2152 }
2153 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2154 diag::err_omp_unnamed_if_clause)
2155 << (TotalAllowedNum > 1) << Values;
2156 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002157 for (auto Loc : NameModifierLoc) {
2158 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2159 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002160 ErrorFound = true;
2161 }
2162 return ErrorFound;
2163}
2164
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002165StmtResult Sema::ActOnOpenMPExecutableDirective(
2166 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2167 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2168 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002169 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002170 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2171 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002172 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002173
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002174 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002175 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002176 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002177 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002178 if (AStmt) {
2179 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2180
2181 // Check default data sharing attributes for referenced variables.
2182 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2183 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2184 if (DSAChecker.isErrorFound())
2185 return StmtError();
2186 // Generate list of implicitly defined firstprivate variables.
2187 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002188
2189 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2190 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2191 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2192 SourceLocation(), SourceLocation())) {
2193 ClausesWithImplicit.push_back(Implicit);
2194 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2195 DSAChecker.getImplicitFirstprivate().size();
2196 } else
2197 ErrorFound = true;
2198 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002199 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002200
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002201 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002202 switch (Kind) {
2203 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002204 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2205 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002206 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002207 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002208 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002209 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2210 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002211 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002212 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002213 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2214 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002215 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002216 case OMPD_for_simd:
2217 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2218 EndLoc, VarsWithInheritedDSA);
2219 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002220 case OMPD_sections:
2221 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2222 EndLoc);
2223 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002224 case OMPD_section:
2225 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002226 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002227 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2228 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002229 case OMPD_single:
2230 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2231 EndLoc);
2232 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002233 case OMPD_master:
2234 assert(ClausesWithImplicit.empty() &&
2235 "No clauses are allowed for 'omp master' directive");
2236 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2237 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002238 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002239 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2240 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002241 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002242 case OMPD_parallel_for:
2243 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2244 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002245 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002246 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002247 case OMPD_parallel_for_simd:
2248 Res = ActOnOpenMPParallelForSimdDirective(
2249 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002250 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002251 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002252 case OMPD_parallel_sections:
2253 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2254 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002255 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002256 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002257 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002258 Res =
2259 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002260 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002261 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002262 case OMPD_taskyield:
2263 assert(ClausesWithImplicit.empty() &&
2264 "No clauses are allowed for 'omp taskyield' directive");
2265 assert(AStmt == nullptr &&
2266 "No associated statement allowed for 'omp taskyield' directive");
2267 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2268 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002269 case OMPD_barrier:
2270 assert(ClausesWithImplicit.empty() &&
2271 "No clauses are allowed for 'omp barrier' directive");
2272 assert(AStmt == nullptr &&
2273 "No associated statement allowed for 'omp barrier' directive");
2274 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2275 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002276 case OMPD_taskwait:
2277 assert(ClausesWithImplicit.empty() &&
2278 "No clauses are allowed for 'omp taskwait' directive");
2279 assert(AStmt == nullptr &&
2280 "No associated statement allowed for 'omp taskwait' directive");
2281 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2282 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002283 case OMPD_taskgroup:
2284 assert(ClausesWithImplicit.empty() &&
2285 "No clauses are allowed for 'omp taskgroup' directive");
2286 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2287 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002288 case OMPD_flush:
2289 assert(AStmt == nullptr &&
2290 "No associated statement allowed for 'omp flush' directive");
2291 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2292 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002293 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002294 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2295 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002296 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002297 case OMPD_atomic:
2298 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2299 EndLoc);
2300 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002301 case OMPD_teams:
2302 Res =
2303 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2304 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002305 case OMPD_target:
2306 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2307 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002308 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002309 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002310 case OMPD_target_parallel:
2311 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2312 StartLoc, EndLoc);
2313 AllowedNameModifiers.push_back(OMPD_target);
2314 AllowedNameModifiers.push_back(OMPD_parallel);
2315 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002316 case OMPD_target_parallel_for:
2317 Res = ActOnOpenMPTargetParallelForDirective(
2318 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2319 AllowedNameModifiers.push_back(OMPD_target);
2320 AllowedNameModifiers.push_back(OMPD_parallel);
2321 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002322 case OMPD_cancellation_point:
2323 assert(ClausesWithImplicit.empty() &&
2324 "No clauses are allowed for 'omp cancellation point' directive");
2325 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2326 "cancellation point' directive");
2327 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2328 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002329 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002330 assert(AStmt == nullptr &&
2331 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002332 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2333 CancelRegion);
2334 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002335 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002336 case OMPD_target_data:
2337 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2338 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002339 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002340 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002341 case OMPD_target_enter_data:
2342 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2343 EndLoc);
2344 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2345 break;
Samuel Antao72590762016-01-19 20:04:50 +00002346 case OMPD_target_exit_data:
2347 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2348 EndLoc);
2349 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2350 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002351 case OMPD_taskloop:
2352 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2353 EndLoc, VarsWithInheritedDSA);
2354 AllowedNameModifiers.push_back(OMPD_taskloop);
2355 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002356 case OMPD_taskloop_simd:
2357 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2358 EndLoc, VarsWithInheritedDSA);
2359 AllowedNameModifiers.push_back(OMPD_taskloop);
2360 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002361 case OMPD_distribute:
2362 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2363 EndLoc, VarsWithInheritedDSA);
2364 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002365 case OMPD_target_update:
2366 assert(!AStmt && "Statement is not allowed for target update");
2367 Res =
2368 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2369 AllowedNameModifiers.push_back(OMPD_target_update);
2370 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002371 case OMPD_distribute_parallel_for:
2372 Res = ActOnOpenMPDistributeParallelForDirective(
2373 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2374 AllowedNameModifiers.push_back(OMPD_parallel);
2375 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002376 case OMPD_distribute_parallel_for_simd:
2377 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2378 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2379 AllowedNameModifiers.push_back(OMPD_parallel);
2380 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002381 case OMPD_distribute_simd:
2382 Res = ActOnOpenMPDistributeSimdDirective(
2383 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2384 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002385 case OMPD_target_parallel_for_simd:
2386 Res = ActOnOpenMPTargetParallelForSimdDirective(
2387 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2388 AllowedNameModifiers.push_back(OMPD_target);
2389 AllowedNameModifiers.push_back(OMPD_parallel);
2390 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002391 case OMPD_target_simd:
2392 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2393 EndLoc, VarsWithInheritedDSA);
2394 AllowedNameModifiers.push_back(OMPD_target);
2395 break;
Kelvin Li02532872016-08-05 14:37:37 +00002396 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002397 Res = ActOnOpenMPTeamsDistributeDirective(
2398 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002399 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002400 case OMPD_teams_distribute_simd:
2401 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2402 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2403 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002404 case OMPD_declare_target:
2405 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002406 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002407 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002408 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002409 llvm_unreachable("OpenMP Directive is not allowed");
2410 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002411 llvm_unreachable("Unknown OpenMP directive");
2412 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002413
Alexey Bataev4acb8592014-07-07 13:01:15 +00002414 for (auto P : VarsWithInheritedDSA) {
2415 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2416 << P.first << P.second->getSourceRange();
2417 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002418 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2419
2420 if (!AllowedNameModifiers.empty())
2421 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2422 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002423
Alexey Bataeved09d242014-05-28 05:53:51 +00002424 if (ErrorFound)
2425 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002426 return Res;
2427}
2428
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002429Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2430 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002431 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002432 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2433 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002434 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002435 assert(Linears.size() == LinModifiers.size());
2436 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002437 if (!DG || DG.get().isNull())
2438 return DeclGroupPtrTy();
2439
2440 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002441 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002442 return DG;
2443 }
2444 auto *ADecl = DG.get().getSingleDecl();
2445 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2446 ADecl = FTD->getTemplatedDecl();
2447
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002448 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2449 if (!FD) {
2450 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002451 return DeclGroupPtrTy();
2452 }
2453
Alexey Bataev2af33e32016-04-07 12:45:37 +00002454 // OpenMP [2.8.2, declare simd construct, Description]
2455 // The parameter of the simdlen clause must be a constant positive integer
2456 // expression.
2457 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002458 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002459 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002460 // OpenMP [2.8.2, declare simd construct, Description]
2461 // The special this pointer can be used as if was one of the arguments to the
2462 // function in any of the linear, aligned, or uniform clauses.
2463 // The uniform clause declares one or more arguments to have an invariant
2464 // value for all concurrent invocations of the function in the execution of a
2465 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002466 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2467 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002468 for (auto *E : Uniforms) {
2469 E = E->IgnoreParenImpCasts();
2470 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2471 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2472 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2473 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002474 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2475 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002476 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002477 }
2478 if (isa<CXXThisExpr>(E)) {
2479 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002480 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002481 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002482 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2483 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002484 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002485 // OpenMP [2.8.2, declare simd construct, Description]
2486 // The aligned clause declares that the object to which each list item points
2487 // is aligned to the number of bytes expressed in the optional parameter of
2488 // the aligned clause.
2489 // The special this pointer can be used as if was one of the arguments to the
2490 // function in any of the linear, aligned, or uniform clauses.
2491 // The type of list items appearing in the aligned clause must be array,
2492 // pointer, reference to array, or reference to pointer.
2493 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2494 Expr *AlignedThis = nullptr;
2495 for (auto *E : Aligneds) {
2496 E = E->IgnoreParenImpCasts();
2497 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2498 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2499 auto *CanonPVD = PVD->getCanonicalDecl();
2500 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2501 FD->getParamDecl(PVD->getFunctionScopeIndex())
2502 ->getCanonicalDecl() == CanonPVD) {
2503 // OpenMP [2.8.1, simd construct, Restrictions]
2504 // A list-item cannot appear in more than one aligned clause.
2505 if (AlignedArgs.count(CanonPVD) > 0) {
2506 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2507 << 1 << E->getSourceRange();
2508 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2509 diag::note_omp_explicit_dsa)
2510 << getOpenMPClauseName(OMPC_aligned);
2511 continue;
2512 }
2513 AlignedArgs[CanonPVD] = E;
2514 QualType QTy = PVD->getType()
2515 .getNonReferenceType()
2516 .getUnqualifiedType()
2517 .getCanonicalType();
2518 const Type *Ty = QTy.getTypePtrOrNull();
2519 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2520 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2521 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2522 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2523 }
2524 continue;
2525 }
2526 }
2527 if (isa<CXXThisExpr>(E)) {
2528 if (AlignedThis) {
2529 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2530 << 2 << E->getSourceRange();
2531 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2532 << getOpenMPClauseName(OMPC_aligned);
2533 }
2534 AlignedThis = E;
2535 continue;
2536 }
2537 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2538 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2539 }
2540 // The optional parameter of the aligned clause, alignment, must be a constant
2541 // positive integer expression. If no optional parameter is specified,
2542 // implementation-defined default alignments for SIMD instructions on the
2543 // target platforms are assumed.
2544 SmallVector<Expr *, 4> NewAligns;
2545 for (auto *E : Alignments) {
2546 ExprResult Align;
2547 if (E)
2548 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2549 NewAligns.push_back(Align.get());
2550 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002551 // OpenMP [2.8.2, declare simd construct, Description]
2552 // The linear clause declares one or more list items to be private to a SIMD
2553 // lane and to have a linear relationship with respect to the iteration space
2554 // of a loop.
2555 // The special this pointer can be used as if was one of the arguments to the
2556 // function in any of the linear, aligned, or uniform clauses.
2557 // When a linear-step expression is specified in a linear clause it must be
2558 // either a constant integer expression or an integer-typed parameter that is
2559 // specified in a uniform clause on the directive.
2560 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2561 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2562 auto MI = LinModifiers.begin();
2563 for (auto *E : Linears) {
2564 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2565 ++MI;
2566 E = E->IgnoreParenImpCasts();
2567 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2568 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2569 auto *CanonPVD = PVD->getCanonicalDecl();
2570 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2571 FD->getParamDecl(PVD->getFunctionScopeIndex())
2572 ->getCanonicalDecl() == CanonPVD) {
2573 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2574 // A list-item cannot appear in more than one linear clause.
2575 if (LinearArgs.count(CanonPVD) > 0) {
2576 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2577 << getOpenMPClauseName(OMPC_linear)
2578 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2579 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2580 diag::note_omp_explicit_dsa)
2581 << getOpenMPClauseName(OMPC_linear);
2582 continue;
2583 }
2584 // Each argument can appear in at most one uniform or linear clause.
2585 if (UniformedArgs.count(CanonPVD) > 0) {
2586 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2587 << getOpenMPClauseName(OMPC_linear)
2588 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2589 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2590 diag::note_omp_explicit_dsa)
2591 << getOpenMPClauseName(OMPC_uniform);
2592 continue;
2593 }
2594 LinearArgs[CanonPVD] = E;
2595 if (E->isValueDependent() || E->isTypeDependent() ||
2596 E->isInstantiationDependent() ||
2597 E->containsUnexpandedParameterPack())
2598 continue;
2599 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2600 PVD->getOriginalType());
2601 continue;
2602 }
2603 }
2604 if (isa<CXXThisExpr>(E)) {
2605 if (UniformedLinearThis) {
2606 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2607 << getOpenMPClauseName(OMPC_linear)
2608 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2609 << E->getSourceRange();
2610 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2611 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2612 : OMPC_linear);
2613 continue;
2614 }
2615 UniformedLinearThis = E;
2616 if (E->isValueDependent() || E->isTypeDependent() ||
2617 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2618 continue;
2619 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2620 E->getType());
2621 continue;
2622 }
2623 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2624 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2625 }
2626 Expr *Step = nullptr;
2627 Expr *NewStep = nullptr;
2628 SmallVector<Expr *, 4> NewSteps;
2629 for (auto *E : Steps) {
2630 // Skip the same step expression, it was checked already.
2631 if (Step == E || !E) {
2632 NewSteps.push_back(E ? NewStep : nullptr);
2633 continue;
2634 }
2635 Step = E;
2636 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2637 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2638 auto *CanonPVD = PVD->getCanonicalDecl();
2639 if (UniformedArgs.count(CanonPVD) == 0) {
2640 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2641 << Step->getSourceRange();
2642 } else if (E->isValueDependent() || E->isTypeDependent() ||
2643 E->isInstantiationDependent() ||
2644 E->containsUnexpandedParameterPack() ||
2645 CanonPVD->getType()->hasIntegerRepresentation())
2646 NewSteps.push_back(Step);
2647 else {
2648 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2649 << Step->getSourceRange();
2650 }
2651 continue;
2652 }
2653 NewStep = Step;
2654 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2655 !Step->isInstantiationDependent() &&
2656 !Step->containsUnexpandedParameterPack()) {
2657 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2658 .get();
2659 if (NewStep)
2660 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2661 }
2662 NewSteps.push_back(NewStep);
2663 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002664 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2665 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002666 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002667 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2668 const_cast<Expr **>(Linears.data()), Linears.size(),
2669 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2670 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002671 ADecl->addAttr(NewAttr);
2672 return ConvertDeclToDeclGroup(ADecl);
2673}
2674
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002675StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2676 Stmt *AStmt,
2677 SourceLocation StartLoc,
2678 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002679 if (!AStmt)
2680 return StmtError();
2681
Alexey Bataev9959db52014-05-06 10:08:46 +00002682 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2683 // 1.2.2 OpenMP Language Terminology
2684 // Structured block - An executable statement with a single entry at the
2685 // top and a single exit at the bottom.
2686 // The point of exit cannot be a branch out of the structured block.
2687 // longjmp() and throw() must not violate the entry/exit criteria.
2688 CS->getCapturedDecl()->setNothrow();
2689
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002690 getCurFunction()->setHasBranchProtectedScope();
2691
Alexey Bataev25e5b442015-09-15 12:52:43 +00002692 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2693 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002694}
2695
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002696namespace {
2697/// \brief Helper class for checking canonical form of the OpenMP loops and
2698/// extracting iteration space of each loop in the loop nest, that will be used
2699/// for IR generation.
2700class OpenMPIterationSpaceChecker {
2701 /// \brief Reference to Sema.
2702 Sema &SemaRef;
2703 /// \brief A location for diagnostics (when there is no some better location).
2704 SourceLocation DefaultLoc;
2705 /// \brief A location for diagnostics (when increment is not compatible).
2706 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002707 /// \brief A source location for referring to loop init later.
2708 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002709 /// \brief A source location for referring to condition later.
2710 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002711 /// \brief A source location for referring to increment later.
2712 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002713 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002714 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002715 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002716 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002717 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002718 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002719 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002720 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002721 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002722 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002723 /// \brief This flag is true when condition is one of:
2724 /// Var < UB
2725 /// Var <= UB
2726 /// UB > Var
2727 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002728 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002729 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002730 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002731 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002732 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002733
2734public:
2735 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002736 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002737 /// \brief Check init-expr for canonical loop form and save loop counter
2738 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002739 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002740 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2741 /// for less/greater and for strict/non-strict comparison.
2742 bool CheckCond(Expr *S);
2743 /// \brief Check incr-expr for canonical loop form and return true if it
2744 /// does not conform, otherwise save loop step (#Step).
2745 bool CheckInc(Expr *S);
2746 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002747 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002748 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002749 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002750 /// \brief Source range of the loop init.
2751 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2752 /// \brief Source range of the loop condition.
2753 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2754 /// \brief Source range of the loop increment.
2755 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2756 /// \brief True if the step should be subtracted.
2757 bool ShouldSubtractStep() const { return SubtractStep; }
2758 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002759 Expr *
2760 BuildNumIterations(Scope *S, const bool LimitedType,
2761 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002762 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002763 Expr *BuildPreCond(Scope *S, Expr *Cond,
2764 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002765 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002766 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2767 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002768 /// \brief Build reference expression to the private counter be used for
2769 /// codegen.
2770 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002771 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002772 Expr *BuildCounterInit() const;
2773 /// \brief Build step of the counter be used for codegen.
2774 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002775 /// \brief Return true if any expression is dependent.
2776 bool Dependent() const;
2777
2778private:
2779 /// \brief Check the right-hand side of an assignment in the increment
2780 /// expression.
2781 bool CheckIncRHS(Expr *RHS);
2782 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002783 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002784 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002785 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002786 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002787 /// \brief Helper to set loop increment.
2788 bool SetStep(Expr *NewStep, bool Subtract);
2789};
2790
2791bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002792 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002793 assert(!LB && !UB && !Step);
2794 return false;
2795 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002796 return LCDecl->getType()->isDependentType() ||
2797 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2798 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002799}
2800
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002801static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002802 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2803 E = ExprTemp->getSubExpr();
2804
2805 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2806 E = MTE->GetTemporaryExpr();
2807
2808 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2809 E = Binder->getSubExpr();
2810
2811 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2812 E = ICE->getSubExprAsWritten();
2813 return E->IgnoreParens();
2814}
2815
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002816bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2817 Expr *NewLCRefExpr,
2818 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002819 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002820 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002821 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002822 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002823 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002824 LCDecl = getCanonicalDecl(NewLCDecl);
2825 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002826 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2827 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002828 if ((Ctor->isCopyOrMoveConstructor() ||
2829 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2830 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002831 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002832 LB = NewLB;
2833 return false;
2834}
2835
2836bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002837 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002838 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002839 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2840 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002841 if (!NewUB)
2842 return true;
2843 UB = NewUB;
2844 TestIsLessOp = LessOp;
2845 TestIsStrictOp = StrictOp;
2846 ConditionSrcRange = SR;
2847 ConditionLoc = SL;
2848 return false;
2849}
2850
2851bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2852 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002853 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002854 if (!NewStep)
2855 return true;
2856 if (!NewStep->isValueDependent()) {
2857 // Check that the step is integer expression.
2858 SourceLocation StepLoc = NewStep->getLocStart();
2859 ExprResult Val =
2860 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2861 if (Val.isInvalid())
2862 return true;
2863 NewStep = Val.get();
2864
2865 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2866 // If test-expr is of form var relational-op b and relational-op is < or
2867 // <= then incr-expr must cause var to increase on each iteration of the
2868 // loop. If test-expr is of form var relational-op b and relational-op is
2869 // > or >= then incr-expr must cause var to decrease on each iteration of
2870 // the loop.
2871 // If test-expr is of form b relational-op var and relational-op is < or
2872 // <= then incr-expr must cause var to decrease on each iteration of the
2873 // loop. If test-expr is of form b relational-op var and relational-op is
2874 // > or >= then incr-expr must cause var to increase on each iteration of
2875 // the loop.
2876 llvm::APSInt Result;
2877 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2878 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2879 bool IsConstNeg =
2880 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002881 bool IsConstPos =
2882 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002883 bool IsConstZero = IsConstant && !Result.getBoolValue();
2884 if (UB && (IsConstZero ||
2885 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002886 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002887 SemaRef.Diag(NewStep->getExprLoc(),
2888 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002889 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002890 SemaRef.Diag(ConditionLoc,
2891 diag::note_omp_loop_cond_requres_compatible_incr)
2892 << TestIsLessOp << ConditionSrcRange;
2893 return true;
2894 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002895 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002896 NewStep =
2897 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2898 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002899 Subtract = !Subtract;
2900 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002901 }
2902
2903 Step = NewStep;
2904 SubtractStep = Subtract;
2905 return false;
2906}
2907
Alexey Bataev9c821032015-04-30 04:23:23 +00002908bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002909 // Check init-expr for canonical loop form and save loop counter
2910 // variable - #Var and its initialization value - #LB.
2911 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2912 // var = lb
2913 // integer-type var = lb
2914 // random-access-iterator-type var = lb
2915 // pointer-type var = lb
2916 //
2917 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002918 if (EmitDiags) {
2919 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2920 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002921 return true;
2922 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002923 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2924 if (!ExprTemp->cleanupsHaveSideEffects())
2925 S = ExprTemp->getSubExpr();
2926
Alexander Musmana5f070a2014-10-01 06:03:56 +00002927 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002928 if (Expr *E = dyn_cast<Expr>(S))
2929 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002930 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002931 if (BO->getOpcode() == BO_Assign) {
2932 auto *LHS = BO->getLHS()->IgnoreParens();
2933 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2934 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2935 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2936 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2937 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2938 }
2939 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2940 if (ME->isArrow() &&
2941 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2942 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2943 }
2944 }
David Majnemer9d168222016-08-05 17:44:54 +00002945 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002946 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002947 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002948 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002949 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002950 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002951 SemaRef.Diag(S->getLocStart(),
2952 diag::ext_omp_loop_not_canonical_init)
2953 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002954 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002955 }
2956 }
2957 }
David Majnemer9d168222016-08-05 17:44:54 +00002958 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002959 if (CE->getOperator() == OO_Equal) {
2960 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00002961 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002962 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2963 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2964 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2965 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
2966 }
2967 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2968 if (ME->isArrow() &&
2969 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2970 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2971 }
2972 }
2973 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002974
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002975 if (Dependent() || SemaRef.CurContext->isDependentContext())
2976 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00002977 if (EmitDiags) {
2978 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2979 << S->getSourceRange();
2980 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002981 return true;
2982}
2983
Alexey Bataev23b69422014-06-18 07:08:49 +00002984/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002985/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002986static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002987 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002988 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002989 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002990 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2991 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002992 if ((Ctor->isCopyOrMoveConstructor() ||
2993 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2994 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002995 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002996 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
2997 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2998 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2999 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3000 return getCanonicalDecl(ME->getMemberDecl());
3001 return getCanonicalDecl(VD);
3002 }
3003 }
3004 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3005 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3006 return getCanonicalDecl(ME->getMemberDecl());
3007 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003008}
3009
3010bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3011 // Check test-expr for canonical form, save upper-bound UB, flags for
3012 // less/greater and for strict/non-strict comparison.
3013 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3014 // var relational-op b
3015 // b relational-op var
3016 //
3017 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003018 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003019 return true;
3020 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003021 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003022 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003023 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003024 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003025 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003026 return SetUB(BO->getRHS(),
3027 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3028 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3029 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003030 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003031 return SetUB(BO->getLHS(),
3032 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3033 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3034 BO->getSourceRange(), BO->getOperatorLoc());
3035 }
David Majnemer9d168222016-08-05 17:44:54 +00003036 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003037 if (CE->getNumArgs() == 2) {
3038 auto Op = CE->getOperator();
3039 switch (Op) {
3040 case OO_Greater:
3041 case OO_GreaterEqual:
3042 case OO_Less:
3043 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003044 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003045 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3046 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3047 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003048 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003049 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3050 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3051 CE->getOperatorLoc());
3052 break;
3053 default:
3054 break;
3055 }
3056 }
3057 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003058 if (Dependent() || SemaRef.CurContext->isDependentContext())
3059 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003060 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003061 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003062 return true;
3063}
3064
3065bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3066 // RHS of canonical loop form increment can be:
3067 // var + incr
3068 // incr + var
3069 // var - incr
3070 //
3071 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003072 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003073 if (BO->isAdditiveOp()) {
3074 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003075 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003076 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003077 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003078 return SetStep(BO->getLHS(), false);
3079 }
David Majnemer9d168222016-08-05 17:44:54 +00003080 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003081 bool IsAdd = CE->getOperator() == OO_Plus;
3082 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003083 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003084 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003085 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003086 return SetStep(CE->getArg(0), false);
3087 }
3088 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003089 if (Dependent() || SemaRef.CurContext->isDependentContext())
3090 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003092 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003093 return true;
3094}
3095
3096bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3097 // Check incr-expr for canonical loop form and return true if it
3098 // does not conform.
3099 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3100 // ++var
3101 // var++
3102 // --var
3103 // var--
3104 // var += incr
3105 // var -= incr
3106 // var = var + incr
3107 // var = incr + var
3108 // var = var - incr
3109 //
3110 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003111 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003112 return true;
3113 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003114 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3115 if (!ExprTemp->cleanupsHaveSideEffects())
3116 S = ExprTemp->getSubExpr();
3117
Alexander Musmana5f070a2014-10-01 06:03:56 +00003118 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003119 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003120 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003121 if (UO->isIncrementDecrementOp() &&
3122 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003123 return SetStep(SemaRef
3124 .ActOnIntegerConstant(UO->getLocStart(),
3125 (UO->isDecrementOp() ? -1 : 1))
3126 .get(),
3127 false);
3128 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 switch (BO->getOpcode()) {
3130 case BO_AddAssign:
3131 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003132 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003133 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3134 break;
3135 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003136 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003137 return CheckIncRHS(BO->getRHS());
3138 break;
3139 default:
3140 break;
3141 }
David Majnemer9d168222016-08-05 17:44:54 +00003142 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003143 switch (CE->getOperator()) {
3144 case OO_PlusPlus:
3145 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003146 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003147 return SetStep(SemaRef
3148 .ActOnIntegerConstant(
3149 CE->getLocStart(),
3150 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3151 .get(),
3152 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003153 break;
3154 case OO_PlusEqual:
3155 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003156 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003157 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3158 break;
3159 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003160 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003161 return CheckIncRHS(CE->getArg(1));
3162 break;
3163 default:
3164 break;
3165 }
3166 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003167 if (Dependent() || SemaRef.CurContext->isDependentContext())
3168 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003169 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003170 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003171 return true;
3172}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003173
Alexey Bataev5a3af132016-03-29 08:58:54 +00003174static ExprResult
3175tryBuildCapture(Sema &SemaRef, Expr *Capture,
3176 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003177 if (SemaRef.CurContext->isDependentContext())
3178 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003179 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3180 return SemaRef.PerformImplicitConversion(
3181 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3182 /*AllowExplicit=*/true);
3183 auto I = Captures.find(Capture);
3184 if (I != Captures.end())
3185 return buildCapture(SemaRef, Capture, I->second);
3186 DeclRefExpr *Ref = nullptr;
3187 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3188 Captures[Capture] = Ref;
3189 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003190}
3191
Alexander Musmana5f070a2014-10-01 06:03:56 +00003192/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003193Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3194 Scope *S, const bool LimitedType,
3195 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003196 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003197 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003198 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003199 SemaRef.getLangOpts().CPlusPlus) {
3200 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003201 auto *UBExpr = TestIsLessOp ? UB : LB;
3202 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003203 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3204 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003205 if (!Upper || !Lower)
3206 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003207
3208 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3209
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003210 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003211 // BuildBinOp already emitted error, this one is to point user to upper
3212 // and lower bound, and to tell what is passed to 'operator-'.
3213 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3214 << Upper->getSourceRange() << Lower->getSourceRange();
3215 return nullptr;
3216 }
3217 }
3218
3219 if (!Diff.isUsable())
3220 return nullptr;
3221
3222 // Upper - Lower [- 1]
3223 if (TestIsStrictOp)
3224 Diff = SemaRef.BuildBinOp(
3225 S, DefaultLoc, BO_Sub, Diff.get(),
3226 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3227 if (!Diff.isUsable())
3228 return nullptr;
3229
3230 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003231 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3232 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003233 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003234 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003235 if (!Diff.isUsable())
3236 return nullptr;
3237
3238 // Parentheses (for dumping/debugging purposes only).
3239 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3240 if (!Diff.isUsable())
3241 return nullptr;
3242
3243 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003244 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003245 if (!Diff.isUsable())
3246 return nullptr;
3247
Alexander Musman174b3ca2014-10-06 11:16:29 +00003248 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003249 QualType Type = Diff.get()->getType();
3250 auto &C = SemaRef.Context;
3251 bool UseVarType = VarType->hasIntegerRepresentation() &&
3252 C.getTypeSize(Type) > C.getTypeSize(VarType);
3253 if (!Type->isIntegerType() || UseVarType) {
3254 unsigned NewSize =
3255 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3256 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3257 : Type->hasSignedIntegerRepresentation();
3258 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003259 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3260 Diff = SemaRef.PerformImplicitConversion(
3261 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3262 if (!Diff.isUsable())
3263 return nullptr;
3264 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003265 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003266 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003267 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3268 if (NewSize != C.getTypeSize(Type)) {
3269 if (NewSize < C.getTypeSize(Type)) {
3270 assert(NewSize == 64 && "incorrect loop var size");
3271 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3272 << InitSrcRange << ConditionSrcRange;
3273 }
3274 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003275 NewSize, Type->hasSignedIntegerRepresentation() ||
3276 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003277 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3278 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3279 Sema::AA_Converting, true);
3280 if (!Diff.isUsable())
3281 return nullptr;
3282 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003283 }
3284 }
3285
Alexander Musmana5f070a2014-10-01 06:03:56 +00003286 return Diff.get();
3287}
3288
Alexey Bataev5a3af132016-03-29 08:58:54 +00003289Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3290 Scope *S, Expr *Cond,
3291 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003292 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3293 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3294 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003295
Alexey Bataev5a3af132016-03-29 08:58:54 +00003296 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3297 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3298 if (!NewLB.isUsable() || !NewUB.isUsable())
3299 return nullptr;
3300
Alexey Bataev62dbb972015-04-22 11:59:37 +00003301 auto CondExpr = SemaRef.BuildBinOp(
3302 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3303 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003304 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003305 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003306 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3307 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003308 CondExpr = SemaRef.PerformImplicitConversion(
3309 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3310 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003311 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003312 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3313 // Otherwise use original loop conditon and evaluate it in runtime.
3314 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3315}
3316
Alexander Musmana5f070a2014-10-01 06:03:56 +00003317/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003318DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003319 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003320 auto *VD = dyn_cast<VarDecl>(LCDecl);
3321 if (!VD) {
3322 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3323 auto *Ref = buildDeclRefExpr(
3324 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003325 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3326 // If the loop control decl is explicitly marked as private, do not mark it
3327 // as captured again.
3328 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3329 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003330 return Ref;
3331 }
3332 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003333 DefaultLoc);
3334}
3335
3336Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003337 if (LCDecl && !LCDecl->isInvalidDecl()) {
3338 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003339 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003340 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3341 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003342 if (PrivateVar->isInvalidDecl())
3343 return nullptr;
3344 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3345 }
3346 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003347}
3348
David Majnemer9d168222016-08-05 17:44:54 +00003349/// \brief Build instillation of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003350Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3351
3352/// \brief Build step of the counter be used for codegen.
3353Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3354
3355/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003356struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003357 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003358 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003359 /// \brief This expression calculates the number of iterations in the loop.
3360 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003361 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003362 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003363 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003364 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003365 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003366 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003367 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003368 /// \brief This is step for the #CounterVar used to generate its update:
3369 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003370 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003371 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003372 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003373 /// \brief Source range of the loop init.
3374 SourceRange InitSrcRange;
3375 /// \brief Source range of the loop condition.
3376 SourceRange CondSrcRange;
3377 /// \brief Source range of the loop increment.
3378 SourceRange IncSrcRange;
3379};
3380
Alexey Bataev23b69422014-06-18 07:08:49 +00003381} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003382
Alexey Bataev9c821032015-04-30 04:23:23 +00003383void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3384 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3385 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003386 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3387 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003388 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3389 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003390 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3391 if (auto *D = ISC.GetLoopDecl()) {
3392 auto *VD = dyn_cast<VarDecl>(D);
3393 if (!VD) {
3394 if (auto *Private = IsOpenMPCapturedDecl(D))
3395 VD = Private;
3396 else {
3397 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3398 /*WithInit=*/false);
3399 VD = cast<VarDecl>(Ref->getDecl());
3400 }
3401 }
3402 DSAStack->addLoopControlVariable(D, VD);
3403 }
3404 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003405 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003406 }
3407}
3408
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003409/// \brief Called on a for stmt to check and extract its iteration space
3410/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003411static bool CheckOpenMPIterationSpace(
3412 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3413 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003414 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003415 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003416 LoopIterationSpace &ResultIterSpace,
3417 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003418 // OpenMP [2.6, Canonical Loop Form]
3419 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003420 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003421 if (!For) {
3422 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003423 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3424 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3425 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3426 if (NestedLoopCount > 1) {
3427 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3428 SemaRef.Diag(DSA.getConstructLoc(),
3429 diag::note_omp_collapse_ordered_expr)
3430 << 2 << CollapseLoopCountExpr->getSourceRange()
3431 << OrderedLoopCountExpr->getSourceRange();
3432 else if (CollapseLoopCountExpr)
3433 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3434 diag::note_omp_collapse_ordered_expr)
3435 << 0 << CollapseLoopCountExpr->getSourceRange();
3436 else
3437 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3438 diag::note_omp_collapse_ordered_expr)
3439 << 1 << OrderedLoopCountExpr->getSourceRange();
3440 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003441 return true;
3442 }
3443 assert(For->getBody());
3444
3445 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3446
3447 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003448 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003449 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003450 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003451
3452 bool HasErrors = false;
3453
3454 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003455 if (auto *LCDecl = ISC.GetLoopDecl()) {
3456 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003457
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003458 // OpenMP [2.6, Canonical Loop Form]
3459 // Var is one of the following:
3460 // A variable of signed or unsigned integer type.
3461 // For C++, a variable of a random access iterator type.
3462 // For C, a variable of a pointer type.
3463 auto VarType = LCDecl->getType().getNonReferenceType();
3464 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3465 !VarType->isPointerType() &&
3466 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3467 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3468 << SemaRef.getLangOpts().CPlusPlus;
3469 HasErrors = true;
3470 }
3471
3472 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3473 // a Construct
3474 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3475 // parallel for construct is (are) private.
3476 // The loop iteration variable in the associated for-loop of a simd
3477 // construct with just one associated for-loop is linear with a
3478 // constant-linear-step that is the increment of the associated for-loop.
3479 // Exclude loop var from the list of variables with implicitly defined data
3480 // sharing attributes.
3481 VarsWithImplicitDSA.erase(LCDecl);
3482
3483 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3484 // in a Construct, C/C++].
3485 // The loop iteration variable in the associated for-loop of a simd
3486 // construct with just one associated for-loop may be listed in a linear
3487 // clause with a constant-linear-step that is the increment of the
3488 // associated for-loop.
3489 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3490 // parallel for construct may be listed in a private or lastprivate clause.
3491 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3492 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3493 // declared in the loop and it is predetermined as a private.
3494 auto PredeterminedCKind =
3495 isOpenMPSimdDirective(DKind)
3496 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3497 : OMPC_private;
3498 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3499 DVar.CKind != PredeterminedCKind) ||
3500 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3501 isOpenMPDistributeDirective(DKind)) &&
3502 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3503 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3504 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3505 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3506 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3507 << getOpenMPClauseName(PredeterminedCKind);
3508 if (DVar.RefExpr == nullptr)
3509 DVar.CKind = PredeterminedCKind;
3510 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3511 HasErrors = true;
3512 } else if (LoopDeclRefExpr != nullptr) {
3513 // Make the loop iteration variable private (for worksharing constructs),
3514 // linear (for simd directives with the only one associated loop) or
3515 // lastprivate (for simd directives with several collapsed or ordered
3516 // loops).
3517 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003518 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3519 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003520 /*FromParent=*/false);
3521 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3522 }
3523
3524 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3525
3526 // Check test-expr.
3527 HasErrors |= ISC.CheckCond(For->getCond());
3528
3529 // Check incr-expr.
3530 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003531 }
3532
Alexander Musmana5f070a2014-10-01 06:03:56 +00003533 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003534 return HasErrors;
3535
Alexander Musmana5f070a2014-10-01 06:03:56 +00003536 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003537 ResultIterSpace.PreCond =
3538 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003539 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003540 DSA.getCurScope(),
3541 (isOpenMPWorksharingDirective(DKind) ||
3542 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3543 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003544 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003545 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003546 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3547 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3548 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3549 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3550 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3551 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3552
Alexey Bataev62dbb972015-04-22 11:59:37 +00003553 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3554 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003555 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003556 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003557 ResultIterSpace.CounterInit == nullptr ||
3558 ResultIterSpace.CounterStep == nullptr);
3559
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003560 return HasErrors;
3561}
3562
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003563/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003564static ExprResult
3565BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3566 ExprResult Start,
3567 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003568 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003569 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3570 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003571 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003572 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003573 VarRef.get()->getType())) {
3574 NewStart = SemaRef.PerformImplicitConversion(
3575 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3576 /*AllowExplicit=*/true);
3577 if (!NewStart.isUsable())
3578 return ExprError();
3579 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003580
3581 auto Init =
3582 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3583 return Init;
3584}
3585
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003587static ExprResult
3588BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3589 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3590 ExprResult Step, bool Subtract,
3591 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003592 // Add parentheses (for debugging purposes only).
3593 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3594 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3595 !Step.isUsable())
3596 return ExprError();
3597
Alexey Bataev5a3af132016-03-29 08:58:54 +00003598 ExprResult NewStep = Step;
3599 if (Captures)
3600 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003601 if (NewStep.isInvalid())
3602 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003603 ExprResult Update =
3604 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003605 if (!Update.isUsable())
3606 return ExprError();
3607
Alexey Bataevc0214e02016-02-16 12:13:49 +00003608 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3609 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003610 ExprResult NewStart = Start;
3611 if (Captures)
3612 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003613 if (NewStart.isInvalid())
3614 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003615
Alexey Bataevc0214e02016-02-16 12:13:49 +00003616 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3617 ExprResult SavedUpdate = Update;
3618 ExprResult UpdateVal;
3619 if (VarRef.get()->getType()->isOverloadableType() ||
3620 NewStart.get()->getType()->isOverloadableType() ||
3621 Update.get()->getType()->isOverloadableType()) {
3622 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3623 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3624 Update =
3625 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3626 if (Update.isUsable()) {
3627 UpdateVal =
3628 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3629 VarRef.get(), SavedUpdate.get());
3630 if (UpdateVal.isUsable()) {
3631 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3632 UpdateVal.get());
3633 }
3634 }
3635 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3636 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003637
Alexey Bataevc0214e02016-02-16 12:13:49 +00003638 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3639 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3640 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3641 NewStart.get(), SavedUpdate.get());
3642 if (!Update.isUsable())
3643 return ExprError();
3644
Alexey Bataev11481f52016-02-17 10:29:05 +00003645 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3646 VarRef.get()->getType())) {
3647 Update = SemaRef.PerformImplicitConversion(
3648 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3649 if (!Update.isUsable())
3650 return ExprError();
3651 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003652
3653 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3654 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003655 return Update;
3656}
3657
3658/// \brief Convert integer expression \a E to make it have at least \a Bits
3659/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003660static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003661 if (E == nullptr)
3662 return ExprError();
3663 auto &C = SemaRef.Context;
3664 QualType OldType = E->getType();
3665 unsigned HasBits = C.getTypeSize(OldType);
3666 if (HasBits >= Bits)
3667 return ExprResult(E);
3668 // OK to convert to signed, because new type has more bits than old.
3669 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3670 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3671 true);
3672}
3673
3674/// \brief Check if the given expression \a E is a constant integer that fits
3675/// into \a Bits bits.
3676static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3677 if (E == nullptr)
3678 return false;
3679 llvm::APSInt Result;
3680 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3681 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3682 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003683}
3684
Alexey Bataev5a3af132016-03-29 08:58:54 +00003685/// Build preinits statement for the given declarations.
3686static Stmt *buildPreInits(ASTContext &Context,
3687 SmallVectorImpl<Decl *> &PreInits) {
3688 if (!PreInits.empty()) {
3689 return new (Context) DeclStmt(
3690 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3691 SourceLocation(), SourceLocation());
3692 }
3693 return nullptr;
3694}
3695
3696/// Build preinits statement for the given declarations.
3697static Stmt *buildPreInits(ASTContext &Context,
3698 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3699 if (!Captures.empty()) {
3700 SmallVector<Decl *, 16> PreInits;
3701 for (auto &Pair : Captures)
3702 PreInits.push_back(Pair.second->getDecl());
3703 return buildPreInits(Context, PreInits);
3704 }
3705 return nullptr;
3706}
3707
3708/// Build postupdate expression for the given list of postupdates expressions.
3709static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3710 Expr *PostUpdate = nullptr;
3711 if (!PostUpdates.empty()) {
3712 for (auto *E : PostUpdates) {
3713 Expr *ConvE = S.BuildCStyleCastExpr(
3714 E->getExprLoc(),
3715 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3716 E->getExprLoc(), E)
3717 .get();
3718 PostUpdate = PostUpdate
3719 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3720 PostUpdate, ConvE)
3721 .get()
3722 : ConvE;
3723 }
3724 }
3725 return PostUpdate;
3726}
3727
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003728/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003729/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3730/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003731static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003732CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3733 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3734 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003735 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003736 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003737 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003738 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003739 // Found 'collapse' clause - calculate collapse number.
3740 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003741 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003742 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003743 }
3744 if (OrderedLoopCountExpr) {
3745 // Found 'ordered' clause - calculate collapse number.
3746 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003747 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3748 if (Result.getLimitedValue() < NestedLoopCount) {
3749 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3750 diag::err_omp_wrong_ordered_loop_count)
3751 << OrderedLoopCountExpr->getSourceRange();
3752 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3753 diag::note_collapse_loop_count)
3754 << CollapseLoopCountExpr->getSourceRange();
3755 }
3756 NestedLoopCount = Result.getLimitedValue();
3757 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003758 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003759 // This is helper routine for loop directives (e.g., 'for', 'simd',
3760 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003761 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003762 SmallVector<LoopIterationSpace, 4> IterSpaces;
3763 IterSpaces.resize(NestedLoopCount);
3764 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003765 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003766 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003767 NestedLoopCount, CollapseLoopCountExpr,
3768 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003769 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003770 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003772 // OpenMP [2.8.1, simd construct, Restrictions]
3773 // All loops associated with the construct must be perfectly nested; that
3774 // is, there must be no intervening code nor any OpenMP directive between
3775 // any two loops.
3776 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 }
3778
Alexander Musmana5f070a2014-10-01 06:03:56 +00003779 Built.clear(/* size */ NestedLoopCount);
3780
3781 if (SemaRef.CurContext->isDependentContext())
3782 return NestedLoopCount;
3783
3784 // An example of what is generated for the following code:
3785 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003786 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003787 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003788 // for (k = 0; k < NK; ++k)
3789 // for (j = J0; j < NJ; j+=2) {
3790 // <loop body>
3791 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003792 //
3793 // We generate the code below.
3794 // Note: the loop body may be outlined in CodeGen.
3795 // Note: some counters may be C++ classes, operator- is used to find number of
3796 // iterations and operator+= to calculate counter value.
3797 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3798 // or i64 is currently supported).
3799 //
3800 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3801 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3802 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3803 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3804 // // similar updates for vars in clauses (e.g. 'linear')
3805 // <loop body (using local i and j)>
3806 // }
3807 // i = NI; // assign final values of counters
3808 // j = NJ;
3809 //
3810
3811 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3812 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003813 // Precondition tests if there is at least one iteration (all conditions are
3814 // true).
3815 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003816 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003817 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003818 32 /* Bits */, SemaRef
3819 .PerformImplicitConversion(
3820 N0->IgnoreImpCasts(), N0->getType(),
3821 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003822 .get(),
3823 SemaRef);
3824 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003825 64 /* Bits */, SemaRef
3826 .PerformImplicitConversion(
3827 N0->IgnoreImpCasts(), N0->getType(),
3828 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003829 .get(),
3830 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003831
3832 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3833 return NestedLoopCount;
3834
3835 auto &C = SemaRef.Context;
3836 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3837
3838 Scope *CurScope = DSA.getCurScope();
3839 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003840 if (PreCond.isUsable()) {
3841 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3842 PreCond.get(), IterSpaces[Cnt].PreCond);
3843 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003844 auto N = IterSpaces[Cnt].NumIterations;
3845 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3846 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003847 LastIteration32 = SemaRef.BuildBinOp(
3848 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003849 SemaRef
3850 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3851 Sema::AA_Converting,
3852 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003853 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003854 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003855 LastIteration64 = SemaRef.BuildBinOp(
3856 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003857 SemaRef
3858 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3859 Sema::AA_Converting,
3860 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003861 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003862 }
3863
3864 // Choose either the 32-bit or 64-bit version.
3865 ExprResult LastIteration = LastIteration64;
3866 if (LastIteration32.isUsable() &&
3867 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3868 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3869 FitsInto(
3870 32 /* Bits */,
3871 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3872 LastIteration64.get(), SemaRef)))
3873 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003874 QualType VType = LastIteration.get()->getType();
3875 QualType RealVType = VType;
3876 QualType StrideVType = VType;
3877 if (isOpenMPTaskLoopDirective(DKind)) {
3878 VType =
3879 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3880 StrideVType =
3881 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3882 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003883
3884 if (!LastIteration.isUsable())
3885 return 0;
3886
3887 // Save the number of iterations.
3888 ExprResult NumIterations = LastIteration;
3889 {
3890 LastIteration = SemaRef.BuildBinOp(
3891 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3892 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3893 if (!LastIteration.isUsable())
3894 return 0;
3895 }
3896
3897 // Calculate the last iteration number beforehand instead of doing this on
3898 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3899 llvm::APSInt Result;
3900 bool IsConstant =
3901 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3902 ExprResult CalcLastIteration;
3903 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003904 ExprResult SaveRef =
3905 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003906 LastIteration = SaveRef;
3907
3908 // Prepare SaveRef + 1.
3909 NumIterations = SemaRef.BuildBinOp(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003910 CurScope, SourceLocation(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003911 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3912 if (!NumIterations.isUsable())
3913 return 0;
3914 }
3915
3916 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3917
David Majnemer9d168222016-08-05 17:44:54 +00003918 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003919 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003920 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3921 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003922 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003923 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3924 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003925 SemaRef.AddInitializerToDecl(
3926 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3927 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3928
3929 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003930 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3931 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003932 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3933 /*DirectInit*/ false,
3934 /*TypeMayContainAuto*/ false);
3935
3936 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3937 // This will be used to implement clause 'lastprivate'.
3938 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003939 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3940 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003941 SemaRef.AddInitializerToDecl(
3942 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3943 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3944
3945 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00003946 VarDecl *STDecl =
3947 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3948 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003949 SemaRef.AddInitializerToDecl(
3950 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3951 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3952
3953 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00003954 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00003955 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3956 UB.get(), LastIteration.get());
3957 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3958 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3959 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3960 CondOp.get());
3961 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00003962
3963 // If we have a combined directive that combines 'distribute', 'for' or
3964 // 'simd' we need to be able to access the bounds of the schedule of the
3965 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
3966 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
3967 if (isOpenMPLoopBoundSharingDirective(DKind)) {
3968 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
3969
3970 // We expect to have at least 2 more parameters than the 'parallel'
3971 // directive does - the lower and upper bounds of the previous schedule.
3972 assert(CD->getNumParams() >= 4 &&
3973 "Unexpected number of parameters in loop combined directive");
3974
3975 // Set the proper type for the bounds given what we learned from the
3976 // enclosed loops.
3977 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
3978 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
3979
3980 // Previous lower and upper bounds are obtained from the region
3981 // parameters.
3982 PrevLB =
3983 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
3984 PrevUB =
3985 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
3986 }
Alexander Musmanc6388682014-12-15 07:07:06 +00003987 }
3988
3989 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003990 ExprResult IV;
3991 ExprResult Init;
3992 {
Alexey Bataev7292c292016-04-25 12:22:29 +00003993 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
3994 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00003995 Expr *RHS =
3996 (isOpenMPWorksharingDirective(DKind) ||
3997 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
3998 ? LB.get()
3999 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004000 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4001 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004002 }
4003
Alexander Musmanc6388682014-12-15 07:07:06 +00004004 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004005 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004006 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004007 (isOpenMPWorksharingDirective(DKind) ||
4008 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004009 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4010 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4011 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004012
4013 // Loop increment (IV = IV + 1)
4014 SourceLocation IncLoc;
4015 ExprResult Inc =
4016 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4017 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4018 if (!Inc.isUsable())
4019 return 0;
4020 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004021 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4022 if (!Inc.isUsable())
4023 return 0;
4024
4025 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4026 // Used for directives with static scheduling.
4027 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004028 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4029 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004030 // LB + ST
4031 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4032 if (!NextLB.isUsable())
4033 return 0;
4034 // LB = LB + ST
4035 NextLB =
4036 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4037 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4038 if (!NextLB.isUsable())
4039 return 0;
4040 // UB + ST
4041 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4042 if (!NextUB.isUsable())
4043 return 0;
4044 // UB = UB + ST
4045 NextUB =
4046 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4047 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4048 if (!NextUB.isUsable())
4049 return 0;
4050 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004051
4052 // Build updates and final values of the loop counters.
4053 bool HasErrors = false;
4054 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004055 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004056 Built.Updates.resize(NestedLoopCount);
4057 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004058 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004059 {
4060 ExprResult Div;
4061 // Go from inner nested loop to outer.
4062 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4063 LoopIterationSpace &IS = IterSpaces[Cnt];
4064 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4065 // Build: Iter = (IV / Div) % IS.NumIters
4066 // where Div is product of previous iterations' IS.NumIters.
4067 ExprResult Iter;
4068 if (Div.isUsable()) {
4069 Iter =
4070 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4071 } else {
4072 Iter = IV;
4073 assert((Cnt == (int)NestedLoopCount - 1) &&
4074 "unusable div expected on first iteration only");
4075 }
4076
4077 if (Cnt != 0 && Iter.isUsable())
4078 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4079 IS.NumIterations);
4080 if (!Iter.isUsable()) {
4081 HasErrors = true;
4082 break;
4083 }
4084
Alexey Bataev39f915b82015-05-08 10:41:21 +00004085 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004086 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4087 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4088 IS.CounterVar->getExprLoc(),
4089 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004090 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004091 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004092 if (!Init.isUsable()) {
4093 HasErrors = true;
4094 break;
4095 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004096 ExprResult Update = BuildCounterUpdate(
4097 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4098 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004099 if (!Update.isUsable()) {
4100 HasErrors = true;
4101 break;
4102 }
4103
4104 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4105 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004106 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004107 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004108 if (!Final.isUsable()) {
4109 HasErrors = true;
4110 break;
4111 }
4112
4113 // Build Div for the next iteration: Div <- Div * IS.NumIters
4114 if (Cnt != 0) {
4115 if (Div.isUnset())
4116 Div = IS.NumIterations;
4117 else
4118 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4119 IS.NumIterations);
4120
4121 // Add parentheses (for debugging purposes only).
4122 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004123 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004124 if (!Div.isUsable()) {
4125 HasErrors = true;
4126 break;
4127 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004128 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004129 }
4130 if (!Update.isUsable() || !Final.isUsable()) {
4131 HasErrors = true;
4132 break;
4133 }
4134 // Save results
4135 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004136 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004137 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004138 Built.Updates[Cnt] = Update.get();
4139 Built.Finals[Cnt] = Final.get();
4140 }
4141 }
4142
4143 if (HasErrors)
4144 return 0;
4145
4146 // Save results
4147 Built.IterationVarRef = IV.get();
4148 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004149 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004150 Built.CalcLastIteration =
4151 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004152 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004153 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004154 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004155 Built.Init = Init.get();
4156 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004157 Built.LB = LB.get();
4158 Built.UB = UB.get();
4159 Built.IL = IL.get();
4160 Built.ST = ST.get();
4161 Built.EUB = EUB.get();
4162 Built.NLB = NextLB.get();
4163 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004164 Built.PrevLB = PrevLB.get();
4165 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004166
Alexey Bataev8b427062016-05-25 12:36:08 +00004167 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4168 // Fill data for doacross depend clauses.
4169 for (auto Pair : DSA.getDoacrossDependClauses()) {
4170 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4171 Pair.first->setCounterValue(CounterVal);
4172 else {
4173 if (NestedLoopCount != Pair.second.size() ||
4174 NestedLoopCount != LoopMultipliers.size() + 1) {
4175 // Erroneous case - clause has some problems.
4176 Pair.first->setCounterValue(CounterVal);
4177 continue;
4178 }
4179 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4180 auto I = Pair.second.rbegin();
4181 auto IS = IterSpaces.rbegin();
4182 auto ILM = LoopMultipliers.rbegin();
4183 Expr *UpCounterVal = CounterVal;
4184 Expr *Multiplier = nullptr;
4185 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4186 if (I->first) {
4187 assert(IS->CounterStep);
4188 Expr *NormalizedOffset =
4189 SemaRef
4190 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4191 I->first, IS->CounterStep)
4192 .get();
4193 if (Multiplier) {
4194 NormalizedOffset =
4195 SemaRef
4196 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4197 NormalizedOffset, Multiplier)
4198 .get();
4199 }
4200 assert(I->second == OO_Plus || I->second == OO_Minus);
4201 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004202 UpCounterVal = SemaRef
4203 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4204 UpCounterVal, NormalizedOffset)
4205 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004206 }
4207 Multiplier = *ILM;
4208 ++I;
4209 ++IS;
4210 ++ILM;
4211 }
4212 Pair.first->setCounterValue(UpCounterVal);
4213 }
4214 }
4215
Alexey Bataevabfc0692014-06-25 06:52:00 +00004216 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004217}
4218
Alexey Bataev10e775f2015-07-30 11:36:16 +00004219static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004220 auto CollapseClauses =
4221 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4222 if (CollapseClauses.begin() != CollapseClauses.end())
4223 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004224 return nullptr;
4225}
4226
Alexey Bataev10e775f2015-07-30 11:36:16 +00004227static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004228 auto OrderedClauses =
4229 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4230 if (OrderedClauses.begin() != OrderedClauses.end())
4231 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004232 return nullptr;
4233}
4234
Kelvin Lic5609492016-07-15 04:39:07 +00004235static bool checkSimdlenSafelenSpecified(Sema &S,
4236 const ArrayRef<OMPClause *> Clauses) {
4237 OMPSafelenClause *Safelen = nullptr;
4238 OMPSimdlenClause *Simdlen = nullptr;
4239
4240 for (auto *Clause : Clauses) {
4241 if (Clause->getClauseKind() == OMPC_safelen)
4242 Safelen = cast<OMPSafelenClause>(Clause);
4243 else if (Clause->getClauseKind() == OMPC_simdlen)
4244 Simdlen = cast<OMPSimdlenClause>(Clause);
4245 if (Safelen && Simdlen)
4246 break;
4247 }
4248
4249 if (Simdlen && Safelen) {
4250 llvm::APSInt SimdlenRes, SafelenRes;
4251 auto SimdlenLength = Simdlen->getSimdlen();
4252 auto SafelenLength = Safelen->getSafelen();
4253 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4254 SimdlenLength->isInstantiationDependent() ||
4255 SimdlenLength->containsUnexpandedParameterPack())
4256 return false;
4257 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4258 SafelenLength->isInstantiationDependent() ||
4259 SafelenLength->containsUnexpandedParameterPack())
4260 return false;
4261 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4262 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4263 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4264 // If both simdlen and safelen clauses are specified, the value of the
4265 // simdlen parameter must be less than or equal to the value of the safelen
4266 // parameter.
4267 if (SimdlenRes > SafelenRes) {
4268 S.Diag(SimdlenLength->getExprLoc(),
4269 diag::err_omp_wrong_simdlen_safelen_values)
4270 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4271 return true;
4272 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004273 }
4274 return false;
4275}
4276
Alexey Bataev4acb8592014-07-07 13:01:15 +00004277StmtResult Sema::ActOnOpenMPSimdDirective(
4278 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4279 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004280 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004281 if (!AStmt)
4282 return StmtError();
4283
4284 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004285 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004286 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4287 // define the nested loops number.
4288 unsigned NestedLoopCount = CheckOpenMPLoop(
4289 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4290 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004291 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004292 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004293
Alexander Musmana5f070a2014-10-01 06:03:56 +00004294 assert((CurContext->isDependentContext() || B.builtAll()) &&
4295 "omp simd loop exprs were not built");
4296
Alexander Musman3276a272015-03-21 10:12:56 +00004297 if (!CurContext->isDependentContext()) {
4298 // Finalize the clauses that need pre-built expressions for CodeGen.
4299 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004300 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004301 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004302 B.NumIterations, *this, CurScope,
4303 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004304 return StmtError();
4305 }
4306 }
4307
Kelvin Lic5609492016-07-15 04:39:07 +00004308 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004309 return StmtError();
4310
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004311 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004312 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4313 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004314}
4315
Alexey Bataev4acb8592014-07-07 13:01:15 +00004316StmtResult Sema::ActOnOpenMPForDirective(
4317 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4318 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004319 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004320 if (!AStmt)
4321 return StmtError();
4322
4323 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004324 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004325 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4326 // define the nested loops number.
4327 unsigned NestedLoopCount = CheckOpenMPLoop(
4328 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4329 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004330 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004331 return StmtError();
4332
Alexander Musmana5f070a2014-10-01 06:03:56 +00004333 assert((CurContext->isDependentContext() || B.builtAll()) &&
4334 "omp for loop exprs were not built");
4335
Alexey Bataev54acd402015-08-04 11:18:19 +00004336 if (!CurContext->isDependentContext()) {
4337 // Finalize the clauses that need pre-built expressions for CodeGen.
4338 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004339 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004340 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004341 B.NumIterations, *this, CurScope,
4342 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004343 return StmtError();
4344 }
4345 }
4346
Alexey Bataevf29276e2014-06-18 04:14:57 +00004347 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004348 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004349 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004350}
4351
Alexander Musmanf82886e2014-09-18 05:12:34 +00004352StmtResult Sema::ActOnOpenMPForSimdDirective(
4353 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4354 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004355 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004356 if (!AStmt)
4357 return StmtError();
4358
4359 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004360 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004361 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4362 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004363 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004364 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4365 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4366 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004367 if (NestedLoopCount == 0)
4368 return StmtError();
4369
Alexander Musmanc6388682014-12-15 07:07:06 +00004370 assert((CurContext->isDependentContext() || B.builtAll()) &&
4371 "omp for simd loop exprs were not built");
4372
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004373 if (!CurContext->isDependentContext()) {
4374 // Finalize the clauses that need pre-built expressions for CodeGen.
4375 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004376 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004377 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004378 B.NumIterations, *this, CurScope,
4379 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004380 return StmtError();
4381 }
4382 }
4383
Kelvin Lic5609492016-07-15 04:39:07 +00004384 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004385 return StmtError();
4386
Alexander Musmanf82886e2014-09-18 05:12:34 +00004387 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004388 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4389 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004390}
4391
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004392StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4393 Stmt *AStmt,
4394 SourceLocation StartLoc,
4395 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004396 if (!AStmt)
4397 return StmtError();
4398
4399 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004400 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004401 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004402 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004403 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004404 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004405 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004406 return StmtError();
4407 // All associated statements must be '#pragma omp section' except for
4408 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004409 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004410 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4411 if (SectionStmt)
4412 Diag(SectionStmt->getLocStart(),
4413 diag::err_omp_sections_substmt_not_section);
4414 return StmtError();
4415 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004416 cast<OMPSectionDirective>(SectionStmt)
4417 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004418 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004419 } else {
4420 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4421 return StmtError();
4422 }
4423
4424 getCurFunction()->setHasBranchProtectedScope();
4425
Alexey Bataev25e5b442015-09-15 12:52:43 +00004426 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4427 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004428}
4429
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004430StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4431 SourceLocation StartLoc,
4432 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004433 if (!AStmt)
4434 return StmtError();
4435
4436 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004437
4438 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004439 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004440
Alexey Bataev25e5b442015-09-15 12:52:43 +00004441 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4442 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004443}
4444
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004445StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4446 Stmt *AStmt,
4447 SourceLocation StartLoc,
4448 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004449 if (!AStmt)
4450 return StmtError();
4451
4452 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004453
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004454 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004455
Alexey Bataev3255bf32015-01-19 05:20:46 +00004456 // OpenMP [2.7.3, single Construct, Restrictions]
4457 // The copyprivate clause must not be used with the nowait clause.
4458 OMPClause *Nowait = nullptr;
4459 OMPClause *Copyprivate = nullptr;
4460 for (auto *Clause : Clauses) {
4461 if (Clause->getClauseKind() == OMPC_nowait)
4462 Nowait = Clause;
4463 else if (Clause->getClauseKind() == OMPC_copyprivate)
4464 Copyprivate = Clause;
4465 if (Copyprivate && Nowait) {
4466 Diag(Copyprivate->getLocStart(),
4467 diag::err_omp_single_copyprivate_with_nowait);
4468 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4469 return StmtError();
4470 }
4471 }
4472
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004473 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4474}
4475
Alexander Musman80c22892014-07-17 08:54:58 +00004476StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4477 SourceLocation StartLoc,
4478 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004479 if (!AStmt)
4480 return StmtError();
4481
4482 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004483
4484 getCurFunction()->setHasBranchProtectedScope();
4485
4486 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4487}
4488
Alexey Bataev28c75412015-12-15 08:19:24 +00004489StmtResult Sema::ActOnOpenMPCriticalDirective(
4490 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4491 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004492 if (!AStmt)
4493 return StmtError();
4494
4495 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004496
Alexey Bataev28c75412015-12-15 08:19:24 +00004497 bool ErrorFound = false;
4498 llvm::APSInt Hint;
4499 SourceLocation HintLoc;
4500 bool DependentHint = false;
4501 for (auto *C : Clauses) {
4502 if (C->getClauseKind() == OMPC_hint) {
4503 if (!DirName.getName()) {
4504 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4505 ErrorFound = true;
4506 }
4507 Expr *E = cast<OMPHintClause>(C)->getHint();
4508 if (E->isTypeDependent() || E->isValueDependent() ||
4509 E->isInstantiationDependent())
4510 DependentHint = true;
4511 else {
4512 Hint = E->EvaluateKnownConstInt(Context);
4513 HintLoc = C->getLocStart();
4514 }
4515 }
4516 }
4517 if (ErrorFound)
4518 return StmtError();
4519 auto Pair = DSAStack->getCriticalWithHint(DirName);
4520 if (Pair.first && DirName.getName() && !DependentHint) {
4521 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4522 Diag(StartLoc, diag::err_omp_critical_with_hint);
4523 if (HintLoc.isValid()) {
4524 Diag(HintLoc, diag::note_omp_critical_hint_here)
4525 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4526 } else
4527 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4528 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4529 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4530 << 1
4531 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4532 /*Radix=*/10, /*Signed=*/false);
4533 } else
4534 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4535 }
4536 }
4537
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004538 getCurFunction()->setHasBranchProtectedScope();
4539
Alexey Bataev28c75412015-12-15 08:19:24 +00004540 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4541 Clauses, AStmt);
4542 if (!Pair.first && DirName.getName() && !DependentHint)
4543 DSAStack->addCriticalWithHint(Dir, Hint);
4544 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004545}
4546
Alexey Bataev4acb8592014-07-07 13:01:15 +00004547StmtResult Sema::ActOnOpenMPParallelForDirective(
4548 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4549 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004550 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004551 if (!AStmt)
4552 return StmtError();
4553
Alexey Bataev4acb8592014-07-07 13:01:15 +00004554 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4555 // 1.2.2 OpenMP Language Terminology
4556 // Structured block - An executable statement with a single entry at the
4557 // top and a single exit at the bottom.
4558 // The point of exit cannot be a branch out of the structured block.
4559 // longjmp() and throw() must not violate the entry/exit criteria.
4560 CS->getCapturedDecl()->setNothrow();
4561
Alexander Musmanc6388682014-12-15 07:07:06 +00004562 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004563 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4564 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004565 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004566 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4567 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4568 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004569 if (NestedLoopCount == 0)
4570 return StmtError();
4571
Alexander Musmana5f070a2014-10-01 06:03:56 +00004572 assert((CurContext->isDependentContext() || B.builtAll()) &&
4573 "omp parallel for loop exprs were not built");
4574
Alexey Bataev54acd402015-08-04 11:18:19 +00004575 if (!CurContext->isDependentContext()) {
4576 // Finalize the clauses that need pre-built expressions for CodeGen.
4577 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004578 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004579 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004580 B.NumIterations, *this, CurScope,
4581 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004582 return StmtError();
4583 }
4584 }
4585
Alexey Bataev4acb8592014-07-07 13:01:15 +00004586 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004587 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004588 NestedLoopCount, Clauses, AStmt, B,
4589 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004590}
4591
Alexander Musmane4e893b2014-09-23 09:33:00 +00004592StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4593 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4594 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004595 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004596 if (!AStmt)
4597 return StmtError();
4598
Alexander Musmane4e893b2014-09-23 09:33:00 +00004599 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4600 // 1.2.2 OpenMP Language Terminology
4601 // Structured block - An executable statement with a single entry at the
4602 // top and a single exit at the bottom.
4603 // The point of exit cannot be a branch out of the structured block.
4604 // longjmp() and throw() must not violate the entry/exit criteria.
4605 CS->getCapturedDecl()->setNothrow();
4606
Alexander Musmanc6388682014-12-15 07:07:06 +00004607 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004608 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4609 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004610 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004611 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4612 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4613 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004614 if (NestedLoopCount == 0)
4615 return StmtError();
4616
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004617 if (!CurContext->isDependentContext()) {
4618 // Finalize the clauses that need pre-built expressions for CodeGen.
4619 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004620 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004621 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004622 B.NumIterations, *this, CurScope,
4623 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004624 return StmtError();
4625 }
4626 }
4627
Kelvin Lic5609492016-07-15 04:39:07 +00004628 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004629 return StmtError();
4630
Alexander Musmane4e893b2014-09-23 09:33:00 +00004631 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004632 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004633 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004634}
4635
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004636StmtResult
4637Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4638 Stmt *AStmt, SourceLocation StartLoc,
4639 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004640 if (!AStmt)
4641 return StmtError();
4642
4643 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004644 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004645 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004646 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004647 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004648 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004649 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004650 return StmtError();
4651 // All associated statements must be '#pragma omp section' except for
4652 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004653 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004654 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4655 if (SectionStmt)
4656 Diag(SectionStmt->getLocStart(),
4657 diag::err_omp_parallel_sections_substmt_not_section);
4658 return StmtError();
4659 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004660 cast<OMPSectionDirective>(SectionStmt)
4661 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004662 }
4663 } else {
4664 Diag(AStmt->getLocStart(),
4665 diag::err_omp_parallel_sections_not_compound_stmt);
4666 return StmtError();
4667 }
4668
4669 getCurFunction()->setHasBranchProtectedScope();
4670
Alexey Bataev25e5b442015-09-15 12:52:43 +00004671 return OMPParallelSectionsDirective::Create(
4672 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004673}
4674
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004675StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4676 Stmt *AStmt, SourceLocation StartLoc,
4677 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004678 if (!AStmt)
4679 return StmtError();
4680
David Majnemer9d168222016-08-05 17:44:54 +00004681 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004682 // 1.2.2 OpenMP Language Terminology
4683 // Structured block - An executable statement with a single entry at the
4684 // top and a single exit at the bottom.
4685 // The point of exit cannot be a branch out of the structured block.
4686 // longjmp() and throw() must not violate the entry/exit criteria.
4687 CS->getCapturedDecl()->setNothrow();
4688
4689 getCurFunction()->setHasBranchProtectedScope();
4690
Alexey Bataev25e5b442015-09-15 12:52:43 +00004691 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4692 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004693}
4694
Alexey Bataev68446b72014-07-18 07:47:19 +00004695StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4696 SourceLocation EndLoc) {
4697 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4698}
4699
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004700StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4701 SourceLocation EndLoc) {
4702 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4703}
4704
Alexey Bataev2df347a2014-07-18 10:17:07 +00004705StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4706 SourceLocation EndLoc) {
4707 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4708}
4709
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004710StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4711 SourceLocation StartLoc,
4712 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004713 if (!AStmt)
4714 return StmtError();
4715
4716 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004717
4718 getCurFunction()->setHasBranchProtectedScope();
4719
4720 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4721}
4722
Alexey Bataev6125da92014-07-21 11:26:11 +00004723StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4724 SourceLocation StartLoc,
4725 SourceLocation EndLoc) {
4726 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4727 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4728}
4729
Alexey Bataev346265e2015-09-25 10:37:12 +00004730StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4731 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004732 SourceLocation StartLoc,
4733 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004734 OMPClause *DependFound = nullptr;
4735 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004736 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004737 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004738 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004739 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004740 for (auto *C : Clauses) {
4741 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4742 DependFound = C;
4743 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4744 if (DependSourceClause) {
4745 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4746 << getOpenMPDirectiveName(OMPD_ordered)
4747 << getOpenMPClauseName(OMPC_depend) << 2;
4748 ErrorFound = true;
4749 } else
4750 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004751 if (DependSinkClause) {
4752 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4753 << 0;
4754 ErrorFound = true;
4755 }
4756 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4757 if (DependSourceClause) {
4758 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4759 << 1;
4760 ErrorFound = true;
4761 }
4762 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004763 }
4764 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004765 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004766 else if (C->getClauseKind() == OMPC_simd)
4767 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004768 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004769 if (!ErrorFound && !SC &&
4770 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004771 // OpenMP [2.8.1,simd Construct, Restrictions]
4772 // An ordered construct with the simd clause is the only OpenMP construct
4773 // that can appear in the simd region.
4774 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004775 ErrorFound = true;
4776 } else if (DependFound && (TC || SC)) {
4777 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4778 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4779 ErrorFound = true;
4780 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4781 Diag(DependFound->getLocStart(),
4782 diag::err_omp_ordered_directive_without_param);
4783 ErrorFound = true;
4784 } else if (TC || Clauses.empty()) {
4785 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4786 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4787 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4788 << (TC != nullptr);
4789 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4790 ErrorFound = true;
4791 }
4792 }
4793 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004794 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004795
4796 if (AStmt) {
4797 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4798
4799 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004800 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004801
4802 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004803}
4804
Alexey Bataev1d160b12015-03-13 12:27:31 +00004805namespace {
4806/// \brief Helper class for checking expression in 'omp atomic [update]'
4807/// construct.
4808class OpenMPAtomicUpdateChecker {
4809 /// \brief Error results for atomic update expressions.
4810 enum ExprAnalysisErrorCode {
4811 /// \brief A statement is not an expression statement.
4812 NotAnExpression,
4813 /// \brief Expression is not builtin binary or unary operation.
4814 NotABinaryOrUnaryExpression,
4815 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4816 NotAnUnaryIncDecExpression,
4817 /// \brief An expression is not of scalar type.
4818 NotAScalarType,
4819 /// \brief A binary operation is not an assignment operation.
4820 NotAnAssignmentOp,
4821 /// \brief RHS part of the binary operation is not a binary expression.
4822 NotABinaryExpression,
4823 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4824 /// expression.
4825 NotABinaryOperator,
4826 /// \brief RHS binary operation does not have reference to the updated LHS
4827 /// part.
4828 NotAnUpdateExpression,
4829 /// \brief No errors is found.
4830 NoError
4831 };
4832 /// \brief Reference to Sema.
4833 Sema &SemaRef;
4834 /// \brief A location for note diagnostics (when error is found).
4835 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004836 /// \brief 'x' lvalue part of the source atomic expression.
4837 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004838 /// \brief 'expr' rvalue part of the source atomic expression.
4839 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004840 /// \brief Helper expression of the form
4841 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4842 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4843 Expr *UpdateExpr;
4844 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4845 /// important for non-associative operations.
4846 bool IsXLHSInRHSPart;
4847 BinaryOperatorKind Op;
4848 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004849 /// \brief true if the source expression is a postfix unary operation, false
4850 /// if it is a prefix unary operation.
4851 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004852
4853public:
4854 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004855 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004856 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004857 /// \brief Check specified statement that it is suitable for 'atomic update'
4858 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004859 /// expression. If DiagId and NoteId == 0, then only check is performed
4860 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004861 /// \param DiagId Diagnostic which should be emitted if error is found.
4862 /// \param NoteId Diagnostic note for the main error message.
4863 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004864 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004865 /// \brief Return the 'x' lvalue part of the source atomic expression.
4866 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004867 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4868 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004869 /// \brief Return the update expression used in calculation of the updated
4870 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4871 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4872 Expr *getUpdateExpr() const { return UpdateExpr; }
4873 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4874 /// false otherwise.
4875 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4876
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() const { return IsPostfixUpdate; }
4880
Alexey Bataev1d160b12015-03-13 12:27:31 +00004881private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004882 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4883 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004884};
4885} // namespace
4886
4887bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4888 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4889 ExprAnalysisErrorCode ErrorFound = NoError;
4890 SourceLocation ErrorLoc, NoteLoc;
4891 SourceRange ErrorRange, NoteRange;
4892 // Allowed constructs are:
4893 // x = x binop expr;
4894 // x = expr binop x;
4895 if (AtomicBinOp->getOpcode() == BO_Assign) {
4896 X = AtomicBinOp->getLHS();
4897 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4898 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4899 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4900 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4901 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004902 Op = AtomicInnerBinOp->getOpcode();
4903 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004904 auto *LHS = AtomicInnerBinOp->getLHS();
4905 auto *RHS = AtomicInnerBinOp->getRHS();
4906 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4907 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4908 /*Canonical=*/true);
4909 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4910 /*Canonical=*/true);
4911 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4912 /*Canonical=*/true);
4913 if (XId == LHSId) {
4914 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004915 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004916 } else if (XId == RHSId) {
4917 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004918 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004919 } else {
4920 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4921 ErrorRange = AtomicInnerBinOp->getSourceRange();
4922 NoteLoc = X->getExprLoc();
4923 NoteRange = X->getSourceRange();
4924 ErrorFound = NotAnUpdateExpression;
4925 }
4926 } else {
4927 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4928 ErrorRange = AtomicInnerBinOp->getSourceRange();
4929 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4930 NoteRange = SourceRange(NoteLoc, NoteLoc);
4931 ErrorFound = NotABinaryOperator;
4932 }
4933 } else {
4934 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4935 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4936 ErrorFound = NotABinaryExpression;
4937 }
4938 } else {
4939 ErrorLoc = AtomicBinOp->getExprLoc();
4940 ErrorRange = AtomicBinOp->getSourceRange();
4941 NoteLoc = AtomicBinOp->getOperatorLoc();
4942 NoteRange = SourceRange(NoteLoc, NoteLoc);
4943 ErrorFound = NotAnAssignmentOp;
4944 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004945 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004946 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4947 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4948 return true;
4949 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004950 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004951 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004952}
4953
4954bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4955 unsigned NoteId) {
4956 ExprAnalysisErrorCode ErrorFound = NoError;
4957 SourceLocation ErrorLoc, NoteLoc;
4958 SourceRange ErrorRange, NoteRange;
4959 // Allowed constructs are:
4960 // x++;
4961 // x--;
4962 // ++x;
4963 // --x;
4964 // x binop= expr;
4965 // x = x binop expr;
4966 // x = expr binop x;
4967 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4968 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4969 if (AtomicBody->getType()->isScalarType() ||
4970 AtomicBody->isInstantiationDependent()) {
4971 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4972 AtomicBody->IgnoreParenImpCasts())) {
4973 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004974 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004975 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004976 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004977 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00004978 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004979 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004980 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4981 AtomicBody->IgnoreParenImpCasts())) {
4982 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00004983 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00004984 return true;
David Majnemer9d168222016-08-05 17:44:54 +00004985 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
4986 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004987 // Check for Unary Operation
4988 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004989 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004990 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4991 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00004992 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004993 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4994 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004995 } else {
4996 ErrorFound = NotAnUnaryIncDecExpression;
4997 ErrorLoc = AtomicUnaryOp->getExprLoc();
4998 ErrorRange = AtomicUnaryOp->getSourceRange();
4999 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5000 NoteRange = SourceRange(NoteLoc, NoteLoc);
5001 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005002 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005003 ErrorFound = NotABinaryOrUnaryExpression;
5004 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5005 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5006 }
5007 } else {
5008 ErrorFound = NotAScalarType;
5009 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5010 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5011 }
5012 } else {
5013 ErrorFound = NotAnExpression;
5014 NoteLoc = ErrorLoc = S->getLocStart();
5015 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5016 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005017 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005018 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5019 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5020 return true;
5021 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005022 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005023 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005024 // Build an update expression of form 'OpaqueValueExpr(x) binop
5025 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5026 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5027 auto *OVEX = new (SemaRef.getASTContext())
5028 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5029 auto *OVEExpr = new (SemaRef.getASTContext())
5030 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5031 auto Update =
5032 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5033 IsXLHSInRHSPart ? OVEExpr : OVEX);
5034 if (Update.isInvalid())
5035 return true;
5036 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5037 Sema::AA_Casting);
5038 if (Update.isInvalid())
5039 return true;
5040 UpdateExpr = Update.get();
5041 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005042 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005043}
5044
Alexey Bataev0162e452014-07-22 10:10:35 +00005045StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5046 Stmt *AStmt,
5047 SourceLocation StartLoc,
5048 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005049 if (!AStmt)
5050 return StmtError();
5051
David Majnemer9d168222016-08-05 17:44:54 +00005052 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005053 // 1.2.2 OpenMP Language Terminology
5054 // Structured block - An executable statement with a single entry at the
5055 // top and a single exit at the bottom.
5056 // The point of exit cannot be a branch out of the structured block.
5057 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005058 OpenMPClauseKind AtomicKind = OMPC_unknown;
5059 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005060 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005061 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005062 C->getClauseKind() == OMPC_update ||
5063 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005064 if (AtomicKind != OMPC_unknown) {
5065 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5066 << SourceRange(C->getLocStart(), C->getLocEnd());
5067 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5068 << getOpenMPClauseName(AtomicKind);
5069 } else {
5070 AtomicKind = C->getClauseKind();
5071 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005072 }
5073 }
5074 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005075
Alexey Bataev459dec02014-07-24 06:46:57 +00005076 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005077 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5078 Body = EWC->getSubExpr();
5079
Alexey Bataev62cec442014-11-18 10:14:22 +00005080 Expr *X = nullptr;
5081 Expr *V = nullptr;
5082 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005083 Expr *UE = nullptr;
5084 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005085 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005086 // OpenMP [2.12.6, atomic Construct]
5087 // In the next expressions:
5088 // * x and v (as applicable) are both l-value expressions with scalar type.
5089 // * During the execution of an atomic region, multiple syntactic
5090 // occurrences of x must designate the same storage location.
5091 // * Neither of v and expr (as applicable) may access the storage location
5092 // designated by x.
5093 // * Neither of x and expr (as applicable) may access the storage location
5094 // designated by v.
5095 // * expr is an expression with scalar type.
5096 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5097 // * binop, binop=, ++, and -- are not overloaded operators.
5098 // * The expression x binop expr must be numerically equivalent to x binop
5099 // (expr). This requirement is satisfied if the operators in expr have
5100 // precedence greater than binop, or by using parentheses around expr or
5101 // subexpressions of expr.
5102 // * The expression expr binop x must be numerically equivalent to (expr)
5103 // binop x. This requirement is satisfied if the operators in expr have
5104 // precedence equal to or greater than binop, or by using parentheses around
5105 // expr or subexpressions of expr.
5106 // * For forms that allow multiple occurrences of x, the number of times
5107 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005108 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005109 enum {
5110 NotAnExpression,
5111 NotAnAssignmentOp,
5112 NotAScalarType,
5113 NotAnLValue,
5114 NoError
5115 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005116 SourceLocation ErrorLoc, NoteLoc;
5117 SourceRange ErrorRange, NoteRange;
5118 // If clause is read:
5119 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005120 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5121 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005122 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5123 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5124 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5125 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5126 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5127 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5128 if (!X->isLValue() || !V->isLValue()) {
5129 auto NotLValueExpr = X->isLValue() ? V : X;
5130 ErrorFound = NotAnLValue;
5131 ErrorLoc = AtomicBinOp->getExprLoc();
5132 ErrorRange = AtomicBinOp->getSourceRange();
5133 NoteLoc = NotLValueExpr->getExprLoc();
5134 NoteRange = NotLValueExpr->getSourceRange();
5135 }
5136 } else if (!X->isInstantiationDependent() ||
5137 !V->isInstantiationDependent()) {
5138 auto NotScalarExpr =
5139 (X->isInstantiationDependent() || X->getType()->isScalarType())
5140 ? V
5141 : X;
5142 ErrorFound = NotAScalarType;
5143 ErrorLoc = AtomicBinOp->getExprLoc();
5144 ErrorRange = AtomicBinOp->getSourceRange();
5145 NoteLoc = NotScalarExpr->getExprLoc();
5146 NoteRange = NotScalarExpr->getSourceRange();
5147 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005148 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005149 ErrorFound = NotAnAssignmentOp;
5150 ErrorLoc = AtomicBody->getExprLoc();
5151 ErrorRange = AtomicBody->getSourceRange();
5152 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5153 : AtomicBody->getExprLoc();
5154 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5155 : AtomicBody->getSourceRange();
5156 }
5157 } else {
5158 ErrorFound = NotAnExpression;
5159 NoteLoc = ErrorLoc = Body->getLocStart();
5160 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005161 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005162 if (ErrorFound != NoError) {
5163 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5164 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005165 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5166 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005167 return StmtError();
5168 } else if (CurContext->isDependentContext())
5169 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005170 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005171 enum {
5172 NotAnExpression,
5173 NotAnAssignmentOp,
5174 NotAScalarType,
5175 NotAnLValue,
5176 NoError
5177 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005178 SourceLocation ErrorLoc, NoteLoc;
5179 SourceRange ErrorRange, NoteRange;
5180 // If clause is write:
5181 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005182 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5183 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005184 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5185 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005186 X = AtomicBinOp->getLHS();
5187 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005188 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5189 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5190 if (!X->isLValue()) {
5191 ErrorFound = NotAnLValue;
5192 ErrorLoc = AtomicBinOp->getExprLoc();
5193 ErrorRange = AtomicBinOp->getSourceRange();
5194 NoteLoc = X->getExprLoc();
5195 NoteRange = X->getSourceRange();
5196 }
5197 } else if (!X->isInstantiationDependent() ||
5198 !E->isInstantiationDependent()) {
5199 auto NotScalarExpr =
5200 (X->isInstantiationDependent() || X->getType()->isScalarType())
5201 ? E
5202 : X;
5203 ErrorFound = NotAScalarType;
5204 ErrorLoc = AtomicBinOp->getExprLoc();
5205 ErrorRange = AtomicBinOp->getSourceRange();
5206 NoteLoc = NotScalarExpr->getExprLoc();
5207 NoteRange = NotScalarExpr->getSourceRange();
5208 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005209 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005210 ErrorFound = NotAnAssignmentOp;
5211 ErrorLoc = AtomicBody->getExprLoc();
5212 ErrorRange = AtomicBody->getSourceRange();
5213 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5214 : AtomicBody->getExprLoc();
5215 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5216 : AtomicBody->getSourceRange();
5217 }
5218 } else {
5219 ErrorFound = NotAnExpression;
5220 NoteLoc = ErrorLoc = Body->getLocStart();
5221 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005222 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005223 if (ErrorFound != NoError) {
5224 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5225 << ErrorRange;
5226 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5227 << NoteRange;
5228 return StmtError();
5229 } else if (CurContext->isDependentContext())
5230 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005231 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005232 // If clause is update:
5233 // x++;
5234 // x--;
5235 // ++x;
5236 // --x;
5237 // x binop= expr;
5238 // x = x binop expr;
5239 // x = expr binop x;
5240 OpenMPAtomicUpdateChecker Checker(*this);
5241 if (Checker.checkStatement(
5242 Body, (AtomicKind == OMPC_update)
5243 ? diag::err_omp_atomic_update_not_expression_statement
5244 : diag::err_omp_atomic_not_expression_statement,
5245 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005246 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005247 if (!CurContext->isDependentContext()) {
5248 E = Checker.getExpr();
5249 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005250 UE = Checker.getUpdateExpr();
5251 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005252 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005253 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005254 enum {
5255 NotAnAssignmentOp,
5256 NotACompoundStatement,
5257 NotTwoSubstatements,
5258 NotASpecificExpression,
5259 NoError
5260 } ErrorFound = NoError;
5261 SourceLocation ErrorLoc, NoteLoc;
5262 SourceRange ErrorRange, NoteRange;
5263 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5264 // If clause is a capture:
5265 // v = x++;
5266 // v = x--;
5267 // v = ++x;
5268 // v = --x;
5269 // v = x binop= expr;
5270 // v = x = x binop expr;
5271 // v = x = expr binop x;
5272 auto *AtomicBinOp =
5273 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5274 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5275 V = AtomicBinOp->getLHS();
5276 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5277 OpenMPAtomicUpdateChecker Checker(*this);
5278 if (Checker.checkStatement(
5279 Body, diag::err_omp_atomic_capture_not_expression_statement,
5280 diag::note_omp_atomic_update))
5281 return StmtError();
5282 E = Checker.getExpr();
5283 X = Checker.getX();
5284 UE = Checker.getUpdateExpr();
5285 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5286 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005287 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005288 ErrorLoc = AtomicBody->getExprLoc();
5289 ErrorRange = AtomicBody->getSourceRange();
5290 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5291 : AtomicBody->getExprLoc();
5292 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5293 : AtomicBody->getSourceRange();
5294 ErrorFound = NotAnAssignmentOp;
5295 }
5296 if (ErrorFound != NoError) {
5297 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5298 << ErrorRange;
5299 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5300 return StmtError();
5301 } else if (CurContext->isDependentContext()) {
5302 UE = V = E = X = nullptr;
5303 }
5304 } else {
5305 // If clause is a capture:
5306 // { v = x; x = expr; }
5307 // { v = x; x++; }
5308 // { v = x; x--; }
5309 // { v = x; ++x; }
5310 // { v = x; --x; }
5311 // { v = x; x binop= expr; }
5312 // { v = x; x = x binop expr; }
5313 // { v = x; x = expr binop x; }
5314 // { x++; v = x; }
5315 // { x--; v = x; }
5316 // { ++x; v = x; }
5317 // { --x; v = x; }
5318 // { x binop= expr; v = x; }
5319 // { x = x binop expr; v = x; }
5320 // { x = expr binop x; v = x; }
5321 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5322 // Check that this is { expr1; expr2; }
5323 if (CS->size() == 2) {
5324 auto *First = CS->body_front();
5325 auto *Second = CS->body_back();
5326 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5327 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5328 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5329 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5330 // Need to find what subexpression is 'v' and what is 'x'.
5331 OpenMPAtomicUpdateChecker Checker(*this);
5332 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5333 BinaryOperator *BinOp = nullptr;
5334 if (IsUpdateExprFound) {
5335 BinOp = dyn_cast<BinaryOperator>(First);
5336 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5337 }
5338 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5339 // { v = x; x++; }
5340 // { v = x; x--; }
5341 // { v = x; ++x; }
5342 // { v = x; --x; }
5343 // { v = x; x binop= expr; }
5344 // { v = x; x = x binop expr; }
5345 // { v = x; x = expr binop x; }
5346 // Check that the first expression has form v = x.
5347 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5348 llvm::FoldingSetNodeID XId, PossibleXId;
5349 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5350 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5351 IsUpdateExprFound = XId == PossibleXId;
5352 if (IsUpdateExprFound) {
5353 V = BinOp->getLHS();
5354 X = Checker.getX();
5355 E = Checker.getExpr();
5356 UE = Checker.getUpdateExpr();
5357 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005358 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005359 }
5360 }
5361 if (!IsUpdateExprFound) {
5362 IsUpdateExprFound = !Checker.checkStatement(First);
5363 BinOp = nullptr;
5364 if (IsUpdateExprFound) {
5365 BinOp = dyn_cast<BinaryOperator>(Second);
5366 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5367 }
5368 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5369 // { x++; v = x; }
5370 // { x--; v = x; }
5371 // { ++x; v = x; }
5372 // { --x; v = x; }
5373 // { x binop= expr; v = x; }
5374 // { x = x binop expr; v = x; }
5375 // { x = expr binop x; v = x; }
5376 // Check that the second expression has form v = x.
5377 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5378 llvm::FoldingSetNodeID XId, PossibleXId;
5379 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5380 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5381 IsUpdateExprFound = XId == PossibleXId;
5382 if (IsUpdateExprFound) {
5383 V = BinOp->getLHS();
5384 X = Checker.getX();
5385 E = Checker.getExpr();
5386 UE = Checker.getUpdateExpr();
5387 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005388 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005389 }
5390 }
5391 }
5392 if (!IsUpdateExprFound) {
5393 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005394 auto *FirstExpr = dyn_cast<Expr>(First);
5395 auto *SecondExpr = dyn_cast<Expr>(Second);
5396 if (!FirstExpr || !SecondExpr ||
5397 !(FirstExpr->isInstantiationDependent() ||
5398 SecondExpr->isInstantiationDependent())) {
5399 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5400 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005401 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005402 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5403 : First->getLocStart();
5404 NoteRange = ErrorRange = FirstBinOp
5405 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005406 : SourceRange(ErrorLoc, ErrorLoc);
5407 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005408 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5409 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5410 ErrorFound = NotAnAssignmentOp;
5411 NoteLoc = ErrorLoc = SecondBinOp
5412 ? SecondBinOp->getOperatorLoc()
5413 : Second->getLocStart();
5414 NoteRange = ErrorRange =
5415 SecondBinOp ? SecondBinOp->getSourceRange()
5416 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005417 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005418 auto *PossibleXRHSInFirst =
5419 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5420 auto *PossibleXLHSInSecond =
5421 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5422 llvm::FoldingSetNodeID X1Id, X2Id;
5423 PossibleXRHSInFirst->Profile(X1Id, Context,
5424 /*Canonical=*/true);
5425 PossibleXLHSInSecond->Profile(X2Id, Context,
5426 /*Canonical=*/true);
5427 IsUpdateExprFound = X1Id == X2Id;
5428 if (IsUpdateExprFound) {
5429 V = FirstBinOp->getLHS();
5430 X = SecondBinOp->getLHS();
5431 E = SecondBinOp->getRHS();
5432 UE = nullptr;
5433 IsXLHSInRHSPart = false;
5434 IsPostfixUpdate = true;
5435 } else {
5436 ErrorFound = NotASpecificExpression;
5437 ErrorLoc = FirstBinOp->getExprLoc();
5438 ErrorRange = FirstBinOp->getSourceRange();
5439 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5440 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5441 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005442 }
5443 }
5444 }
5445 }
5446 } else {
5447 NoteLoc = ErrorLoc = Body->getLocStart();
5448 NoteRange = ErrorRange =
5449 SourceRange(Body->getLocStart(), Body->getLocStart());
5450 ErrorFound = NotTwoSubstatements;
5451 }
5452 } else {
5453 NoteLoc = ErrorLoc = Body->getLocStart();
5454 NoteRange = ErrorRange =
5455 SourceRange(Body->getLocStart(), Body->getLocStart());
5456 ErrorFound = NotACompoundStatement;
5457 }
5458 if (ErrorFound != NoError) {
5459 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5460 << ErrorRange;
5461 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5462 return StmtError();
5463 } else if (CurContext->isDependentContext()) {
5464 UE = V = E = X = nullptr;
5465 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005466 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005467 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005468
5469 getCurFunction()->setHasBranchProtectedScope();
5470
Alexey Bataev62cec442014-11-18 10:14:22 +00005471 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005472 X, V, E, UE, IsXLHSInRHSPart,
5473 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005474}
5475
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005476StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5477 Stmt *AStmt,
5478 SourceLocation StartLoc,
5479 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005480 if (!AStmt)
5481 return StmtError();
5482
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005483 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5484 // 1.2.2 OpenMP Language Terminology
5485 // Structured block - An executable statement with a single entry at the
5486 // top and a single exit at the bottom.
5487 // The point of exit cannot be a branch out of the structured block.
5488 // longjmp() and throw() must not violate the entry/exit criteria.
5489 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005490
Alexey Bataev13314bf2014-10-09 04:18:56 +00005491 // OpenMP [2.16, Nesting of Regions]
5492 // If specified, a teams construct must be contained within a target
5493 // construct. That target construct must contain no statements or directives
5494 // outside of the teams construct.
5495 if (DSAStack->hasInnerTeamsRegion()) {
5496 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5497 bool OMPTeamsFound = true;
5498 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5499 auto I = CS->body_begin();
5500 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005501 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005502 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5503 OMPTeamsFound = false;
5504 break;
5505 }
5506 ++I;
5507 }
5508 assert(I != CS->body_end() && "Not found statement");
5509 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005510 } else {
5511 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5512 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005513 }
5514 if (!OMPTeamsFound) {
5515 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5516 Diag(DSAStack->getInnerTeamsRegionLoc(),
5517 diag::note_omp_nested_teams_construct_here);
5518 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5519 << isa<OMPExecutableDirective>(S);
5520 return StmtError();
5521 }
5522 }
5523
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005524 getCurFunction()->setHasBranchProtectedScope();
5525
5526 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5527}
5528
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005529StmtResult
5530Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5531 Stmt *AStmt, SourceLocation StartLoc,
5532 SourceLocation EndLoc) {
5533 if (!AStmt)
5534 return StmtError();
5535
5536 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5537 // 1.2.2 OpenMP Language Terminology
5538 // Structured block - An executable statement with a single entry at the
5539 // top and a single exit at the bottom.
5540 // The point of exit cannot be a branch out of the structured block.
5541 // longjmp() and throw() must not violate the entry/exit criteria.
5542 CS->getCapturedDecl()->setNothrow();
5543
5544 getCurFunction()->setHasBranchProtectedScope();
5545
5546 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5547 AStmt);
5548}
5549
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005550StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5551 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5552 SourceLocation EndLoc,
5553 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5554 if (!AStmt)
5555 return StmtError();
5556
5557 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5558 // 1.2.2 OpenMP Language Terminology
5559 // Structured block - An executable statement with a single entry at the
5560 // top and a single exit at the bottom.
5561 // The point of exit cannot be a branch out of the structured block.
5562 // longjmp() and throw() must not violate the entry/exit criteria.
5563 CS->getCapturedDecl()->setNothrow();
5564
5565 OMPLoopDirective::HelperExprs B;
5566 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5567 // define the nested loops number.
5568 unsigned NestedLoopCount =
5569 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5570 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5571 VarsWithImplicitDSA, B);
5572 if (NestedLoopCount == 0)
5573 return StmtError();
5574
5575 assert((CurContext->isDependentContext() || B.builtAll()) &&
5576 "omp target parallel for loop exprs were not built");
5577
5578 if (!CurContext->isDependentContext()) {
5579 // Finalize the clauses that need pre-built expressions for CodeGen.
5580 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005581 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005582 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005583 B.NumIterations, *this, CurScope,
5584 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005585 return StmtError();
5586 }
5587 }
5588
5589 getCurFunction()->setHasBranchProtectedScope();
5590 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5591 NestedLoopCount, Clauses, AStmt,
5592 B, DSAStack->isCancelRegion());
5593}
5594
Samuel Antaodf67fc42016-01-19 19:15:56 +00005595/// \brief Check for existence of a map clause in the list of clauses.
5596static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5597 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5598 I != E; ++I) {
5599 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5600 return true;
5601 }
5602 }
5603
5604 return false;
5605}
5606
Michael Wong65f367f2015-07-21 13:44:28 +00005607StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5608 Stmt *AStmt,
5609 SourceLocation StartLoc,
5610 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005611 if (!AStmt)
5612 return StmtError();
5613
5614 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5615
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005616 // OpenMP [2.10.1, Restrictions, p. 97]
5617 // At least one map clause must appear on the directive.
5618 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005619 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5620 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005621 return StmtError();
5622 }
5623
Michael Wong65f367f2015-07-21 13:44:28 +00005624 getCurFunction()->setHasBranchProtectedScope();
5625
5626 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5627 AStmt);
5628}
5629
Samuel Antaodf67fc42016-01-19 19:15:56 +00005630StmtResult
5631Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5632 SourceLocation StartLoc,
5633 SourceLocation EndLoc) {
5634 // OpenMP [2.10.2, Restrictions, p. 99]
5635 // At least one map clause must appear on the directive.
5636 if (!HasMapClause(Clauses)) {
5637 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5638 << getOpenMPDirectiveName(OMPD_target_enter_data);
5639 return StmtError();
5640 }
5641
5642 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5643 Clauses);
5644}
5645
Samuel Antao72590762016-01-19 20:04:50 +00005646StmtResult
5647Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5648 SourceLocation StartLoc,
5649 SourceLocation EndLoc) {
5650 // OpenMP [2.10.3, Restrictions, p. 102]
5651 // At least one map clause must appear on the directive.
5652 if (!HasMapClause(Clauses)) {
5653 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5654 << getOpenMPDirectiveName(OMPD_target_exit_data);
5655 return StmtError();
5656 }
5657
5658 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5659}
5660
Samuel Antao686c70c2016-05-26 17:30:50 +00005661StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5662 SourceLocation StartLoc,
5663 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005664 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005665 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005666 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005667 seenMotionClause = true;
5668 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005669 if (!seenMotionClause) {
5670 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5671 return StmtError();
5672 }
5673 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5674}
5675
Alexey Bataev13314bf2014-10-09 04:18:56 +00005676StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5677 Stmt *AStmt, SourceLocation StartLoc,
5678 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005679 if (!AStmt)
5680 return StmtError();
5681
Alexey Bataev13314bf2014-10-09 04:18:56 +00005682 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5683 // 1.2.2 OpenMP Language Terminology
5684 // Structured block - An executable statement with a single entry at the
5685 // top and a single exit at the bottom.
5686 // The point of exit cannot be a branch out of the structured block.
5687 // longjmp() and throw() must not violate the entry/exit criteria.
5688 CS->getCapturedDecl()->setNothrow();
5689
5690 getCurFunction()->setHasBranchProtectedScope();
5691
5692 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5693}
5694
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005695StmtResult
5696Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5697 SourceLocation EndLoc,
5698 OpenMPDirectiveKind CancelRegion) {
5699 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5700 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5701 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5702 << getOpenMPDirectiveName(CancelRegion);
5703 return StmtError();
5704 }
5705 if (DSAStack->isParentNowaitRegion()) {
5706 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5707 return StmtError();
5708 }
5709 if (DSAStack->isParentOrderedRegion()) {
5710 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5711 return StmtError();
5712 }
5713 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5714 CancelRegion);
5715}
5716
Alexey Bataev87933c72015-09-18 08:07:34 +00005717StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5718 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005719 SourceLocation EndLoc,
5720 OpenMPDirectiveKind CancelRegion) {
5721 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5722 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5723 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5724 << getOpenMPDirectiveName(CancelRegion);
5725 return StmtError();
5726 }
5727 if (DSAStack->isParentNowaitRegion()) {
5728 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5729 return StmtError();
5730 }
5731 if (DSAStack->isParentOrderedRegion()) {
5732 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5733 return StmtError();
5734 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005735 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005736 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5737 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005738}
5739
Alexey Bataev382967a2015-12-08 12:06:20 +00005740static bool checkGrainsizeNumTasksClauses(Sema &S,
5741 ArrayRef<OMPClause *> Clauses) {
5742 OMPClause *PrevClause = nullptr;
5743 bool ErrorFound = false;
5744 for (auto *C : Clauses) {
5745 if (C->getClauseKind() == OMPC_grainsize ||
5746 C->getClauseKind() == OMPC_num_tasks) {
5747 if (!PrevClause)
5748 PrevClause = C;
5749 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5750 S.Diag(C->getLocStart(),
5751 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5752 << getOpenMPClauseName(C->getClauseKind())
5753 << getOpenMPClauseName(PrevClause->getClauseKind());
5754 S.Diag(PrevClause->getLocStart(),
5755 diag::note_omp_previous_grainsize_num_tasks)
5756 << getOpenMPClauseName(PrevClause->getClauseKind());
5757 ErrorFound = true;
5758 }
5759 }
5760 }
5761 return ErrorFound;
5762}
5763
Alexey Bataev49f6e782015-12-01 04:18:41 +00005764StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5765 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5766 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005767 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005768 if (!AStmt)
5769 return StmtError();
5770
5771 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5772 OMPLoopDirective::HelperExprs B;
5773 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5774 // define the nested loops number.
5775 unsigned NestedLoopCount =
5776 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005777 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005778 VarsWithImplicitDSA, B);
5779 if (NestedLoopCount == 0)
5780 return StmtError();
5781
5782 assert((CurContext->isDependentContext() || B.builtAll()) &&
5783 "omp for loop exprs were not built");
5784
Alexey Bataev382967a2015-12-08 12:06:20 +00005785 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5786 // The grainsize clause and num_tasks clause are mutually exclusive and may
5787 // not appear on the same taskloop directive.
5788 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5789 return StmtError();
5790
Alexey Bataev49f6e782015-12-01 04:18:41 +00005791 getCurFunction()->setHasBranchProtectedScope();
5792 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5793 NestedLoopCount, Clauses, AStmt, B);
5794}
5795
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005796StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5797 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5798 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005799 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005800 if (!AStmt)
5801 return StmtError();
5802
5803 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5804 OMPLoopDirective::HelperExprs B;
5805 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5806 // define the nested loops number.
5807 unsigned NestedLoopCount =
5808 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5809 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5810 VarsWithImplicitDSA, B);
5811 if (NestedLoopCount == 0)
5812 return StmtError();
5813
5814 assert((CurContext->isDependentContext() || B.builtAll()) &&
5815 "omp for loop exprs were not built");
5816
Alexey Bataev5a3af132016-03-29 08:58:54 +00005817 if (!CurContext->isDependentContext()) {
5818 // Finalize the clauses that need pre-built expressions for CodeGen.
5819 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005820 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005821 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005822 B.NumIterations, *this, CurScope,
5823 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005824 return StmtError();
5825 }
5826 }
5827
Alexey Bataev382967a2015-12-08 12:06:20 +00005828 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5829 // The grainsize clause and num_tasks clause are mutually exclusive and may
5830 // not appear on the same taskloop directive.
5831 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5832 return StmtError();
5833
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005834 getCurFunction()->setHasBranchProtectedScope();
5835 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5836 NestedLoopCount, Clauses, AStmt, B);
5837}
5838
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005839StmtResult Sema::ActOnOpenMPDistributeDirective(
5840 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5841 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005842 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005843 if (!AStmt)
5844 return StmtError();
5845
5846 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5847 OMPLoopDirective::HelperExprs B;
5848 // In presence of clause 'collapse' with number of loops, it will
5849 // define the nested loops number.
5850 unsigned NestedLoopCount =
5851 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5852 nullptr /*ordered not a clause on distribute*/, AStmt,
5853 *this, *DSAStack, VarsWithImplicitDSA, B);
5854 if (NestedLoopCount == 0)
5855 return StmtError();
5856
5857 assert((CurContext->isDependentContext() || B.builtAll()) &&
5858 "omp for loop exprs were not built");
5859
5860 getCurFunction()->setHasBranchProtectedScope();
5861 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5862 NestedLoopCount, Clauses, AStmt, B);
5863}
5864
Carlo Bertolli9925f152016-06-27 14:55:37 +00005865StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5866 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5867 SourceLocation EndLoc,
5868 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5869 if (!AStmt)
5870 return StmtError();
5871
5872 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5873 // 1.2.2 OpenMP Language Terminology
5874 // Structured block - An executable statement with a single entry at the
5875 // top and a single exit at the bottom.
5876 // The point of exit cannot be a branch out of the structured block.
5877 // longjmp() and throw() must not violate the entry/exit criteria.
5878 CS->getCapturedDecl()->setNothrow();
5879
5880 OMPLoopDirective::HelperExprs B;
5881 // In presence of clause 'collapse' with number of loops, it will
5882 // define the nested loops number.
5883 unsigned NestedLoopCount = CheckOpenMPLoop(
5884 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5885 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5886 VarsWithImplicitDSA, B);
5887 if (NestedLoopCount == 0)
5888 return StmtError();
5889
5890 assert((CurContext->isDependentContext() || B.builtAll()) &&
5891 "omp for loop exprs were not built");
5892
5893 getCurFunction()->setHasBranchProtectedScope();
5894 return OMPDistributeParallelForDirective::Create(
5895 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5896}
5897
Kelvin Li4a39add2016-07-05 05:00:15 +00005898StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5899 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5900 SourceLocation EndLoc,
5901 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5902 if (!AStmt)
5903 return StmtError();
5904
5905 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5906 // 1.2.2 OpenMP Language Terminology
5907 // Structured block - An executable statement with a single entry at the
5908 // top and a single exit at the bottom.
5909 // The point of exit cannot be a branch out of the structured block.
5910 // longjmp() and throw() must not violate the entry/exit criteria.
5911 CS->getCapturedDecl()->setNothrow();
5912
5913 OMPLoopDirective::HelperExprs B;
5914 // In presence of clause 'collapse' with number of loops, it will
5915 // define the nested loops number.
5916 unsigned NestedLoopCount = CheckOpenMPLoop(
5917 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5918 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5919 VarsWithImplicitDSA, B);
5920 if (NestedLoopCount == 0)
5921 return StmtError();
5922
5923 assert((CurContext->isDependentContext() || B.builtAll()) &&
5924 "omp for loop exprs were not built");
5925
Kelvin Lic5609492016-07-15 04:39:07 +00005926 if (checkSimdlenSafelenSpecified(*this, Clauses))
5927 return StmtError();
5928
Kelvin Li4a39add2016-07-05 05:00:15 +00005929 getCurFunction()->setHasBranchProtectedScope();
5930 return OMPDistributeParallelForSimdDirective::Create(
5931 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5932}
5933
Kelvin Li787f3fc2016-07-06 04:45:38 +00005934StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5935 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5936 SourceLocation EndLoc,
5937 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5938 if (!AStmt)
5939 return StmtError();
5940
5941 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5942 // 1.2.2 OpenMP Language Terminology
5943 // Structured block - An executable statement with a single entry at the
5944 // top and a single exit at the bottom.
5945 // The point of exit cannot be a branch out of the structured block.
5946 // longjmp() and throw() must not violate the entry/exit criteria.
5947 CS->getCapturedDecl()->setNothrow();
5948
5949 OMPLoopDirective::HelperExprs B;
5950 // In presence of clause 'collapse' with number of loops, it will
5951 // define the nested loops number.
5952 unsigned NestedLoopCount =
5953 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5954 nullptr /*ordered not a clause on distribute*/, AStmt,
5955 *this, *DSAStack, VarsWithImplicitDSA, B);
5956 if (NestedLoopCount == 0)
5957 return StmtError();
5958
5959 assert((CurContext->isDependentContext() || B.builtAll()) &&
5960 "omp for loop exprs were not built");
5961
Kelvin Lic5609492016-07-15 04:39:07 +00005962 if (checkSimdlenSafelenSpecified(*this, Clauses))
5963 return StmtError();
5964
Kelvin Li787f3fc2016-07-06 04:45:38 +00005965 getCurFunction()->setHasBranchProtectedScope();
5966 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
5967 NestedLoopCount, Clauses, AStmt, B);
5968}
5969
Kelvin Lia579b912016-07-14 02:54:56 +00005970StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
5971 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5972 SourceLocation EndLoc,
5973 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5974 if (!AStmt)
5975 return StmtError();
5976
5977 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5978 // 1.2.2 OpenMP Language Terminology
5979 // Structured block - An executable statement with a single entry at the
5980 // top and a single exit at the bottom.
5981 // The point of exit cannot be a branch out of the structured block.
5982 // longjmp() and throw() must not violate the entry/exit criteria.
5983 CS->getCapturedDecl()->setNothrow();
5984
5985 OMPLoopDirective::HelperExprs B;
5986 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5987 // define the nested loops number.
5988 unsigned NestedLoopCount = CheckOpenMPLoop(
5989 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
5990 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5991 VarsWithImplicitDSA, B);
5992 if (NestedLoopCount == 0)
5993 return StmtError();
5994
5995 assert((CurContext->isDependentContext() || B.builtAll()) &&
5996 "omp target parallel for simd loop exprs were not built");
5997
5998 if (!CurContext->isDependentContext()) {
5999 // Finalize the clauses that need pre-built expressions for CodeGen.
6000 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006001 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006002 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6003 B.NumIterations, *this, CurScope,
6004 DSAStack))
6005 return StmtError();
6006 }
6007 }
Kelvin Lic5609492016-07-15 04:39:07 +00006008 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006009 return StmtError();
6010
6011 getCurFunction()->setHasBranchProtectedScope();
6012 return OMPTargetParallelForSimdDirective::Create(
6013 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6014}
6015
Kelvin Li986330c2016-07-20 22:57:10 +00006016StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6017 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6018 SourceLocation EndLoc,
6019 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6020 if (!AStmt)
6021 return StmtError();
6022
6023 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6024 // 1.2.2 OpenMP Language Terminology
6025 // Structured block - An executable statement with a single entry at the
6026 // top and a single exit at the bottom.
6027 // The point of exit cannot be a branch out of the structured block.
6028 // longjmp() and throw() must not violate the entry/exit criteria.
6029 CS->getCapturedDecl()->setNothrow();
6030
6031 OMPLoopDirective::HelperExprs B;
6032 // In presence of clause 'collapse' with number of loops, it will define the
6033 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006034 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006035 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6036 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6037 VarsWithImplicitDSA, B);
6038 if (NestedLoopCount == 0)
6039 return StmtError();
6040
6041 assert((CurContext->isDependentContext() || B.builtAll()) &&
6042 "omp target simd loop exprs were not built");
6043
6044 if (!CurContext->isDependentContext()) {
6045 // Finalize the clauses that need pre-built expressions for CodeGen.
6046 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006047 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006048 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6049 B.NumIterations, *this, CurScope,
6050 DSAStack))
6051 return StmtError();
6052 }
6053 }
6054
6055 if (checkSimdlenSafelenSpecified(*this, Clauses))
6056 return StmtError();
6057
6058 getCurFunction()->setHasBranchProtectedScope();
6059 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6060 NestedLoopCount, Clauses, AStmt, B);
6061}
6062
Kelvin Li02532872016-08-05 14:37:37 +00006063StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6064 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6065 SourceLocation EndLoc,
6066 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6067 if (!AStmt)
6068 return StmtError();
6069
6070 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6071 // 1.2.2 OpenMP Language Terminology
6072 // Structured block - An executable statement with a single entry at the
6073 // top and a single exit at the bottom.
6074 // The point of exit cannot be a branch out of the structured block.
6075 // longjmp() and throw() must not violate the entry/exit criteria.
6076 CS->getCapturedDecl()->setNothrow();
6077
6078 OMPLoopDirective::HelperExprs B;
6079 // In presence of clause 'collapse' with number of loops, it will
6080 // define the nested loops number.
6081 unsigned NestedLoopCount =
6082 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6083 nullptr /*ordered not a clause on distribute*/, AStmt,
6084 *this, *DSAStack, VarsWithImplicitDSA, B);
6085 if (NestedLoopCount == 0)
6086 return StmtError();
6087
6088 assert((CurContext->isDependentContext() || B.builtAll()) &&
6089 "omp teams distribute loop exprs were not built");
6090
6091 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006092 return OMPTeamsDistributeDirective::Create(
6093 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006094}
6095
Kelvin Li4e325f72016-10-25 12:50:55 +00006096StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6097 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6098 SourceLocation EndLoc,
6099 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6100 if (!AStmt)
6101 return StmtError();
6102
6103 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6104 // 1.2.2 OpenMP Language Terminology
6105 // Structured block - An executable statement with a single entry at the
6106 // top and a single exit at the bottom.
6107 // The point of exit cannot be a branch out of the structured block.
6108 // longjmp() and throw() must not violate the entry/exit criteria.
6109 CS->getCapturedDecl()->setNothrow();
6110
6111 OMPLoopDirective::HelperExprs B;
6112 // In presence of clause 'collapse' with number of loops, it will
6113 // define the nested loops number.
6114 unsigned NestedLoopCount =
6115 CheckOpenMPLoop(OMPD_teams_distribute_simd,
6116 getCollapseNumberExpr(Clauses),
6117 nullptr /*ordered not a clause on distribute*/, AStmt,
6118 *this, *DSAStack, VarsWithImplicitDSA, B);
6119
6120 if (NestedLoopCount == 0)
6121 return StmtError();
6122
6123 assert((CurContext->isDependentContext() || B.builtAll()) &&
6124 "omp teams distribute simd loop exprs were not built");
6125
6126 if (!CurContext->isDependentContext()) {
6127 // Finalize the clauses that need pre-built expressions for CodeGen.
6128 for (auto C : Clauses) {
6129 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6130 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6131 B.NumIterations, *this, CurScope,
6132 DSAStack))
6133 return StmtError();
6134 }
6135 }
6136
6137 if (checkSimdlenSafelenSpecified(*this, Clauses))
6138 return StmtError();
6139
6140 getCurFunction()->setHasBranchProtectedScope();
6141 return OMPTeamsDistributeSimdDirective::Create(
6142 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6143}
6144
Alexey Bataeved09d242014-05-28 05:53:51 +00006145OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006146 SourceLocation StartLoc,
6147 SourceLocation LParenLoc,
6148 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006149 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006150 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006151 case OMPC_final:
6152 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6153 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006154 case OMPC_num_threads:
6155 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6156 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006157 case OMPC_safelen:
6158 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6159 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006160 case OMPC_simdlen:
6161 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6162 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006163 case OMPC_collapse:
6164 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6165 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006166 case OMPC_ordered:
6167 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6168 break;
Michael Wonge710d542015-08-07 16:16:36 +00006169 case OMPC_device:
6170 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6171 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006172 case OMPC_num_teams:
6173 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6174 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006175 case OMPC_thread_limit:
6176 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6177 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006178 case OMPC_priority:
6179 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6180 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006181 case OMPC_grainsize:
6182 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6183 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006184 case OMPC_num_tasks:
6185 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6186 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006187 case OMPC_hint:
6188 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6189 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006190 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006191 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006192 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006193 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006194 case OMPC_private:
6195 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006196 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006197 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006198 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006199 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006200 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006201 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006202 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006203 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006204 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006205 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006206 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006207 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006208 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006209 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006210 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006211 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006212 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006213 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006214 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006215 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006216 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006217 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006218 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006219 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006220 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006221 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006222 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006223 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006224 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006225 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006226 llvm_unreachable("Clause is not allowed.");
6227 }
6228 return Res;
6229}
6230
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006231OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6232 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006233 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006234 SourceLocation NameModifierLoc,
6235 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006236 SourceLocation EndLoc) {
6237 Expr *ValExpr = Condition;
6238 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6239 !Condition->isInstantiationDependent() &&
6240 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006241 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006242 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006243 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006244
Richard Smith03a4aa32016-06-23 19:02:52 +00006245 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006246 }
6247
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006248 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6249 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006250}
6251
Alexey Bataev3778b602014-07-17 07:32:53 +00006252OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6253 SourceLocation StartLoc,
6254 SourceLocation LParenLoc,
6255 SourceLocation EndLoc) {
6256 Expr *ValExpr = Condition;
6257 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6258 !Condition->isInstantiationDependent() &&
6259 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006260 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006261 if (Val.isInvalid())
6262 return nullptr;
6263
Richard Smith03a4aa32016-06-23 19:02:52 +00006264 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006265 }
6266
6267 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6268}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006269ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6270 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006271 if (!Op)
6272 return ExprError();
6273
6274 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6275 public:
6276 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006277 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006278 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6279 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006280 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6281 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006282 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6283 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006284 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6285 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006286 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6287 QualType T,
6288 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006289 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6290 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006291 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6292 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006293 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006294 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006295 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006296 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6297 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006298 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6299 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006300 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6301 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006302 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006303 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006304 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006305 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6306 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006307 llvm_unreachable("conversion functions are permitted");
6308 }
6309 } ConvertDiagnoser;
6310 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6311}
6312
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006313static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006314 OpenMPClauseKind CKind,
6315 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006316 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6317 !ValExpr->isInstantiationDependent()) {
6318 SourceLocation Loc = ValExpr->getExprLoc();
6319 ExprResult Value =
6320 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6321 if (Value.isInvalid())
6322 return false;
6323
6324 ValExpr = Value.get();
6325 // The expression must evaluate to a non-negative integer value.
6326 llvm::APSInt Result;
6327 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006328 Result.isSigned() &&
6329 !((!StrictlyPositive && Result.isNonNegative()) ||
6330 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006331 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006332 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6333 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006334 return false;
6335 }
6336 }
6337 return true;
6338}
6339
Alexey Bataev568a8332014-03-06 06:15:19 +00006340OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6341 SourceLocation StartLoc,
6342 SourceLocation LParenLoc,
6343 SourceLocation EndLoc) {
6344 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006345
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006346 // OpenMP [2.5, Restrictions]
6347 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006348 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6349 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006350 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006351
Alexey Bataeved09d242014-05-28 05:53:51 +00006352 return new (Context)
6353 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006354}
6355
Alexey Bataev62c87d22014-03-21 04:51:18 +00006356ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006357 OpenMPClauseKind CKind,
6358 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006359 if (!E)
6360 return ExprError();
6361 if (E->isValueDependent() || E->isTypeDependent() ||
6362 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006363 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006364 llvm::APSInt Result;
6365 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6366 if (ICE.isInvalid())
6367 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006368 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6369 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006370 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006371 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6372 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006373 return ExprError();
6374 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006375 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6376 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6377 << E->getSourceRange();
6378 return ExprError();
6379 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006380 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6381 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006382 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006383 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006384 return ICE;
6385}
6386
6387OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6388 SourceLocation LParenLoc,
6389 SourceLocation EndLoc) {
6390 // OpenMP [2.8.1, simd construct, Description]
6391 // The parameter of the safelen clause must be a constant
6392 // positive integer expression.
6393 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6394 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006395 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006396 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006397 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006398}
6399
Alexey Bataev66b15b52015-08-21 11:14:16 +00006400OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6401 SourceLocation LParenLoc,
6402 SourceLocation EndLoc) {
6403 // OpenMP [2.8.1, simd construct, Description]
6404 // The parameter of the simdlen clause must be a constant
6405 // positive integer expression.
6406 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6407 if (Simdlen.isInvalid())
6408 return nullptr;
6409 return new (Context)
6410 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6411}
6412
Alexander Musman64d33f12014-06-04 07:53:32 +00006413OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6414 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006415 SourceLocation LParenLoc,
6416 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006417 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006418 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006419 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006420 // The parameter of the collapse clause must be a constant
6421 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006422 ExprResult NumForLoopsResult =
6423 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6424 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006425 return nullptr;
6426 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006427 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006428}
6429
Alexey Bataev10e775f2015-07-30 11:36:16 +00006430OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6431 SourceLocation EndLoc,
6432 SourceLocation LParenLoc,
6433 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006434 // OpenMP [2.7.1, loop construct, Description]
6435 // OpenMP [2.8.1, simd construct, Description]
6436 // OpenMP [2.9.6, distribute construct, Description]
6437 // The parameter of the ordered clause must be a constant
6438 // positive integer expression if any.
6439 if (NumForLoops && LParenLoc.isValid()) {
6440 ExprResult NumForLoopsResult =
6441 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6442 if (NumForLoopsResult.isInvalid())
6443 return nullptr;
6444 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006445 } else
6446 NumForLoops = nullptr;
6447 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006448 return new (Context)
6449 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6450}
6451
Alexey Bataeved09d242014-05-28 05:53:51 +00006452OMPClause *Sema::ActOnOpenMPSimpleClause(
6453 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6454 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006455 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006456 switch (Kind) {
6457 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006458 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006459 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6460 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006461 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006462 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006463 Res = ActOnOpenMPProcBindClause(
6464 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6465 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006466 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006467 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006468 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006469 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006470 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006471 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006472 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006473 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006474 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006475 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006476 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006477 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006478 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006479 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006480 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006481 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006482 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006483 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006484 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006485 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006486 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006487 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006488 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006489 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006490 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006491 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006492 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006493 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006494 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006495 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006496 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006497 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006498 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006499 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006500 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006501 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006502 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006503 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006504 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006505 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006506 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006507 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006508 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006509 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006510 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006511 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006512 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006513 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006514 llvm_unreachable("Clause is not allowed.");
6515 }
6516 return Res;
6517}
6518
Alexey Bataev6402bca2015-12-28 07:25:51 +00006519static std::string
6520getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6521 ArrayRef<unsigned> Exclude = llvm::None) {
6522 std::string Values;
6523 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6524 unsigned Skipped = Exclude.size();
6525 auto S = Exclude.begin(), E = Exclude.end();
6526 for (unsigned i = First; i < Last; ++i) {
6527 if (std::find(S, E, i) != E) {
6528 --Skipped;
6529 continue;
6530 }
6531 Values += "'";
6532 Values += getOpenMPSimpleClauseTypeName(K, i);
6533 Values += "'";
6534 if (i == Bound - Skipped)
6535 Values += " or ";
6536 else if (i != Bound + 1 - Skipped)
6537 Values += ", ";
6538 }
6539 return Values;
6540}
6541
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006542OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6543 SourceLocation KindKwLoc,
6544 SourceLocation StartLoc,
6545 SourceLocation LParenLoc,
6546 SourceLocation EndLoc) {
6547 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006548 static_assert(OMPC_DEFAULT_unknown > 0,
6549 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006550 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006551 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6552 /*Last=*/OMPC_DEFAULT_unknown)
6553 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006554 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006555 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006556 switch (Kind) {
6557 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006558 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006559 break;
6560 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006561 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006562 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006563 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006564 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006565 break;
6566 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006567 return new (Context)
6568 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006569}
6570
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006571OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6572 SourceLocation KindKwLoc,
6573 SourceLocation StartLoc,
6574 SourceLocation LParenLoc,
6575 SourceLocation EndLoc) {
6576 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006577 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006578 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6579 /*Last=*/OMPC_PROC_BIND_unknown)
6580 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006581 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006582 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006583 return new (Context)
6584 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006585}
6586
Alexey Bataev56dafe82014-06-20 07:16:17 +00006587OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006588 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006589 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006590 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006591 SourceLocation EndLoc) {
6592 OMPClause *Res = nullptr;
6593 switch (Kind) {
6594 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006595 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6596 assert(Argument.size() == NumberOfElements &&
6597 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006598 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006599 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6600 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6601 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6602 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6603 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006604 break;
6605 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006606 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6607 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6608 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6609 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006610 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006611 case OMPC_dist_schedule:
6612 Res = ActOnOpenMPDistScheduleClause(
6613 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6614 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6615 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006616 case OMPC_defaultmap:
6617 enum { Modifier, DefaultmapKind };
6618 Res = ActOnOpenMPDefaultmapClause(
6619 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6620 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006621 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6622 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006623 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006624 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006625 case OMPC_num_threads:
6626 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006627 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006628 case OMPC_collapse:
6629 case OMPC_default:
6630 case OMPC_proc_bind:
6631 case OMPC_private:
6632 case OMPC_firstprivate:
6633 case OMPC_lastprivate:
6634 case OMPC_shared:
6635 case OMPC_reduction:
6636 case OMPC_linear:
6637 case OMPC_aligned:
6638 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006639 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006640 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006641 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006642 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006643 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006644 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006645 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006646 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006647 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006648 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006649 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006650 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006651 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006652 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006653 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006654 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006655 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006656 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006657 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006658 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006659 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006660 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006661 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006662 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006663 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006664 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006665 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006666 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006667 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006668 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006669 llvm_unreachable("Clause is not allowed.");
6670 }
6671 return Res;
6672}
6673
Alexey Bataev6402bca2015-12-28 07:25:51 +00006674static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6675 OpenMPScheduleClauseModifier M2,
6676 SourceLocation M1Loc, SourceLocation M2Loc) {
6677 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6678 SmallVector<unsigned, 2> Excluded;
6679 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6680 Excluded.push_back(M2);
6681 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6682 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6683 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6684 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6685 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6686 << getListOfPossibleValues(OMPC_schedule,
6687 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6688 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6689 Excluded)
6690 << getOpenMPClauseName(OMPC_schedule);
6691 return true;
6692 }
6693 return false;
6694}
6695
Alexey Bataev56dafe82014-06-20 07:16:17 +00006696OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006697 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006698 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006699 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6700 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6701 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6702 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6703 return nullptr;
6704 // OpenMP, 2.7.1, Loop Construct, Restrictions
6705 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6706 // but not both.
6707 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6708 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6709 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6710 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6711 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6712 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6713 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6714 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6715 return nullptr;
6716 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006717 if (Kind == OMPC_SCHEDULE_unknown) {
6718 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00006719 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6720 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6721 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6722 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6723 Exclude);
6724 } else {
6725 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6726 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006727 }
6728 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6729 << Values << getOpenMPClauseName(OMPC_schedule);
6730 return nullptr;
6731 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00006732 // OpenMP, 2.7.1, Loop Construct, Restrictions
6733 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6734 // schedule(guided).
6735 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6736 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6737 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6738 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6739 diag::err_omp_schedule_nonmonotonic_static);
6740 return nullptr;
6741 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006742 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00006743 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00006744 if (ChunkSize) {
6745 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6746 !ChunkSize->isInstantiationDependent() &&
6747 !ChunkSize->containsUnexpandedParameterPack()) {
6748 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6749 ExprResult Val =
6750 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6751 if (Val.isInvalid())
6752 return nullptr;
6753
6754 ValExpr = Val.get();
6755
6756 // OpenMP [2.7.1, Restrictions]
6757 // chunk_size must be a loop invariant integer expression with a positive
6758 // value.
6759 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00006760 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6761 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6762 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006763 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00006764 return nullptr;
6765 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00006766 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
6767 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006768 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6769 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6770 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006771 }
6772 }
6773 }
6774
Alexey Bataev6402bca2015-12-28 07:25:51 +00006775 return new (Context)
6776 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00006777 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006778}
6779
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006780OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6781 SourceLocation StartLoc,
6782 SourceLocation EndLoc) {
6783 OMPClause *Res = nullptr;
6784 switch (Kind) {
6785 case OMPC_ordered:
6786 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6787 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00006788 case OMPC_nowait:
6789 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6790 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006791 case OMPC_untied:
6792 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6793 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006794 case OMPC_mergeable:
6795 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6796 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006797 case OMPC_read:
6798 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6799 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00006800 case OMPC_write:
6801 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6802 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006803 case OMPC_update:
6804 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6805 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00006806 case OMPC_capture:
6807 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6808 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006809 case OMPC_seq_cst:
6810 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6811 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00006812 case OMPC_threads:
6813 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6814 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006815 case OMPC_simd:
6816 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6817 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00006818 case OMPC_nogroup:
6819 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6820 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006821 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006822 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006823 case OMPC_num_threads:
6824 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006825 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006826 case OMPC_collapse:
6827 case OMPC_schedule:
6828 case OMPC_private:
6829 case OMPC_firstprivate:
6830 case OMPC_lastprivate:
6831 case OMPC_shared:
6832 case OMPC_reduction:
6833 case OMPC_linear:
6834 case OMPC_aligned:
6835 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006836 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006837 case OMPC_default:
6838 case OMPC_proc_bind:
6839 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006840 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006841 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006842 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006843 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006844 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006845 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006846 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006847 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00006848 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006849 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006850 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006851 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006852 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006853 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006854 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006855 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006856 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006857 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006858 llvm_unreachable("Clause is not allowed.");
6859 }
6860 return Res;
6861}
6862
Alexey Bataev236070f2014-06-20 11:19:47 +00006863OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6864 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006865 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00006866 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6867}
6868
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006869OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6870 SourceLocation EndLoc) {
6871 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6872}
6873
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006874OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6875 SourceLocation EndLoc) {
6876 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6877}
6878
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006879OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6880 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006881 return new (Context) OMPReadClause(StartLoc, EndLoc);
6882}
6883
Alexey Bataevdea47612014-07-23 07:46:59 +00006884OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6885 SourceLocation EndLoc) {
6886 return new (Context) OMPWriteClause(StartLoc, EndLoc);
6887}
6888
Alexey Bataev67a4f222014-07-23 10:25:33 +00006889OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6890 SourceLocation EndLoc) {
6891 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6892}
6893
Alexey Bataev459dec02014-07-24 06:46:57 +00006894OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6895 SourceLocation EndLoc) {
6896 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6897}
6898
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006899OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6900 SourceLocation EndLoc) {
6901 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6902}
6903
Alexey Bataev346265e2015-09-25 10:37:12 +00006904OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6905 SourceLocation EndLoc) {
6906 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6907}
6908
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006909OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6910 SourceLocation EndLoc) {
6911 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6912}
6913
Alexey Bataevb825de12015-12-07 10:51:44 +00006914OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6915 SourceLocation EndLoc) {
6916 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6917}
6918
Alexey Bataevc5e02582014-06-16 07:08:35 +00006919OMPClause *Sema::ActOnOpenMPVarListClause(
6920 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6921 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6922 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006923 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00006924 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
6925 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
6926 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006927 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006928 switch (Kind) {
6929 case OMPC_private:
6930 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6931 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006932 case OMPC_firstprivate:
6933 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6934 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006935 case OMPC_lastprivate:
6936 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6937 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006938 case OMPC_shared:
6939 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
6940 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006941 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00006942 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
6943 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006944 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00006945 case OMPC_linear:
6946 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00006947 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00006948 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006949 case OMPC_aligned:
6950 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
6951 ColonLoc, EndLoc);
6952 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006953 case OMPC_copyin:
6954 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
6955 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006956 case OMPC_copyprivate:
6957 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6958 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00006959 case OMPC_flush:
6960 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
6961 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006962 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00006963 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00006964 StartLoc, LParenLoc, EndLoc);
6965 break;
6966 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00006967 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
6968 DepLinMapLoc, ColonLoc, VarList, StartLoc,
6969 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006970 break;
Samuel Antao661c0902016-05-26 17:39:58 +00006971 case OMPC_to:
6972 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
6973 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00006974 case OMPC_from:
6975 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
6976 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00006977 case OMPC_use_device_ptr:
6978 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
6979 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00006980 case OMPC_is_device_ptr:
6981 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
6982 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006983 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006984 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006985 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006986 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006987 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006988 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006989 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006990 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006991 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006992 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006993 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006994 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006995 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006996 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006997 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006998 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006999 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007000 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007001 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007002 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007003 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007004 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007005 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007006 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007007 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007008 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007009 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007010 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007011 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007012 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007013 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007014 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007015 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007016 llvm_unreachable("Clause is not allowed.");
7017 }
7018 return Res;
7019}
7020
Alexey Bataev90c228f2016-02-08 09:29:13 +00007021ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007022 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007023 ExprResult Res = BuildDeclRefExpr(
7024 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7025 if (!Res.isUsable())
7026 return ExprError();
7027 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7028 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7029 if (!Res.isUsable())
7030 return ExprError();
7031 }
7032 if (VK != VK_LValue && Res.get()->isGLValue()) {
7033 Res = DefaultLvalueConversion(Res.get());
7034 if (!Res.isUsable())
7035 return ExprError();
7036 }
7037 return Res;
7038}
7039
Alexey Bataev60da77e2016-02-29 05:54:20 +00007040static std::pair<ValueDecl *, bool>
7041getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7042 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007043 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7044 RefExpr->containsUnexpandedParameterPack())
7045 return std::make_pair(nullptr, true);
7046
Alexey Bataevd985eda2016-02-10 11:29:16 +00007047 // OpenMP [3.1, C/C++]
7048 // A list item is a variable name.
7049 // OpenMP [2.9.3.3, Restrictions, p.1]
7050 // A variable that is part of another variable (as an array or
7051 // structure element) cannot appear in a private clause.
7052 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007053 enum {
7054 NoArrayExpr = -1,
7055 ArraySubscript = 0,
7056 OMPArraySection = 1
7057 } IsArrayExpr = NoArrayExpr;
7058 if (AllowArraySection) {
7059 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7060 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7061 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7062 Base = TempASE->getBase()->IgnoreParenImpCasts();
7063 RefExpr = Base;
7064 IsArrayExpr = ArraySubscript;
7065 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7066 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7067 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7068 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7069 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7070 Base = TempASE->getBase()->IgnoreParenImpCasts();
7071 RefExpr = Base;
7072 IsArrayExpr = OMPArraySection;
7073 }
7074 }
7075 ELoc = RefExpr->getExprLoc();
7076 ERange = RefExpr->getSourceRange();
7077 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007078 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7079 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7080 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7081 (S.getCurrentThisType().isNull() || !ME ||
7082 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7083 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007084 if (IsArrayExpr != NoArrayExpr)
7085 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7086 << ERange;
7087 else {
7088 S.Diag(ELoc,
7089 AllowArraySection
7090 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7091 : diag::err_omp_expected_var_name_member_expr)
7092 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7093 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007094 return std::make_pair(nullptr, false);
7095 }
7096 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7097}
7098
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007099OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7100 SourceLocation StartLoc,
7101 SourceLocation LParenLoc,
7102 SourceLocation EndLoc) {
7103 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007104 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007105 for (auto &RefExpr : VarList) {
7106 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007107 SourceLocation ELoc;
7108 SourceRange ERange;
7109 Expr *SimpleRefExpr = RefExpr;
7110 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007111 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007112 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007113 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007114 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007115 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007116 ValueDecl *D = Res.first;
7117 if (!D)
7118 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007119
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007120 QualType Type = D->getType();
7121 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007122
7123 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7124 // A variable that appears in a private clause must not have an incomplete
7125 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007126 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007127 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007128 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007129
Alexey Bataev758e55e2013-09-06 18:03:48 +00007130 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7131 // in a Construct]
7132 // Variables with the predetermined data-sharing attributes may not be
7133 // listed in data-sharing attributes clauses, except for the cases
7134 // listed below. For these exceptions only, listing a predetermined
7135 // variable in a data-sharing attribute clause is allowed and overrides
7136 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007137 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007138 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007139 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7140 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007141 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007142 continue;
7143 }
7144
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007145 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007146 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007147 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007148 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7149 << getOpenMPClauseName(OMPC_private) << Type
7150 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7151 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007152 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007153 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007154 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007155 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007156 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007157 continue;
7158 }
7159
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007160 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7161 // A list item cannot appear in both a map clause and a data-sharing
7162 // attribute clause on the same construct
7163 if (DSAStack->getCurrentDirective() == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +00007164 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007165 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007166 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007167 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7168 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7169 ConflictKind = WhereFoundClauseKind;
7170 return true;
7171 })) {
7172 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007173 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007174 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007175 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7176 ReportOriginalDSA(*this, DSAStack, D, DVar);
7177 continue;
7178 }
7179 }
7180
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007181 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7182 // A variable of class type (or array thereof) that appears in a private
7183 // clause requires an accessible, unambiguous default constructor for the
7184 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007185 // Generate helper private variable and initialize it with the default
7186 // value. The address of the original variable is replaced by the address of
7187 // the new private variable in CodeGen. This new variable is not added to
7188 // IdResolver, so the code in the OpenMP region uses original variable for
7189 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007190 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007191 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7192 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007193 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007194 if (VDPrivate->isInvalidDecl())
7195 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007196 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007197 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007198
Alexey Bataev90c228f2016-02-08 09:29:13 +00007199 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007200 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007201 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007202 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007203 Vars.push_back((VD || CurContext->isDependentContext())
7204 ? RefExpr->IgnoreParens()
7205 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007206 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007207 }
7208
Alexey Bataeved09d242014-05-28 05:53:51 +00007209 if (Vars.empty())
7210 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007211
Alexey Bataev03b340a2014-10-21 03:16:40 +00007212 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7213 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007214}
7215
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007216namespace {
7217class DiagsUninitializedSeveretyRAII {
7218private:
7219 DiagnosticsEngine &Diags;
7220 SourceLocation SavedLoc;
7221 bool IsIgnored;
7222
7223public:
7224 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7225 bool IsIgnored)
7226 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7227 if (!IsIgnored) {
7228 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7229 /*Map*/ diag::Severity::Ignored, Loc);
7230 }
7231 }
7232 ~DiagsUninitializedSeveretyRAII() {
7233 if (!IsIgnored)
7234 Diags.popMappings(SavedLoc);
7235 }
7236};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007237}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007238
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007239OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7240 SourceLocation StartLoc,
7241 SourceLocation LParenLoc,
7242 SourceLocation EndLoc) {
7243 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007244 SmallVector<Expr *, 8> PrivateCopies;
7245 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007246 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007247 bool IsImplicitClause =
7248 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7249 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7250
Alexey Bataeved09d242014-05-28 05:53:51 +00007251 for (auto &RefExpr : VarList) {
7252 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007253 SourceLocation ELoc;
7254 SourceRange ERange;
7255 Expr *SimpleRefExpr = RefExpr;
7256 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007257 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007258 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007259 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007260 PrivateCopies.push_back(nullptr);
7261 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007262 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007263 ValueDecl *D = Res.first;
7264 if (!D)
7265 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007266
Alexey Bataev60da77e2016-02-29 05:54:20 +00007267 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007268 QualType Type = D->getType();
7269 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007270
7271 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7272 // A variable that appears in a private clause must not have an incomplete
7273 // type or a reference type.
7274 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007275 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007276 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007277 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007278
7279 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7280 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007281 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007282 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007283 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007284
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007285 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007286 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007287 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007288 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007289 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007290 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007291 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7292 // A list item that specifies a given variable may not appear in more
7293 // than one clause on the same directive, except that a variable may be
7294 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007295 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007296 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007297 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007298 << getOpenMPClauseName(DVar.CKind)
7299 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007300 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007301 continue;
7302 }
7303
7304 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7305 // in a Construct]
7306 // Variables with the predetermined data-sharing attributes may not be
7307 // listed in data-sharing attributes clauses, except for the cases
7308 // listed below. For these exceptions only, listing a predetermined
7309 // variable in a data-sharing attribute clause is allowed and overrides
7310 // the variable's predetermined data-sharing attributes.
7311 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7312 // in a Construct, C/C++, p.2]
7313 // Variables with const-qualified type having no mutable member may be
7314 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007315 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007316 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7317 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007318 << getOpenMPClauseName(DVar.CKind)
7319 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007320 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007321 continue;
7322 }
7323
Alexey Bataevf29276e2014-06-18 04:14:57 +00007324 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007325 // OpenMP [2.9.3.4, Restrictions, p.2]
7326 // A list item that is private within a parallel region must not appear
7327 // in a firstprivate clause on a worksharing construct if any of the
7328 // worksharing regions arising from the worksharing construct ever bind
7329 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007330 if (isOpenMPWorksharingDirective(CurrDir) &&
7331 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007332 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007333 if (DVar.CKind != OMPC_shared &&
7334 (isOpenMPParallelDirective(DVar.DKind) ||
7335 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007336 Diag(ELoc, diag::err_omp_required_access)
7337 << getOpenMPClauseName(OMPC_firstprivate)
7338 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007339 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007340 continue;
7341 }
7342 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007343 // OpenMP [2.9.3.4, Restrictions, p.3]
7344 // A list item that appears in a reduction clause of a parallel construct
7345 // must not appear in a firstprivate clause on a worksharing or task
7346 // construct if any of the worksharing or task regions arising from the
7347 // worksharing or task construct ever bind to any of the parallel regions
7348 // arising from the parallel construct.
7349 // OpenMP [2.9.3.4, Restrictions, p.4]
7350 // A list item that appears in a reduction clause in worksharing
7351 // construct must not appear in a firstprivate clause in a task construct
7352 // encountered during execution of any of the worksharing regions arising
7353 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007354 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007355 DVar = DSAStack->hasInnermostDSA(
7356 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7357 [](OpenMPDirectiveKind K) -> bool {
7358 return isOpenMPParallelDirective(K) ||
7359 isOpenMPWorksharingDirective(K);
7360 },
7361 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007362 if (DVar.CKind == OMPC_reduction &&
7363 (isOpenMPParallelDirective(DVar.DKind) ||
7364 isOpenMPWorksharingDirective(DVar.DKind))) {
7365 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7366 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007367 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007368 continue;
7369 }
7370 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007371
7372 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7373 // A list item that is private within a teams region must not appear in a
7374 // firstprivate clause on a distribute construct if any of the distribute
7375 // regions arising from the distribute construct ever bind to any of the
7376 // teams regions arising from the teams construct.
7377 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7378 // A list item that appears in a reduction clause of a teams construct
7379 // must not appear in a firstprivate clause on a distribute construct if
7380 // any of the distribute regions arising from the distribute construct
7381 // ever bind to any of the teams regions arising from the teams construct.
7382 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7383 // A list item may appear in a firstprivate or lastprivate clause but not
7384 // both.
7385 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007386 DVar = DSAStack->hasInnermostDSA(
7387 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7388 [](OpenMPDirectiveKind K) -> bool {
7389 return isOpenMPTeamsDirective(K);
7390 },
7391 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007392 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7393 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007394 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007395 continue;
7396 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007397 DVar = DSAStack->hasInnermostDSA(
7398 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7399 [](OpenMPDirectiveKind K) -> bool {
7400 return isOpenMPTeamsDirective(K);
7401 },
7402 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007403 if (DVar.CKind == OMPC_reduction &&
7404 isOpenMPTeamsDirective(DVar.DKind)) {
7405 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007406 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007407 continue;
7408 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007409 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007410 if (DVar.CKind == OMPC_lastprivate) {
7411 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007412 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007413 continue;
7414 }
7415 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007416 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7417 // A list item cannot appear in both a map clause and a data-sharing
7418 // attribute clause on the same construct
7419 if (CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +00007420 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007421 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007422 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007423 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7424 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7425 ConflictKind = WhereFoundClauseKind;
7426 return true;
7427 })) {
7428 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007429 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007430 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007431 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7432 ReportOriginalDSA(*this, DSAStack, D, DVar);
7433 continue;
7434 }
7435 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007436 }
7437
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007438 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007439 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007440 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007441 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7442 << getOpenMPClauseName(OMPC_firstprivate) << Type
7443 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7444 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007445 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007446 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007447 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007448 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007449 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007450 continue;
7451 }
7452
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007453 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007454 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7455 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007456 // Generate helper private variable and initialize it with the value of the
7457 // original variable. The address of the original variable is replaced by
7458 // the address of the new private variable in the CodeGen. This new variable
7459 // is not added to IdResolver, so the code in the OpenMP region uses
7460 // original variable for proper diagnostics and variable capturing.
7461 Expr *VDInitRefExpr = nullptr;
7462 // For arrays generate initializer for single element and replace it by the
7463 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007464 if (Type->isArrayType()) {
7465 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007466 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007467 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007468 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007469 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007470 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007471 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007472 InitializedEntity Entity =
7473 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007474 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7475
7476 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7477 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7478 if (Result.isInvalid())
7479 VDPrivate->setInvalidDecl();
7480 else
7481 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007482 // Remove temp variable declaration.
7483 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007484 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007485 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7486 ".firstprivate.temp");
7487 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7488 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007489 AddInitializerToDecl(VDPrivate,
7490 DefaultLvalueConversion(VDInitRefExpr).get(),
7491 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007492 }
7493 if (VDPrivate->isInvalidDecl()) {
7494 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007495 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007496 diag::note_omp_task_predetermined_firstprivate_here);
7497 }
7498 continue;
7499 }
7500 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007501 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007502 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7503 RefExpr->getExprLoc());
7504 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007505 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007506 if (TopDVar.CKind == OMPC_lastprivate)
7507 Ref = TopDVar.PrivateCopy;
7508 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007509 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007510 if (!IsOpenMPCapturedDecl(D))
7511 ExprCaptures.push_back(Ref->getDecl());
7512 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007513 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007514 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007515 Vars.push_back((VD || CurContext->isDependentContext())
7516 ? RefExpr->IgnoreParens()
7517 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007518 PrivateCopies.push_back(VDPrivateRefExpr);
7519 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007520 }
7521
Alexey Bataeved09d242014-05-28 05:53:51 +00007522 if (Vars.empty())
7523 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007524
7525 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007526 Vars, PrivateCopies, Inits,
7527 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007528}
7529
Alexander Musman1bb328c2014-06-04 13:06:39 +00007530OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7531 SourceLocation StartLoc,
7532 SourceLocation LParenLoc,
7533 SourceLocation EndLoc) {
7534 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007535 SmallVector<Expr *, 8> SrcExprs;
7536 SmallVector<Expr *, 8> DstExprs;
7537 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007538 SmallVector<Decl *, 4> ExprCaptures;
7539 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007540 for (auto &RefExpr : VarList) {
7541 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007542 SourceLocation ELoc;
7543 SourceRange ERange;
7544 Expr *SimpleRefExpr = RefExpr;
7545 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007546 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007547 // It will be analyzed later.
7548 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007549 SrcExprs.push_back(nullptr);
7550 DstExprs.push_back(nullptr);
7551 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007552 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007553 ValueDecl *D = Res.first;
7554 if (!D)
7555 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007556
Alexey Bataev74caaf22016-02-20 04:09:36 +00007557 QualType Type = D->getType();
7558 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007559
7560 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7561 // A variable that appears in a lastprivate clause must not have an
7562 // incomplete type or a reference type.
7563 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007564 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007565 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007566 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007567
7568 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7569 // in a Construct]
7570 // Variables with the predetermined data-sharing attributes may not be
7571 // listed in data-sharing attributes clauses, except for the cases
7572 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007573 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007574 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7575 DVar.CKind != OMPC_firstprivate &&
7576 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7577 Diag(ELoc, diag::err_omp_wrong_dsa)
7578 << getOpenMPClauseName(DVar.CKind)
7579 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007580 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007581 continue;
7582 }
7583
Alexey Bataevf29276e2014-06-18 04:14:57 +00007584 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7585 // OpenMP [2.14.3.5, Restrictions, p.2]
7586 // A list item that is private within a parallel region, or that appears in
7587 // the reduction clause of a parallel construct, must not appear in a
7588 // lastprivate clause on a worksharing construct if any of the corresponding
7589 // worksharing regions ever binds to any of the corresponding parallel
7590 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007591 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007592 if (isOpenMPWorksharingDirective(CurrDir) &&
7593 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007594 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007595 if (DVar.CKind != OMPC_shared) {
7596 Diag(ELoc, diag::err_omp_required_access)
7597 << getOpenMPClauseName(OMPC_lastprivate)
7598 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007599 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007600 continue;
7601 }
7602 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007603
7604 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7605 // A list item may appear in a firstprivate or lastprivate clause but not
7606 // both.
7607 if (CurrDir == OMPD_distribute) {
7608 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7609 if (DVar.CKind == OMPC_firstprivate) {
7610 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7611 ReportOriginalDSA(*this, DSAStack, D, DVar);
7612 continue;
7613 }
7614 }
7615
Alexander Musman1bb328c2014-06-04 13:06:39 +00007616 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007617 // A variable of class type (or array thereof) that appears in a
7618 // lastprivate clause requires an accessible, unambiguous default
7619 // constructor for the class type, unless the list item is also specified
7620 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007621 // A variable of class type (or array thereof) that appears in a
7622 // lastprivate clause requires an accessible, unambiguous copy assignment
7623 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007624 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007625 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007626 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007627 D->hasAttrs() ? &D->getAttrs() : nullptr);
7628 auto *PseudoSrcExpr =
7629 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007630 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007631 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007632 D->hasAttrs() ? &D->getAttrs() : nullptr);
7633 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007634 // For arrays generate assignment operation for single element and replace
7635 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007636 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007637 PseudoDstExpr, PseudoSrcExpr);
7638 if (AssignmentOp.isInvalid())
7639 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007640 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007641 /*DiscardedValue=*/true);
7642 if (AssignmentOp.isInvalid())
7643 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007644
Alexey Bataev74caaf22016-02-20 04:09:36 +00007645 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007646 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007647 if (TopDVar.CKind == OMPC_firstprivate)
7648 Ref = TopDVar.PrivateCopy;
7649 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007650 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007651 if (!IsOpenMPCapturedDecl(D))
7652 ExprCaptures.push_back(Ref->getDecl());
7653 }
7654 if (TopDVar.CKind == OMPC_firstprivate ||
7655 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007656 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007657 ExprResult RefRes = DefaultLvalueConversion(Ref);
7658 if (!RefRes.isUsable())
7659 continue;
7660 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007661 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7662 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007663 if (!PostUpdateRes.isUsable())
7664 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00007665 ExprPostUpdates.push_back(
7666 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007667 }
7668 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007669 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007670 Vars.push_back((VD || CurContext->isDependentContext())
7671 ? RefExpr->IgnoreParens()
7672 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00007673 SrcExprs.push_back(PseudoSrcExpr);
7674 DstExprs.push_back(PseudoDstExpr);
7675 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00007676 }
7677
7678 if (Vars.empty())
7679 return nullptr;
7680
7681 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00007682 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007683 buildPreInits(Context, ExprCaptures),
7684 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00007685}
7686
Alexey Bataev758e55e2013-09-06 18:03:48 +00007687OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7688 SourceLocation StartLoc,
7689 SourceLocation LParenLoc,
7690 SourceLocation EndLoc) {
7691 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00007692 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007693 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007694 SourceLocation ELoc;
7695 SourceRange ERange;
7696 Expr *SimpleRefExpr = RefExpr;
7697 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007698 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00007699 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007700 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007701 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007702 ValueDecl *D = Res.first;
7703 if (!D)
7704 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007705
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007706 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007707 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7708 // in a Construct]
7709 // Variables with the predetermined data-sharing attributes may not be
7710 // listed in data-sharing attributes clauses, except for the cases
7711 // listed below. For these exceptions only, listing a predetermined
7712 // variable in a data-sharing attribute clause is allowed and overrides
7713 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007714 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00007715 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7716 DVar.RefExpr) {
7717 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7718 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007719 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007720 continue;
7721 }
7722
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007723 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007724 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007725 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007726 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007727 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7728 ? RefExpr->IgnoreParens()
7729 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007730 }
7731
Alexey Bataeved09d242014-05-28 05:53:51 +00007732 if (Vars.empty())
7733 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007734
7735 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7736}
7737
Alexey Bataevc5e02582014-06-16 07:08:35 +00007738namespace {
7739class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7740 DSAStackTy *Stack;
7741
7742public:
7743 bool VisitDeclRefExpr(DeclRefExpr *E) {
7744 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007745 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007746 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7747 return false;
7748 if (DVar.CKind != OMPC_unknown)
7749 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007750 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7751 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7752 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007753 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00007754 return true;
7755 return false;
7756 }
7757 return false;
7758 }
7759 bool VisitStmt(Stmt *S) {
7760 for (auto Child : S->children()) {
7761 if (Child && Visit(Child))
7762 return true;
7763 }
7764 return false;
7765 }
Alexey Bataev23b69422014-06-18 07:08:49 +00007766 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00007767};
Alexey Bataev23b69422014-06-18 07:08:49 +00007768} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00007769
Alexey Bataev60da77e2016-02-29 05:54:20 +00007770namespace {
7771// Transform MemberExpression for specified FieldDecl of current class to
7772// DeclRefExpr to specified OMPCapturedExprDecl.
7773class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
7774 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
7775 ValueDecl *Field;
7776 DeclRefExpr *CapturedExpr;
7777
7778public:
7779 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
7780 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
7781
7782 ExprResult TransformMemberExpr(MemberExpr *E) {
7783 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
7784 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00007785 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00007786 return CapturedExpr;
7787 }
7788 return BaseTransform::TransformMemberExpr(E);
7789 }
7790 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
7791};
7792} // namespace
7793
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007794template <typename T>
7795static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
7796 const llvm::function_ref<T(ValueDecl *)> &Gen) {
7797 for (auto &Set : Lookups) {
7798 for (auto *D : Set) {
7799 if (auto Res = Gen(cast<ValueDecl>(D)))
7800 return Res;
7801 }
7802 }
7803 return T();
7804}
7805
7806static ExprResult
7807buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
7808 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
7809 const DeclarationNameInfo &ReductionId, QualType Ty,
7810 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
7811 if (ReductionIdScopeSpec.isInvalid())
7812 return ExprError();
7813 SmallVector<UnresolvedSet<8>, 4> Lookups;
7814 if (S) {
7815 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
7816 Lookup.suppressDiagnostics();
7817 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
7818 auto *D = Lookup.getRepresentativeDecl();
7819 do {
7820 S = S->getParent();
7821 } while (S && !S->isDeclScope(D));
7822 if (S)
7823 S = S->getParent();
7824 Lookups.push_back(UnresolvedSet<8>());
7825 Lookups.back().append(Lookup.begin(), Lookup.end());
7826 Lookup.clear();
7827 }
7828 } else if (auto *ULE =
7829 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
7830 Lookups.push_back(UnresolvedSet<8>());
7831 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00007832 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007833 if (D == PrevD)
7834 Lookups.push_back(UnresolvedSet<8>());
7835 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
7836 Lookups.back().addDecl(DRD);
7837 PrevD = D;
7838 }
7839 }
7840 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
7841 Ty->containsUnexpandedParameterPack() ||
7842 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
7843 return !D->isInvalidDecl() &&
7844 (D->getType()->isDependentType() ||
7845 D->getType()->isInstantiationDependentType() ||
7846 D->getType()->containsUnexpandedParameterPack());
7847 })) {
7848 UnresolvedSet<8> ResSet;
7849 for (auto &Set : Lookups) {
7850 ResSet.append(Set.begin(), Set.end());
7851 // The last item marks the end of all declarations at the specified scope.
7852 ResSet.addDecl(Set[Set.size() - 1]);
7853 }
7854 return UnresolvedLookupExpr::Create(
7855 SemaRef.Context, /*NamingClass=*/nullptr,
7856 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
7857 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
7858 }
7859 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7860 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
7861 if (!D->isInvalidDecl() &&
7862 SemaRef.Context.hasSameType(D->getType(), Ty))
7863 return D;
7864 return nullptr;
7865 }))
7866 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7867 if (auto *VD = filterLookupForUDR<ValueDecl *>(
7868 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
7869 if (!D->isInvalidDecl() &&
7870 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
7871 !Ty.isMoreQualifiedThan(D->getType()))
7872 return D;
7873 return nullptr;
7874 })) {
7875 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7876 /*DetectVirtual=*/false);
7877 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
7878 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
7879 VD->getType().getUnqualifiedType()))) {
7880 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
7881 /*DiagID=*/0) !=
7882 Sema::AR_inaccessible) {
7883 SemaRef.BuildBasePathArray(Paths, BasePath);
7884 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7885 }
7886 }
7887 }
7888 }
7889 if (ReductionIdScopeSpec.isSet()) {
7890 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
7891 return ExprError();
7892 }
7893 return ExprEmpty();
7894}
7895
Alexey Bataevc5e02582014-06-16 07:08:35 +00007896OMPClause *Sema::ActOnOpenMPReductionClause(
7897 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7898 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007899 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
7900 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00007901 auto DN = ReductionId.getName();
7902 auto OOK = DN.getCXXOverloadedOperator();
7903 BinaryOperatorKind BOK = BO_Comma;
7904
7905 // OpenMP [2.14.3.6, reduction clause]
7906 // C
7907 // reduction-identifier is either an identifier or one of the following
7908 // operators: +, -, *, &, |, ^, && and ||
7909 // C++
7910 // reduction-identifier is either an id-expression or one of the following
7911 // operators: +, -, *, &, |, ^, && and ||
7912 // FIXME: Only 'min' and 'max' identifiers are supported for now.
7913 switch (OOK) {
7914 case OO_Plus:
7915 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007916 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007917 break;
7918 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007919 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007920 break;
7921 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007922 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007923 break;
7924 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007925 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007926 break;
7927 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007928 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007929 break;
7930 case OO_AmpAmp:
7931 BOK = BO_LAnd;
7932 break;
7933 case OO_PipePipe:
7934 BOK = BO_LOr;
7935 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007936 case OO_New:
7937 case OO_Delete:
7938 case OO_Array_New:
7939 case OO_Array_Delete:
7940 case OO_Slash:
7941 case OO_Percent:
7942 case OO_Tilde:
7943 case OO_Exclaim:
7944 case OO_Equal:
7945 case OO_Less:
7946 case OO_Greater:
7947 case OO_LessEqual:
7948 case OO_GreaterEqual:
7949 case OO_PlusEqual:
7950 case OO_MinusEqual:
7951 case OO_StarEqual:
7952 case OO_SlashEqual:
7953 case OO_PercentEqual:
7954 case OO_CaretEqual:
7955 case OO_AmpEqual:
7956 case OO_PipeEqual:
7957 case OO_LessLess:
7958 case OO_GreaterGreater:
7959 case OO_LessLessEqual:
7960 case OO_GreaterGreaterEqual:
7961 case OO_EqualEqual:
7962 case OO_ExclaimEqual:
7963 case OO_PlusPlus:
7964 case OO_MinusMinus:
7965 case OO_Comma:
7966 case OO_ArrowStar:
7967 case OO_Arrow:
7968 case OO_Call:
7969 case OO_Subscript:
7970 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00007971 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007972 case NUM_OVERLOADED_OPERATORS:
7973 llvm_unreachable("Unexpected reduction identifier");
7974 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007975 if (auto II = DN.getAsIdentifierInfo()) {
7976 if (II->isStr("max"))
7977 BOK = BO_GT;
7978 else if (II->isStr("min"))
7979 BOK = BO_LT;
7980 }
7981 break;
7982 }
7983 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007984 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00007985 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00007986 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00007987
7988 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007989 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00007990 SmallVector<Expr *, 8> LHSs;
7991 SmallVector<Expr *, 8> RHSs;
7992 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00007993 SmallVector<Decl *, 4> ExprCaptures;
7994 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007995 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
7996 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007997 for (auto RefExpr : VarList) {
7998 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00007999 // OpenMP [2.1, C/C++]
8000 // A list item is a variable or array section, subject to the restrictions
8001 // specified in Section 2.4 on page 42 and in each of the sections
8002 // describing clauses and directives for which a list appears.
8003 // OpenMP [2.14.3.3, Restrictions, p.1]
8004 // A variable that is part of another variable (as an array or
8005 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008006 if (!FirstIter && IR != ER)
8007 ++IR;
8008 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008009 SourceLocation ELoc;
8010 SourceRange ERange;
8011 Expr *SimpleRefExpr = RefExpr;
8012 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8013 /*AllowArraySection=*/true);
8014 if (Res.second) {
8015 // It will be analyzed later.
8016 Vars.push_back(RefExpr);
8017 Privates.push_back(nullptr);
8018 LHSs.push_back(nullptr);
8019 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008020 // Try to find 'declare reduction' corresponding construct before using
8021 // builtin/overloaded operators.
8022 QualType Type = Context.DependentTy;
8023 CXXCastPath BasePath;
8024 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8025 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8026 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8027 if (CurContext->isDependentContext() &&
8028 (DeclareReductionRef.isUnset() ||
8029 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8030 ReductionOps.push_back(DeclareReductionRef.get());
8031 else
8032 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008033 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008034 ValueDecl *D = Res.first;
8035 if (!D)
8036 continue;
8037
Alexey Bataeva1764212015-09-30 09:22:36 +00008038 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008039 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8040 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8041 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008042 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008043 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008044 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8045 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8046 Type = ATy->getElementType();
8047 else
8048 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008049 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008050 } else
8051 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8052 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008053
Alexey Bataevc5e02582014-06-16 07:08:35 +00008054 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8055 // A variable that appears in a private clause must not have an incomplete
8056 // type or a reference type.
8057 if (RequireCompleteType(ELoc, Type,
8058 diag::err_omp_reduction_incomplete_type))
8059 continue;
8060 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008061 // A list item that appears in a reduction clause must not be
8062 // const-qualified.
8063 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008064 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008065 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008066 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008067 bool IsDecl = !VD ||
8068 VD->isThisDeclarationADefinition(Context) ==
8069 VarDecl::DeclarationOnly;
8070 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008071 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008072 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008073 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008074 continue;
8075 }
8076 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8077 // If a list-item is a reference type then it must bind to the same object
8078 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008079 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008080 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008081 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008082 DSARefChecker Check(DSAStack);
8083 if (Check.Visit(VDDef->getInit())) {
8084 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8085 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8086 continue;
8087 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008088 }
8089 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008090
Alexey Bataevc5e02582014-06-16 07:08:35 +00008091 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8092 // in a Construct]
8093 // Variables with the predetermined data-sharing attributes may not be
8094 // listed in data-sharing attributes clauses, except for the cases
8095 // listed below. For these exceptions only, listing a predetermined
8096 // variable in a data-sharing attribute clause is allowed and overrides
8097 // the variable's predetermined data-sharing attributes.
8098 // OpenMP [2.14.3.6, Restrictions, p.3]
8099 // Any number of reduction clauses can be specified on the directive,
8100 // but a list item can appear only once in the reduction clauses for that
8101 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008102 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008103 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008104 if (DVar.CKind == OMPC_reduction) {
8105 Diag(ELoc, diag::err_omp_once_referenced)
8106 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008107 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008108 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008109 } else if (DVar.CKind != OMPC_unknown) {
8110 Diag(ELoc, diag::err_omp_wrong_dsa)
8111 << getOpenMPClauseName(DVar.CKind)
8112 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008113 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008114 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008115 }
8116
8117 // OpenMP [2.14.3.6, Restrictions, p.1]
8118 // A list item that appears in a reduction clause of a worksharing
8119 // construct must be shared in the parallel regions to which any of the
8120 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008121 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8122 if (isOpenMPWorksharingDirective(CurrDir) &&
8123 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008124 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008125 if (DVar.CKind != OMPC_shared) {
8126 Diag(ELoc, diag::err_omp_required_access)
8127 << getOpenMPClauseName(OMPC_reduction)
8128 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008129 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008130 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008131 }
8132 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008133
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008134 // Try to find 'declare reduction' corresponding construct before using
8135 // builtin/overloaded operators.
8136 CXXCastPath BasePath;
8137 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8138 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8139 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8140 if (DeclareReductionRef.isInvalid())
8141 continue;
8142 if (CurContext->isDependentContext() &&
8143 (DeclareReductionRef.isUnset() ||
8144 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8145 Vars.push_back(RefExpr);
8146 Privates.push_back(nullptr);
8147 LHSs.push_back(nullptr);
8148 RHSs.push_back(nullptr);
8149 ReductionOps.push_back(DeclareReductionRef.get());
8150 continue;
8151 }
8152 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8153 // Not allowed reduction identifier is found.
8154 Diag(ReductionId.getLocStart(),
8155 diag::err_omp_unknown_reduction_identifier)
8156 << Type << ReductionIdRange;
8157 continue;
8158 }
8159
8160 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8161 // The type of a list item that appears in a reduction clause must be valid
8162 // for the reduction-identifier. For a max or min reduction in C, the type
8163 // of the list item must be an allowed arithmetic data type: char, int,
8164 // float, double, or _Bool, possibly modified with long, short, signed, or
8165 // unsigned. For a max or min reduction in C++, the type of the list item
8166 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8167 // double, or bool, possibly modified with long, short, signed, or unsigned.
8168 if (DeclareReductionRef.isUnset()) {
8169 if ((BOK == BO_GT || BOK == BO_LT) &&
8170 !(Type->isScalarType() ||
8171 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8172 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8173 << getLangOpts().CPlusPlus;
8174 if (!ASE && !OASE) {
8175 bool IsDecl = !VD ||
8176 VD->isThisDeclarationADefinition(Context) ==
8177 VarDecl::DeclarationOnly;
8178 Diag(D->getLocation(),
8179 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8180 << D;
8181 }
8182 continue;
8183 }
8184 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8185 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8186 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8187 if (!ASE && !OASE) {
8188 bool IsDecl = !VD ||
8189 VD->isThisDeclarationADefinition(Context) ==
8190 VarDecl::DeclarationOnly;
8191 Diag(D->getLocation(),
8192 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8193 << D;
8194 }
8195 continue;
8196 }
8197 }
8198
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008199 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008200 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008201 D->hasAttrs() ? &D->getAttrs() : nullptr);
8202 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8203 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008204 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008205 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008206 (!ASE &&
8207 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008208 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008209 // Create pseudo array type for private copy. The size for this array will
8210 // be generated during codegen.
8211 // For array subscripts or single variables Private Ty is the same as Type
8212 // (type of the variable or single array element).
8213 PrivateTy = Context.getVariableArrayType(
8214 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8215 Context.getSizeType(), VK_RValue),
8216 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008217 } else if (!ASE && !OASE &&
8218 Context.getAsArrayType(D->getType().getNonReferenceType()))
8219 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008220 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008221 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8222 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008223 // Add initializer for private variable.
8224 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008225 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8226 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8227 if (DeclareReductionRef.isUsable()) {
8228 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8229 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8230 if (DRD->getInitializer()) {
8231 Init = DRDRef;
8232 RHSVD->setInit(DRDRef);
8233 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008234 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008235 } else {
8236 switch (BOK) {
8237 case BO_Add:
8238 case BO_Xor:
8239 case BO_Or:
8240 case BO_LOr:
8241 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8242 if (Type->isScalarType() || Type->isAnyComplexType())
8243 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8244 break;
8245 case BO_Mul:
8246 case BO_LAnd:
8247 if (Type->isScalarType() || Type->isAnyComplexType()) {
8248 // '*' and '&&' reduction ops - initializer is '1'.
8249 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008250 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008251 break;
8252 case BO_And: {
8253 // '&' reduction op - initializer is '~0'.
8254 QualType OrigType = Type;
8255 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8256 Type = ComplexTy->getElementType();
8257 if (Type->isRealFloatingType()) {
8258 llvm::APFloat InitValue =
8259 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8260 /*isIEEE=*/true);
8261 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8262 Type, ELoc);
8263 } else if (Type->isScalarType()) {
8264 auto Size = Context.getTypeSize(Type);
8265 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8266 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8267 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8268 }
8269 if (Init && OrigType->isAnyComplexType()) {
8270 // Init = 0xFFFF + 0xFFFFi;
8271 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8272 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8273 }
8274 Type = OrigType;
8275 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008276 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008277 case BO_LT:
8278 case BO_GT: {
8279 // 'min' reduction op - initializer is 'Largest representable number in
8280 // the reduction list item type'.
8281 // 'max' reduction op - initializer is 'Least representable number in
8282 // the reduction list item type'.
8283 if (Type->isIntegerType() || Type->isPointerType()) {
8284 bool IsSigned = Type->hasSignedIntegerRepresentation();
8285 auto Size = Context.getTypeSize(Type);
8286 QualType IntTy =
8287 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8288 llvm::APInt InitValue =
8289 (BOK != BO_LT)
8290 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8291 : llvm::APInt::getMinValue(Size)
8292 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8293 : llvm::APInt::getMaxValue(Size);
8294 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8295 if (Type->isPointerType()) {
8296 // Cast to pointer type.
8297 auto CastExpr = BuildCStyleCastExpr(
8298 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8299 SourceLocation(), Init);
8300 if (CastExpr.isInvalid())
8301 continue;
8302 Init = CastExpr.get();
8303 }
8304 } else if (Type->isRealFloatingType()) {
8305 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8306 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8307 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8308 Type, ELoc);
8309 }
8310 break;
8311 }
8312 case BO_PtrMemD:
8313 case BO_PtrMemI:
8314 case BO_MulAssign:
8315 case BO_Div:
8316 case BO_Rem:
8317 case BO_Sub:
8318 case BO_Shl:
8319 case BO_Shr:
8320 case BO_LE:
8321 case BO_GE:
8322 case BO_EQ:
8323 case BO_NE:
8324 case BO_AndAssign:
8325 case BO_XorAssign:
8326 case BO_OrAssign:
8327 case BO_Assign:
8328 case BO_AddAssign:
8329 case BO_SubAssign:
8330 case BO_DivAssign:
8331 case BO_RemAssign:
8332 case BO_ShlAssign:
8333 case BO_ShrAssign:
8334 case BO_Comma:
8335 llvm_unreachable("Unexpected reduction operation");
8336 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008337 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008338 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008339 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8340 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008341 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008342 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008343 if (RHSVD->isInvalidDecl())
8344 continue;
8345 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008346 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8347 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008348 bool IsDecl =
8349 !VD ||
8350 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8351 Diag(D->getLocation(),
8352 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8353 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008354 continue;
8355 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008356 // Store initializer for single element in private copy. Will be used during
8357 // codegen.
8358 PrivateVD->setInit(RHSVD->getInit());
8359 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008360 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008361 ExprResult ReductionOp;
8362 if (DeclareReductionRef.isUsable()) {
8363 QualType RedTy = DeclareReductionRef.get()->getType();
8364 QualType PtrRedTy = Context.getPointerType(RedTy);
8365 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8366 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8367 if (!BasePath.empty()) {
8368 LHS = DefaultLvalueConversion(LHS.get());
8369 RHS = DefaultLvalueConversion(RHS.get());
8370 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8371 CK_UncheckedDerivedToBase, LHS.get(),
8372 &BasePath, LHS.get()->getValueKind());
8373 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8374 CK_UncheckedDerivedToBase, RHS.get(),
8375 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008376 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008377 FunctionProtoType::ExtProtoInfo EPI;
8378 QualType Params[] = {PtrRedTy, PtrRedTy};
8379 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8380 auto *OVE = new (Context) OpaqueValueExpr(
8381 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8382 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8383 Expr *Args[] = {LHS.get(), RHS.get()};
8384 ReductionOp = new (Context)
8385 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8386 } else {
8387 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8388 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8389 if (ReductionOp.isUsable()) {
8390 if (BOK != BO_LT && BOK != BO_GT) {
8391 ReductionOp =
8392 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8393 BO_Assign, LHSDRE, ReductionOp.get());
8394 } else {
8395 auto *ConditionalOp = new (Context) ConditionalOperator(
8396 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8397 RHSDRE, Type, VK_LValue, OK_Ordinary);
8398 ReductionOp =
8399 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8400 BO_Assign, LHSDRE, ConditionalOp);
8401 }
8402 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8403 }
8404 if (ReductionOp.isInvalid())
8405 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008406 }
8407
Alexey Bataev60da77e2016-02-29 05:54:20 +00008408 DeclRefExpr *Ref = nullptr;
8409 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008410 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008411 if (ASE || OASE) {
8412 TransformExprToCaptures RebuildToCapture(*this, D);
8413 VarsExpr =
8414 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8415 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008416 } else {
8417 VarsExpr = Ref =
8418 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008419 }
8420 if (!IsOpenMPCapturedDecl(D)) {
8421 ExprCaptures.push_back(Ref->getDecl());
8422 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8423 ExprResult RefRes = DefaultLvalueConversion(Ref);
8424 if (!RefRes.isUsable())
8425 continue;
8426 ExprResult PostUpdateRes =
8427 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8428 SimpleRefExpr, RefRes.get());
8429 if (!PostUpdateRes.isUsable())
8430 continue;
8431 ExprPostUpdates.push_back(
8432 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008433 }
8434 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008435 }
8436 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8437 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008438 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008439 LHSs.push_back(LHSDRE);
8440 RHSs.push_back(RHSDRE);
8441 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008442 }
8443
8444 if (Vars.empty())
8445 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008446
Alexey Bataevc5e02582014-06-16 07:08:35 +00008447 return OMPReductionClause::Create(
8448 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008449 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008450 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8451 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008452}
8453
Alexey Bataevecba70f2016-04-12 11:02:11 +00008454bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8455 SourceLocation LinLoc) {
8456 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8457 LinKind == OMPC_LINEAR_unknown) {
8458 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8459 return true;
8460 }
8461 return false;
8462}
8463
8464bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8465 OpenMPLinearClauseKind LinKind,
8466 QualType Type) {
8467 auto *VD = dyn_cast_or_null<VarDecl>(D);
8468 // A variable must not have an incomplete type or a reference type.
8469 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8470 return true;
8471 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8472 !Type->isReferenceType()) {
8473 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8474 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8475 return true;
8476 }
8477 Type = Type.getNonReferenceType();
8478
8479 // A list item must not be const-qualified.
8480 if (Type.isConstant(Context)) {
8481 Diag(ELoc, diag::err_omp_const_variable)
8482 << getOpenMPClauseName(OMPC_linear);
8483 if (D) {
8484 bool IsDecl =
8485 !VD ||
8486 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8487 Diag(D->getLocation(),
8488 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8489 << D;
8490 }
8491 return true;
8492 }
8493
8494 // A list item must be of integral or pointer type.
8495 Type = Type.getUnqualifiedType().getCanonicalType();
8496 const auto *Ty = Type.getTypePtrOrNull();
8497 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8498 !Ty->isPointerType())) {
8499 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8500 if (D) {
8501 bool IsDecl =
8502 !VD ||
8503 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8504 Diag(D->getLocation(),
8505 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8506 << D;
8507 }
8508 return true;
8509 }
8510 return false;
8511}
8512
Alexey Bataev182227b2015-08-20 10:54:39 +00008513OMPClause *Sema::ActOnOpenMPLinearClause(
8514 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8515 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8516 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008517 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008518 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008519 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008520 SmallVector<Decl *, 4> ExprCaptures;
8521 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008522 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008523 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008524 for (auto &RefExpr : VarList) {
8525 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008526 SourceLocation ELoc;
8527 SourceRange ERange;
8528 Expr *SimpleRefExpr = RefExpr;
8529 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8530 /*AllowArraySection=*/false);
8531 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008532 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008533 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008534 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008535 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008536 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008537 ValueDecl *D = Res.first;
8538 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008539 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008540
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008541 QualType Type = D->getType();
8542 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008543
8544 // OpenMP [2.14.3.7, linear clause]
8545 // A list-item cannot appear in more than one linear clause.
8546 // A list-item that appears in a linear clause cannot appear in any
8547 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008548 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008549 if (DVar.RefExpr) {
8550 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8551 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008552 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008553 continue;
8554 }
8555
Alexey Bataevecba70f2016-04-12 11:02:11 +00008556 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008557 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008558 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008559
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008560 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008561 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8562 D->hasAttrs() ? &D->getAttrs() : nullptr);
8563 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008564 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008565 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008566 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008567 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008568 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008569 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8570 if (!IsOpenMPCapturedDecl(D)) {
8571 ExprCaptures.push_back(Ref->getDecl());
8572 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8573 ExprResult RefRes = DefaultLvalueConversion(Ref);
8574 if (!RefRes.isUsable())
8575 continue;
8576 ExprResult PostUpdateRes =
8577 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8578 SimpleRefExpr, RefRes.get());
8579 if (!PostUpdateRes.isUsable())
8580 continue;
8581 ExprPostUpdates.push_back(
8582 IgnoredValueConversions(PostUpdateRes.get()).get());
8583 }
8584 }
8585 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008586 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008587 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008588 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008589 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008590 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008591 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8592 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8593
8594 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008595 Vars.push_back((VD || CurContext->isDependentContext())
8596 ? RefExpr->IgnoreParens()
8597 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008598 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008599 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008600 }
8601
8602 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008603 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008604
8605 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008606 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008607 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8608 !Step->isInstantiationDependent() &&
8609 !Step->containsUnexpandedParameterPack()) {
8610 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008611 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008612 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008613 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008614 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008615
Alexander Musman3276a272015-03-21 10:12:56 +00008616 // Build var to save the step value.
8617 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008618 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008619 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008620 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008621 ExprResult CalcStep =
8622 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008623 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008624
Alexander Musman8dba6642014-04-22 13:09:42 +00008625 // Warn about zero linear step (it would be probably better specified as
8626 // making corresponding variables 'const').
8627 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008628 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8629 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008630 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8631 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008632 if (!IsConstant && CalcStep.isUsable()) {
8633 // Calculate the step beforehand instead of doing this on each iteration.
8634 // (This is not used if the number of iterations may be kfold-ed).
8635 CalcStepExpr = CalcStep.get();
8636 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008637 }
8638
Alexey Bataev182227b2015-08-20 10:54:39 +00008639 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8640 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008641 StepExpr, CalcStepExpr,
8642 buildPreInits(Context, ExprCaptures),
8643 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008644}
8645
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008646static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8647 Expr *NumIterations, Sema &SemaRef,
8648 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008649 // Walk the vars and build update/final expressions for the CodeGen.
8650 SmallVector<Expr *, 8> Updates;
8651 SmallVector<Expr *, 8> Finals;
8652 Expr *Step = Clause.getStep();
8653 Expr *CalcStep = Clause.getCalcStep();
8654 // OpenMP [2.14.3.7, linear clause]
8655 // If linear-step is not specified it is assumed to be 1.
8656 if (Step == nullptr)
8657 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008658 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00008659 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008660 }
Alexander Musman3276a272015-03-21 10:12:56 +00008661 bool HasErrors = false;
8662 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008663 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008664 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00008665 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008666 SourceLocation ELoc;
8667 SourceRange ERange;
8668 Expr *SimpleRefExpr = RefExpr;
8669 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8670 /*AllowArraySection=*/false);
8671 ValueDecl *D = Res.first;
8672 if (Res.second || !D) {
8673 Updates.push_back(nullptr);
8674 Finals.push_back(nullptr);
8675 HasErrors = true;
8676 continue;
8677 }
8678 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8679 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8680 ->getMemberDecl();
8681 }
8682 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00008683 Expr *InitExpr = *CurInit;
8684
8685 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00008686 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008687 Expr *CapturedRef;
8688 if (LinKind == OMPC_LINEAR_uval)
8689 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8690 else
8691 CapturedRef =
8692 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8693 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8694 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008695
8696 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008697 ExprResult Update;
8698 if (!Info.first) {
8699 Update =
8700 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8701 InitExpr, IV, Step, /* Subtract */ false);
8702 } else
8703 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008704 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8705 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008706
8707 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008708 ExprResult Final;
8709 if (!Info.first) {
8710 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8711 InitExpr, NumIterations, Step,
8712 /* Subtract */ false);
8713 } else
8714 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008715 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8716 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008717
Alexander Musman3276a272015-03-21 10:12:56 +00008718 if (!Update.isUsable() || !Final.isUsable()) {
8719 Updates.push_back(nullptr);
8720 Finals.push_back(nullptr);
8721 HasErrors = true;
8722 } else {
8723 Updates.push_back(Update.get());
8724 Finals.push_back(Final.get());
8725 }
Richard Trieucc3949d2016-02-18 22:34:54 +00008726 ++CurInit;
8727 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00008728 }
8729 Clause.setUpdates(Updates);
8730 Clause.setFinals(Finals);
8731 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00008732}
8733
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008734OMPClause *Sema::ActOnOpenMPAlignedClause(
8735 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8736 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8737
8738 SmallVector<Expr *, 8> Vars;
8739 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00008740 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8741 SourceLocation ELoc;
8742 SourceRange ERange;
8743 Expr *SimpleRefExpr = RefExpr;
8744 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8745 /*AllowArraySection=*/false);
8746 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008747 // It will be analyzed later.
8748 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008749 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00008750 ValueDecl *D = Res.first;
8751 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008752 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008753
Alexey Bataev1efd1662016-03-29 10:59:56 +00008754 QualType QType = D->getType();
8755 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008756
8757 // OpenMP [2.8.1, simd construct, Restrictions]
8758 // The type of list items appearing in the aligned clause must be
8759 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008760 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008761 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00008762 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008763 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008764 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008765 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00008766 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008767 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00008768 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008769 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008770 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008771 continue;
8772 }
8773
8774 // OpenMP [2.8.1, simd construct, Restrictions]
8775 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00008776 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00008777 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008778 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8779 << getOpenMPClauseName(OMPC_aligned);
8780 continue;
8781 }
8782
Alexey Bataev1efd1662016-03-29 10:59:56 +00008783 DeclRefExpr *Ref = nullptr;
8784 if (!VD && IsOpenMPCapturedDecl(D))
8785 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8786 Vars.push_back(DefaultFunctionArrayConversion(
8787 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
8788 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008789 }
8790
8791 // OpenMP [2.8.1, simd construct, Description]
8792 // The parameter of the aligned clause, alignment, must be a constant
8793 // positive integer expression.
8794 // If no optional parameter is specified, implementation-defined default
8795 // alignments for SIMD instructions on the target platforms are assumed.
8796 if (Alignment != nullptr) {
8797 ExprResult AlignResult =
8798 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8799 if (AlignResult.isInvalid())
8800 return nullptr;
8801 Alignment = AlignResult.get();
8802 }
8803 if (Vars.empty())
8804 return nullptr;
8805
8806 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8807 EndLoc, Vars, Alignment);
8808}
8809
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008810OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8811 SourceLocation StartLoc,
8812 SourceLocation LParenLoc,
8813 SourceLocation EndLoc) {
8814 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008815 SmallVector<Expr *, 8> SrcExprs;
8816 SmallVector<Expr *, 8> DstExprs;
8817 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00008818 for (auto &RefExpr : VarList) {
8819 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
8820 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008821 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008822 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008823 SrcExprs.push_back(nullptr);
8824 DstExprs.push_back(nullptr);
8825 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008826 continue;
8827 }
8828
Alexey Bataeved09d242014-05-28 05:53:51 +00008829 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008830 // OpenMP [2.1, C/C++]
8831 // A list item is a variable name.
8832 // OpenMP [2.14.4.1, Restrictions, p.1]
8833 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00008834 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008835 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008836 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8837 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008838 continue;
8839 }
8840
8841 Decl *D = DE->getDecl();
8842 VarDecl *VD = cast<VarDecl>(D);
8843
8844 QualType Type = VD->getType();
8845 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8846 // It will be analyzed later.
8847 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008848 SrcExprs.push_back(nullptr);
8849 DstExprs.push_back(nullptr);
8850 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008851 continue;
8852 }
8853
8854 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
8855 // A list item that appears in a copyin clause must be threadprivate.
8856 if (!DSAStack->isThreadPrivate(VD)) {
8857 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00008858 << getOpenMPClauseName(OMPC_copyin)
8859 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008860 continue;
8861 }
8862
8863 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8864 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00008865 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008866 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008867 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008868 auto *SrcVD =
8869 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
8870 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008871 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008872 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
8873 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008874 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
8875 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008876 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008877 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008878 // For arrays generate assignment operation for single element and replace
8879 // it by the original array element in CodeGen.
8880 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8881 PseudoDstExpr, PseudoSrcExpr);
8882 if (AssignmentOp.isInvalid())
8883 continue;
8884 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8885 /*DiscardedValue=*/true);
8886 if (AssignmentOp.isInvalid())
8887 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008888
8889 DSAStack->addDSA(VD, DE, OMPC_copyin);
8890 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008891 SrcExprs.push_back(PseudoSrcExpr);
8892 DstExprs.push_back(PseudoDstExpr);
8893 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008894 }
8895
Alexey Bataeved09d242014-05-28 05:53:51 +00008896 if (Vars.empty())
8897 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008898
Alexey Bataevf56f98c2015-04-16 05:39:01 +00008899 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8900 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008901}
8902
Alexey Bataevbae9a792014-06-27 10:37:06 +00008903OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8904 SourceLocation StartLoc,
8905 SourceLocation LParenLoc,
8906 SourceLocation EndLoc) {
8907 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00008908 SmallVector<Expr *, 8> SrcExprs;
8909 SmallVector<Expr *, 8> DstExprs;
8910 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008911 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00008912 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8913 SourceLocation ELoc;
8914 SourceRange ERange;
8915 Expr *SimpleRefExpr = RefExpr;
8916 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8917 /*AllowArraySection=*/false);
8918 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00008919 // It will be analyzed later.
8920 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00008921 SrcExprs.push_back(nullptr);
8922 DstExprs.push_back(nullptr);
8923 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008924 }
Alexey Bataeve122da12016-03-17 10:50:17 +00008925 ValueDecl *D = Res.first;
8926 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00008927 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008928
Alexey Bataeve122da12016-03-17 10:50:17 +00008929 QualType Type = D->getType();
8930 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008931
8932 // OpenMP [2.14.4.2, Restrictions, p.2]
8933 // A list item that appears in a copyprivate clause may not appear in a
8934 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00008935 if (!VD || !DSAStack->isThreadPrivate(VD)) {
8936 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00008937 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8938 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00008939 Diag(ELoc, diag::err_omp_wrong_dsa)
8940 << getOpenMPClauseName(DVar.CKind)
8941 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00008942 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008943 continue;
8944 }
8945
8946 // OpenMP [2.11.4.2, Restrictions, p.1]
8947 // All list items that appear in a copyprivate clause must be either
8948 // threadprivate or private in the enclosing context.
8949 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00008950 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008951 if (DVar.CKind == OMPC_shared) {
8952 Diag(ELoc, diag::err_omp_required_access)
8953 << getOpenMPClauseName(OMPC_copyprivate)
8954 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00008955 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00008956 continue;
8957 }
8958 }
8959 }
8960
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008961 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008962 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008963 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008964 << getOpenMPClauseName(OMPC_copyprivate) << Type
8965 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008966 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00008967 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008968 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00008969 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008970 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00008971 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00008972 continue;
8973 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008974
Alexey Bataevbae9a792014-06-27 10:37:06 +00008975 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8976 // A variable of class type (or array thereof) that appears in a
8977 // copyin clause requires an accessible, unambiguous copy assignment
8978 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008979 Type = Context.getBaseElementType(Type.getNonReferenceType())
8980 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00008981 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00008982 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
8983 D->hasAttrs() ? &D->getAttrs() : nullptr);
8984 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00008985 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00008986 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
8987 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00008988 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00008989 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00008990 PseudoDstExpr, PseudoSrcExpr);
8991 if (AssignmentOp.isInvalid())
8992 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00008993 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00008994 /*DiscardedValue=*/true);
8995 if (AssignmentOp.isInvalid())
8996 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008997
8998 // No need to mark vars as copyprivate, they are already threadprivate or
8999 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009000 assert(VD || IsOpenMPCapturedDecl(D));
9001 Vars.push_back(
9002 VD ? RefExpr->IgnoreParens()
9003 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009004 SrcExprs.push_back(PseudoSrcExpr);
9005 DstExprs.push_back(PseudoDstExpr);
9006 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009007 }
9008
9009 if (Vars.empty())
9010 return nullptr;
9011
Alexey Bataeva63048e2015-03-23 06:18:07 +00009012 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9013 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009014}
9015
Alexey Bataev6125da92014-07-21 11:26:11 +00009016OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9017 SourceLocation StartLoc,
9018 SourceLocation LParenLoc,
9019 SourceLocation EndLoc) {
9020 if (VarList.empty())
9021 return nullptr;
9022
9023 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9024}
Alexey Bataevdea47612014-07-23 07:46:59 +00009025
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009026OMPClause *
9027Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9028 SourceLocation DepLoc, SourceLocation ColonLoc,
9029 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9030 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009031 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009032 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009033 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009034 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009035 return nullptr;
9036 }
9037 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009038 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9039 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009040 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009041 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009042 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9043 /*Last=*/OMPC_DEPEND_unknown, Except)
9044 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009045 return nullptr;
9046 }
9047 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009048 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009049 llvm::APSInt DepCounter(/*BitWidth=*/32);
9050 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9051 if (DepKind == OMPC_DEPEND_sink) {
9052 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9053 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9054 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009055 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009056 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009057 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9058 DSAStack->getParentOrderedRegionParam()) {
9059 for (auto &RefExpr : VarList) {
9060 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009061 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009062 // It will be analyzed later.
9063 Vars.push_back(RefExpr);
9064 continue;
9065 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009066
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009067 SourceLocation ELoc = RefExpr->getExprLoc();
9068 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9069 if (DepKind == OMPC_DEPEND_sink) {
9070 if (DepCounter >= TotalDepCount) {
9071 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9072 continue;
9073 }
9074 ++DepCounter;
9075 // OpenMP [2.13.9, Summary]
9076 // depend(dependence-type : vec), where dependence-type is:
9077 // 'sink' and where vec is the iteration vector, which has the form:
9078 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9079 // where n is the value specified by the ordered clause in the loop
9080 // directive, xi denotes the loop iteration variable of the i-th nested
9081 // loop associated with the loop directive, and di is a constant
9082 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009083 if (CurContext->isDependentContext()) {
9084 // It will be analyzed later.
9085 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009086 continue;
9087 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009088 SimpleExpr = SimpleExpr->IgnoreImplicit();
9089 OverloadedOperatorKind OOK = OO_None;
9090 SourceLocation OOLoc;
9091 Expr *LHS = SimpleExpr;
9092 Expr *RHS = nullptr;
9093 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9094 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9095 OOLoc = BO->getOperatorLoc();
9096 LHS = BO->getLHS()->IgnoreParenImpCasts();
9097 RHS = BO->getRHS()->IgnoreParenImpCasts();
9098 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9099 OOK = OCE->getOperator();
9100 OOLoc = OCE->getOperatorLoc();
9101 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9102 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9103 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9104 OOK = MCE->getMethodDecl()
9105 ->getNameInfo()
9106 .getName()
9107 .getCXXOverloadedOperator();
9108 OOLoc = MCE->getCallee()->getExprLoc();
9109 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9110 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9111 }
9112 SourceLocation ELoc;
9113 SourceRange ERange;
9114 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9115 /*AllowArraySection=*/false);
9116 if (Res.second) {
9117 // It will be analyzed later.
9118 Vars.push_back(RefExpr);
9119 }
9120 ValueDecl *D = Res.first;
9121 if (!D)
9122 continue;
9123
9124 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9125 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9126 continue;
9127 }
9128 if (RHS) {
9129 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9130 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9131 if (RHSRes.isInvalid())
9132 continue;
9133 }
9134 if (!CurContext->isDependentContext() &&
9135 DSAStack->getParentOrderedRegionParam() &&
9136 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9137 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9138 << DSAStack->getParentLoopControlVariable(
9139 DepCounter.getZExtValue());
9140 continue;
9141 }
9142 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009143 } else {
9144 // OpenMP [2.11.1.1, Restrictions, p.3]
9145 // A variable that is part of another variable (such as a field of a
9146 // structure) but is not an array element or an array section cannot
9147 // appear in a depend clause.
9148 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9149 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9150 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9151 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9152 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009153 (ASE &&
9154 !ASE->getBase()
9155 ->getType()
9156 .getNonReferenceType()
9157 ->isPointerType() &&
9158 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009159 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9160 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009161 continue;
9162 }
9163 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009164 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9165 }
9166
9167 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9168 TotalDepCount > VarList.size() &&
9169 DSAStack->getParentOrderedRegionParam()) {
9170 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9171 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9172 }
9173 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9174 Vars.empty())
9175 return nullptr;
9176 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009177 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9178 DepKind, DepLoc, ColonLoc, Vars);
9179 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9180 DSAStack->addDoacrossDependClause(C, OpsOffs);
9181 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009182}
Michael Wonge710d542015-08-07 16:16:36 +00009183
9184OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9185 SourceLocation LParenLoc,
9186 SourceLocation EndLoc) {
9187 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009188
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009189 // OpenMP [2.9.1, Restrictions]
9190 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009191 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9192 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009193 return nullptr;
9194
Michael Wonge710d542015-08-07 16:16:36 +00009195 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9196}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009197
9198static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9199 DSAStackTy *Stack, CXXRecordDecl *RD) {
9200 if (!RD || RD->isInvalidDecl())
9201 return true;
9202
9203 auto QTy = SemaRef.Context.getRecordType(RD);
9204 if (RD->isDynamicClass()) {
9205 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9206 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9207 return false;
9208 }
9209 auto *DC = RD;
9210 bool IsCorrect = true;
9211 for (auto *I : DC->decls()) {
9212 if (I) {
9213 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9214 if (MD->isStatic()) {
9215 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9216 SemaRef.Diag(MD->getLocation(),
9217 diag::note_omp_static_member_in_target);
9218 IsCorrect = false;
9219 }
9220 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9221 if (VD->isStaticDataMember()) {
9222 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9223 SemaRef.Diag(VD->getLocation(),
9224 diag::note_omp_static_member_in_target);
9225 IsCorrect = false;
9226 }
9227 }
9228 }
9229 }
9230
9231 for (auto &I : RD->bases()) {
9232 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9233 I.getType()->getAsCXXRecordDecl()))
9234 IsCorrect = false;
9235 }
9236 return IsCorrect;
9237}
9238
9239static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9240 DSAStackTy *Stack, QualType QTy) {
9241 NamedDecl *ND;
9242 if (QTy->isIncompleteType(&ND)) {
9243 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9244 return false;
9245 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009246 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009247 return false;
9248 }
9249 return true;
9250}
9251
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009252/// \brief Return true if it can be proven that the provided array expression
9253/// (array section or array subscript) does NOT specify the whole size of the
9254/// array whose base type is \a BaseQTy.
9255static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9256 const Expr *E,
9257 QualType BaseQTy) {
9258 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9259
9260 // If this is an array subscript, it refers to the whole size if the size of
9261 // the dimension is constant and equals 1. Also, an array section assumes the
9262 // format of an array subscript if no colon is used.
9263 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9264 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9265 return ATy->getSize().getSExtValue() != 1;
9266 // Size can't be evaluated statically.
9267 return false;
9268 }
9269
9270 assert(OASE && "Expecting array section if not an array subscript.");
9271 auto *LowerBound = OASE->getLowerBound();
9272 auto *Length = OASE->getLength();
9273
9274 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009275 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009276 if (LowerBound) {
9277 llvm::APSInt ConstLowerBound;
9278 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9279 return false; // Can't get the integer value as a constant.
9280 if (ConstLowerBound.getSExtValue())
9281 return true;
9282 }
9283
9284 // If we don't have a length we covering the whole dimension.
9285 if (!Length)
9286 return false;
9287
9288 // If the base is a pointer, we don't have a way to get the size of the
9289 // pointee.
9290 if (BaseQTy->isPointerType())
9291 return false;
9292
9293 // We can only check if the length is the same as the size of the dimension
9294 // if we have a constant array.
9295 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9296 if (!CATy)
9297 return false;
9298
9299 llvm::APSInt ConstLength;
9300 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9301 return false; // Can't get the integer value as a constant.
9302
9303 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9304}
9305
9306// Return true if it can be proven that the provided array expression (array
9307// section or array subscript) does NOT specify a single element of the array
9308// whose base type is \a BaseQTy.
9309static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009310 const Expr *E,
9311 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009312 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9313
9314 // An array subscript always refer to a single element. Also, an array section
9315 // assumes the format of an array subscript if no colon is used.
9316 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9317 return false;
9318
9319 assert(OASE && "Expecting array section if not an array subscript.");
9320 auto *Length = OASE->getLength();
9321
9322 // If we don't have a length we have to check if the array has unitary size
9323 // for this dimension. Also, we should always expect a length if the base type
9324 // is pointer.
9325 if (!Length) {
9326 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9327 return ATy->getSize().getSExtValue() != 1;
9328 // We cannot assume anything.
9329 return false;
9330 }
9331
9332 // Check if the length evaluates to 1.
9333 llvm::APSInt ConstLength;
9334 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9335 return false; // Can't get the integer value as a constant.
9336
9337 return ConstLength.getSExtValue() != 1;
9338}
9339
Samuel Antao661c0902016-05-26 17:39:58 +00009340// Return the expression of the base of the mappable expression or null if it
9341// cannot be determined and do all the necessary checks to see if the expression
9342// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009343// components of the expression.
9344static Expr *CheckMapClauseExpressionBase(
9345 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009346 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9347 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009348 SourceLocation ELoc = E->getExprLoc();
9349 SourceRange ERange = E->getSourceRange();
9350
9351 // The base of elements of list in a map clause have to be either:
9352 // - a reference to variable or field.
9353 // - a member expression.
9354 // - an array expression.
9355 //
9356 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9357 // reference to 'r'.
9358 //
9359 // If we have:
9360 //
9361 // struct SS {
9362 // Bla S;
9363 // foo() {
9364 // #pragma omp target map (S.Arr[:12]);
9365 // }
9366 // }
9367 //
9368 // We want to retrieve the member expression 'this->S';
9369
9370 Expr *RelevantExpr = nullptr;
9371
Samuel Antao5de996e2016-01-22 20:21:36 +00009372 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9373 // If a list item is an array section, it must specify contiguous storage.
9374 //
9375 // For this restriction it is sufficient that we make sure only references
9376 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009377 // exist except in the rightmost expression (unless they cover the whole
9378 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009379 //
9380 // r.ArrS[3:5].Arr[6:7]
9381 //
9382 // r.ArrS[3:5].x
9383 //
9384 // but these would be valid:
9385 // r.ArrS[3].Arr[6:7]
9386 //
9387 // r.ArrS[3].x
9388
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009389 bool AllowUnitySizeArraySection = true;
9390 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009391
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009392 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009393 E = E->IgnoreParenImpCasts();
9394
9395 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9396 if (!isa<VarDecl>(CurE->getDecl()))
9397 break;
9398
9399 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009400
9401 // If we got a reference to a declaration, we should not expect any array
9402 // section before that.
9403 AllowUnitySizeArraySection = false;
9404 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009405
9406 // Record the component.
9407 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9408 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009409 continue;
9410 }
9411
9412 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9413 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9414
9415 if (isa<CXXThisExpr>(BaseE))
9416 // We found a base expression: this->Val.
9417 RelevantExpr = CurE;
9418 else
9419 E = BaseE;
9420
9421 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9422 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9423 << CurE->getSourceRange();
9424 break;
9425 }
9426
9427 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9428
9429 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9430 // A bit-field cannot appear in a map clause.
9431 //
9432 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009433 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9434 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009435 break;
9436 }
9437
9438 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9439 // If the type of a list item is a reference to a type T then the type
9440 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009441 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009442
9443 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9444 // A list item cannot be a variable that is a member of a structure with
9445 // a union type.
9446 //
9447 if (auto *RT = CurType->getAs<RecordType>())
9448 if (RT->isUnionType()) {
9449 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9450 << CurE->getSourceRange();
9451 break;
9452 }
9453
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009454 // If we got a member expression, we should not expect any array section
9455 // before that:
9456 //
9457 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9458 // If a list item is an element of a structure, only the rightmost symbol
9459 // of the variable reference can be an array section.
9460 //
9461 AllowUnitySizeArraySection = false;
9462 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009463
9464 // Record the component.
9465 CurComponents.push_back(
9466 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009467 continue;
9468 }
9469
9470 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9471 E = CurE->getBase()->IgnoreParenImpCasts();
9472
9473 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9474 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9475 << 0 << CurE->getSourceRange();
9476 break;
9477 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009478
9479 // If we got an array subscript that express the whole dimension we
9480 // can have any array expressions before. If it only expressing part of
9481 // the dimension, we can only have unitary-size array expressions.
9482 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9483 E->getType()))
9484 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009485
9486 // Record the component - we don't have any declaration associated.
9487 CurComponents.push_back(
9488 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009489 continue;
9490 }
9491
9492 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009493 E = CurE->getBase()->IgnoreParenImpCasts();
9494
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009495 auto CurType =
9496 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9497
Samuel Antao5de996e2016-01-22 20:21:36 +00009498 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9499 // If the type of a list item is a reference to a type T then the type
9500 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009501 if (CurType->isReferenceType())
9502 CurType = CurType->getPointeeType();
9503
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009504 bool IsPointer = CurType->isAnyPointerType();
9505
9506 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009507 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9508 << 0 << CurE->getSourceRange();
9509 break;
9510 }
9511
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009512 bool NotWhole =
9513 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9514 bool NotUnity =
9515 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9516
Samuel Antaodab51bb2016-07-18 23:22:11 +00009517 if (AllowWholeSizeArraySection) {
9518 // Any array section is currently allowed. Allowing a whole size array
9519 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009520 //
9521 // If this array section refers to the whole dimension we can still
9522 // accept other array sections before this one, except if the base is a
9523 // pointer. Otherwise, only unitary sections are accepted.
9524 if (NotWhole || IsPointer)
9525 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009526 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009527 // A unity or whole array section is not allowed and that is not
9528 // compatible with the properties of the current array section.
9529 SemaRef.Diag(
9530 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9531 << CurE->getSourceRange();
9532 break;
9533 }
Samuel Antao90927002016-04-26 14:54:23 +00009534
9535 // Record the component - we don't have any declaration associated.
9536 CurComponents.push_back(
9537 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009538 continue;
9539 }
9540
9541 // If nothing else worked, this is not a valid map clause expression.
9542 SemaRef.Diag(ELoc,
9543 diag::err_omp_expected_named_var_member_or_array_expression)
9544 << ERange;
9545 break;
9546 }
9547
9548 return RelevantExpr;
9549}
9550
9551// Return true if expression E associated with value VD has conflicts with other
9552// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009553static bool CheckMapConflicts(
9554 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9555 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009556 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9557 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009558 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009559 SourceLocation ELoc = E->getExprLoc();
9560 SourceRange ERange = E->getSourceRange();
9561
9562 // In order to easily check the conflicts we need to match each component of
9563 // the expression under test with the components of the expressions that are
9564 // already in the stack.
9565
Samuel Antao5de996e2016-01-22 20:21:36 +00009566 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009567 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009568 "Map clause expression with unexpected base!");
9569
9570 // Variables to help detecting enclosing problems in data environment nests.
9571 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009572 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009573
Samuel Antao90927002016-04-26 14:54:23 +00009574 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9575 VD, CurrentRegionOnly,
9576 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009577 StackComponents,
9578 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009579
Samuel Antao5de996e2016-01-22 20:21:36 +00009580 assert(!StackComponents.empty() &&
9581 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009582 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009583 "Map clause expression with unexpected base!");
9584
Samuel Antao90927002016-04-26 14:54:23 +00009585 // The whole expression in the stack.
9586 auto *RE = StackComponents.front().getAssociatedExpression();
9587
Samuel Antao5de996e2016-01-22 20:21:36 +00009588 // Expressions must start from the same base. Here we detect at which
9589 // point both expressions diverge from each other and see if we can
9590 // detect if the memory referred to both expressions is contiguous and
9591 // do not overlap.
9592 auto CI = CurComponents.rbegin();
9593 auto CE = CurComponents.rend();
9594 auto SI = StackComponents.rbegin();
9595 auto SE = StackComponents.rend();
9596 for (; CI != CE && SI != SE; ++CI, ++SI) {
9597
9598 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9599 // At most one list item can be an array item derived from a given
9600 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009601 if (CurrentRegionOnly &&
9602 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9603 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9604 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9605 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9606 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009607 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009608 << CI->getAssociatedExpression()->getSourceRange();
9609 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9610 diag::note_used_here)
9611 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009612 return true;
9613 }
9614
9615 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009616 if (CI->getAssociatedExpression()->getStmtClass() !=
9617 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009618 break;
9619
9620 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009621 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009622 break;
9623 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009624 // Check if the extra components of the expressions in the enclosing
9625 // data environment are redundant for the current base declaration.
9626 // If they are, the maps completely overlap, which is legal.
9627 for (; SI != SE; ++SI) {
9628 QualType Type;
9629 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009630 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009631 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009632 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9633 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009634 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9635 Type =
9636 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9637 }
9638 if (Type.isNull() || Type->isAnyPointerType() ||
9639 CheckArrayExpressionDoesNotReferToWholeSize(
9640 SemaRef, SI->getAssociatedExpression(), Type))
9641 break;
9642 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009643
9644 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9645 // List items of map clauses in the same construct must not share
9646 // original storage.
9647 //
9648 // If the expressions are exactly the same or one is a subset of the
9649 // other, it means they are sharing storage.
9650 if (CI == CE && SI == SE) {
9651 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009652 if (CKind == OMPC_map)
9653 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9654 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009655 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009656 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9657 << ERange;
9658 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009659 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9660 << RE->getSourceRange();
9661 return true;
9662 } else {
9663 // If we find the same expression in the enclosing data environment,
9664 // that is legal.
9665 IsEnclosedByDataEnvironmentExpr = true;
9666 return false;
9667 }
9668 }
9669
Samuel Antao90927002016-04-26 14:54:23 +00009670 QualType DerivedType =
9671 std::prev(CI)->getAssociatedDeclaration()->getType();
9672 SourceLocation DerivedLoc =
9673 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +00009674
9675 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9676 // If the type of a list item is a reference to a type T then the type
9677 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009678 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009679
9680 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9681 // A variable for which the type is pointer and an array section
9682 // derived from that variable must not appear as list items of map
9683 // clauses of the same construct.
9684 //
9685 // Also, cover one of the cases in:
9686 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9687 // If any part of the original storage of a list item has corresponding
9688 // storage in the device data environment, all of the original storage
9689 // must have corresponding storage in the device data environment.
9690 //
9691 if (DerivedType->isAnyPointerType()) {
9692 if (CI == CE || SI == SE) {
9693 SemaRef.Diag(
9694 DerivedLoc,
9695 diag::err_omp_pointer_mapped_along_with_derived_section)
9696 << DerivedLoc;
9697 } else {
9698 assert(CI != CE && SI != SE);
9699 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9700 << DerivedLoc;
9701 }
9702 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9703 << RE->getSourceRange();
9704 return true;
9705 }
9706
9707 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9708 // List items of map clauses in the same construct must not share
9709 // original storage.
9710 //
9711 // An expression is a subset of the other.
9712 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +00009713 if (CKind == OMPC_map)
9714 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9715 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009716 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009717 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9718 << ERange;
9719 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009720 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9721 << RE->getSourceRange();
9722 return true;
9723 }
9724
9725 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +00009726 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +00009727 if (!CurrentRegionOnly && SI != SE)
9728 EnclosingExpr = RE;
9729
9730 // The current expression is a subset of the expression in the data
9731 // environment.
9732 IsEnclosedByDataEnvironmentExpr |=
9733 (!CurrentRegionOnly && CI != CE && SI == SE);
9734
9735 return false;
9736 });
9737
9738 if (CurrentRegionOnly)
9739 return FoundError;
9740
9741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9742 // If any part of the original storage of a list item has corresponding
9743 // storage in the device data environment, all of the original storage must
9744 // have corresponding storage in the device data environment.
9745 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9746 // If a list item is an element of a structure, and a different element of
9747 // the structure has a corresponding list item in the device data environment
9748 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +00009749 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +00009750 // data environment prior to the task encountering the construct.
9751 //
9752 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9753 SemaRef.Diag(ELoc,
9754 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9755 << ERange;
9756 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9757 << EnclosingExpr->getSourceRange();
9758 return true;
9759 }
9760
9761 return FoundError;
9762}
9763
Samuel Antao661c0902016-05-26 17:39:58 +00009764namespace {
9765// Utility struct that gathers all the related lists associated with a mappable
9766// expression.
9767struct MappableVarListInfo final {
9768 // The list of expressions.
9769 ArrayRef<Expr *> VarList;
9770 // The list of processed expressions.
9771 SmallVector<Expr *, 16> ProcessedVarList;
9772 // The mappble components for each expression.
9773 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
9774 // The base declaration of the variable.
9775 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
9776
9777 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
9778 // We have a list of components and base declarations for each entry in the
9779 // variable list.
9780 VarComponents.reserve(VarList.size());
9781 VarBaseDeclarations.reserve(VarList.size());
9782 }
9783};
9784}
9785
9786// Check the validity of the provided variable list for the provided clause kind
9787// \a CKind. In the check process the valid expressions, and mappable expression
9788// components and variables are extracted and used to fill \a Vars,
9789// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
9790// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
9791static void
9792checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
9793 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
9794 SourceLocation StartLoc,
9795 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
9796 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009797 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
9798 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +00009799 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009800
Samuel Antao90927002016-04-26 14:54:23 +00009801 // Keep track of the mappable components and base declarations in this clause.
9802 // Each entry in the list is going to have a list of components associated. We
9803 // record each set of the components so that we can build the clause later on.
9804 // In the end we should have the same amount of declarations and component
9805 // lists.
Samuel Antao90927002016-04-26 14:54:23 +00009806
Samuel Antao661c0902016-05-26 17:39:58 +00009807 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009808 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009809 SourceLocation ELoc = RE->getExprLoc();
9810
Kelvin Li0bff7af2015-11-23 05:32:03 +00009811 auto *VE = RE->IgnoreParenLValueCasts();
9812
9813 if (VE->isValueDependent() || VE->isTypeDependent() ||
9814 VE->isInstantiationDependent() ||
9815 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009816 // We can only analyze this information once the missing information is
9817 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +00009818 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009819 continue;
9820 }
9821
9822 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009823
Samuel Antao5de996e2016-01-22 20:21:36 +00009824 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009825 SemaRef.Diag(ELoc,
9826 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +00009827 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +00009828 continue;
9829 }
9830
Samuel Antao90927002016-04-26 14:54:23 +00009831 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
9832 ValueDecl *CurDeclaration = nullptr;
9833
9834 // Obtain the array or member expression bases if required. Also, fill the
9835 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +00009836 auto *BE =
9837 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009838 if (!BE)
9839 continue;
9840
Samuel Antao90927002016-04-26 14:54:23 +00009841 assert(!CurComponents.empty() &&
9842 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009843
Samuel Antao90927002016-04-26 14:54:23 +00009844 // For the following checks, we rely on the base declaration which is
9845 // expected to be associated with the last component. The declaration is
9846 // expected to be a variable or a field (if 'this' is being mapped).
9847 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
9848 assert(CurDeclaration && "Null decl on map clause.");
9849 assert(
9850 CurDeclaration->isCanonicalDecl() &&
9851 "Expecting components to have associated only canonical declarations.");
9852
9853 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
9854 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +00009855
9856 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +00009857 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +00009858
9859 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +00009860 // threadprivate variables cannot appear in a map clause.
9861 // OpenMP 4.5 [2.10.5, target update Construct]
9862 // threadprivate variables cannot appear in a from clause.
9863 if (VD && DSAS->isThreadPrivate(VD)) {
9864 auto DVar = DSAS->getTopDSA(VD, false);
9865 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
9866 << getOpenMPClauseName(CKind);
9867 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009868 continue;
9869 }
9870
Samuel Antao5de996e2016-01-22 20:21:36 +00009871 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9872 // A list item cannot appear in both a map clause and a data-sharing
9873 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +00009874
Samuel Antao5de996e2016-01-22 20:21:36 +00009875 // Check conflicts with other map clause expressions. We check the conflicts
9876 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +00009877 // environment, because the restrictions are different. We only have to
9878 // check conflicts across regions for the map clauses.
9879 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9880 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009881 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009882 if (CKind == OMPC_map &&
9883 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9884 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +00009885 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +00009886
Samuel Antao661c0902016-05-26 17:39:58 +00009887 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +00009888 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9889 // If the type of a list item is a reference to a type T then the type will
9890 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009891 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009892
Samuel Antao661c0902016-05-26 17:39:58 +00009893 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
9894 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +00009895 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +00009896 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +00009897 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
9898 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009899 continue;
9900
Samuel Antao661c0902016-05-26 17:39:58 +00009901 if (CKind == OMPC_map) {
9902 // target enter data
9903 // OpenMP [2.10.2, Restrictions, p. 99]
9904 // A map-type must be specified in all map clauses and must be either
9905 // to or alloc.
9906 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
9907 if (DKind == OMPD_target_enter_data &&
9908 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
9909 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9910 << (IsMapTypeImplicit ? 1 : 0)
9911 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9912 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009913 continue;
9914 }
Samuel Antao661c0902016-05-26 17:39:58 +00009915
9916 // target exit_data
9917 // OpenMP [2.10.3, Restrictions, p. 102]
9918 // A map-type must be specified in all map clauses and must be either
9919 // from, release, or delete.
9920 if (DKind == OMPD_target_exit_data &&
9921 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
9922 MapType == OMPC_MAP_delete)) {
9923 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9924 << (IsMapTypeImplicit ? 1 : 0)
9925 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9926 << getOpenMPDirectiveName(DKind);
9927 continue;
9928 }
9929
9930 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9931 // A list item cannot appear in both a map clause and a data-sharing
9932 // attribute clause on the same construct
9933 if (DKind == OMPD_target && VD) {
9934 auto DVar = DSAS->getTopDSA(VD, false);
9935 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009936 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +00009937 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +00009938 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +00009939 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
9940 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
9941 continue;
9942 }
9943 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009944 }
9945
Samuel Antao90927002016-04-26 14:54:23 +00009946 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +00009947 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +00009948
9949 // Store the components in the stack so that they can be used to check
9950 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +00009951 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
9952 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +00009953
9954 // Save the components and declaration to create the clause. For purposes of
9955 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +00009956 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +00009957 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
9958 MVLI.VarComponents.back().append(CurComponents.begin(),
9959 CurComponents.end());
9960 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
9961 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009962 }
Samuel Antao661c0902016-05-26 17:39:58 +00009963}
9964
9965OMPClause *
9966Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9967 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9968 SourceLocation MapLoc, SourceLocation ColonLoc,
9969 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9970 SourceLocation LParenLoc, SourceLocation EndLoc) {
9971 MappableVarListInfo MVLI(VarList);
9972 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
9973 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009974
Samuel Antao5de996e2016-01-22 20:21:36 +00009975 // We need to produce a map clause even if we don't have variables so that
9976 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +00009977 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9978 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
9979 MVLI.VarComponents, MapTypeModifier, MapType,
9980 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +00009981}
Kelvin Li099bb8c2015-11-24 20:50:12 +00009982
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00009983QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9984 TypeResult ParsedType) {
9985 assert(ParsedType.isUsable());
9986
9987 QualType ReductionType = GetTypeFromParser(ParsedType.get());
9988 if (ReductionType.isNull())
9989 return QualType();
9990
9991 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
9992 // A type name in a declare reduction directive cannot be a function type, an
9993 // array type, a reference type, or a type qualified with const, volatile or
9994 // restrict.
9995 if (ReductionType.hasQualifiers()) {
9996 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
9997 return QualType();
9998 }
9999
10000 if (ReductionType->isFunctionType()) {
10001 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10002 return QualType();
10003 }
10004 if (ReductionType->isReferenceType()) {
10005 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10006 return QualType();
10007 }
10008 if (ReductionType->isArrayType()) {
10009 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10010 return QualType();
10011 }
10012 return ReductionType;
10013}
10014
10015Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10016 Scope *S, DeclContext *DC, DeclarationName Name,
10017 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10018 AccessSpecifier AS, Decl *PrevDeclInScope) {
10019 SmallVector<Decl *, 8> Decls;
10020 Decls.reserve(ReductionTypes.size());
10021
10022 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10023 ForRedeclaration);
10024 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10025 // A reduction-identifier may not be re-declared in the current scope for the
10026 // same type or for a type that is compatible according to the base language
10027 // rules.
10028 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10029 OMPDeclareReductionDecl *PrevDRD = nullptr;
10030 bool InCompoundScope = true;
10031 if (S != nullptr) {
10032 // Find previous declaration with the same name not referenced in other
10033 // declarations.
10034 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10035 InCompoundScope =
10036 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10037 LookupName(Lookup, S);
10038 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10039 /*AllowInlineNamespace=*/false);
10040 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10041 auto Filter = Lookup.makeFilter();
10042 while (Filter.hasNext()) {
10043 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10044 if (InCompoundScope) {
10045 auto I = UsedAsPrevious.find(PrevDecl);
10046 if (I == UsedAsPrevious.end())
10047 UsedAsPrevious[PrevDecl] = false;
10048 if (auto *D = PrevDecl->getPrevDeclInScope())
10049 UsedAsPrevious[D] = true;
10050 }
10051 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10052 PrevDecl->getLocation();
10053 }
10054 Filter.done();
10055 if (InCompoundScope) {
10056 for (auto &PrevData : UsedAsPrevious) {
10057 if (!PrevData.second) {
10058 PrevDRD = PrevData.first;
10059 break;
10060 }
10061 }
10062 }
10063 } else if (PrevDeclInScope != nullptr) {
10064 auto *PrevDRDInScope = PrevDRD =
10065 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10066 do {
10067 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10068 PrevDRDInScope->getLocation();
10069 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10070 } while (PrevDRDInScope != nullptr);
10071 }
10072 for (auto &TyData : ReductionTypes) {
10073 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10074 bool Invalid = false;
10075 if (I != PreviousRedeclTypes.end()) {
10076 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10077 << TyData.first;
10078 Diag(I->second, diag::note_previous_definition);
10079 Invalid = true;
10080 }
10081 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10082 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10083 Name, TyData.first, PrevDRD);
10084 DC->addDecl(DRD);
10085 DRD->setAccess(AS);
10086 Decls.push_back(DRD);
10087 if (Invalid)
10088 DRD->setInvalidDecl();
10089 else
10090 PrevDRD = DRD;
10091 }
10092
10093 return DeclGroupPtrTy::make(
10094 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10095}
10096
10097void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10098 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10099
10100 // Enter new function scope.
10101 PushFunctionScope();
10102 getCurFunction()->setHasBranchProtectedScope();
10103 getCurFunction()->setHasOMPDeclareReductionCombiner();
10104
10105 if (S != nullptr)
10106 PushDeclContext(S, DRD);
10107 else
10108 CurContext = DRD;
10109
10110 PushExpressionEvaluationContext(PotentiallyEvaluated);
10111
10112 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010113 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10114 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10115 // uses semantics of argument handles by value, but it should be passed by
10116 // reference. C lang does not support references, so pass all parameters as
10117 // pointers.
10118 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010119 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010120 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010121 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10122 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10123 // uses semantics of argument handles by value, but it should be passed by
10124 // reference. C lang does not support references, so pass all parameters as
10125 // pointers.
10126 // Create 'T omp_out;' variable.
10127 auto *OmpOutParm =
10128 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10129 if (S != nullptr) {
10130 PushOnScopeChains(OmpInParm, S);
10131 PushOnScopeChains(OmpOutParm, S);
10132 } else {
10133 DRD->addDecl(OmpInParm);
10134 DRD->addDecl(OmpOutParm);
10135 }
10136}
10137
10138void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10139 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10140 DiscardCleanupsInEvaluationContext();
10141 PopExpressionEvaluationContext();
10142
10143 PopDeclContext();
10144 PopFunctionScopeInfo();
10145
10146 if (Combiner != nullptr)
10147 DRD->setCombiner(Combiner);
10148 else
10149 DRD->setInvalidDecl();
10150}
10151
10152void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10153 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10154
10155 // Enter new function scope.
10156 PushFunctionScope();
10157 getCurFunction()->setHasBranchProtectedScope();
10158
10159 if (S != nullptr)
10160 PushDeclContext(S, DRD);
10161 else
10162 CurContext = DRD;
10163
10164 PushExpressionEvaluationContext(PotentiallyEvaluated);
10165
10166 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010167 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10168 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10169 // uses semantics of argument handles by value, but it should be passed by
10170 // reference. C lang does not support references, so pass all parameters as
10171 // pointers.
10172 // Create 'T omp_priv;' variable.
10173 auto *OmpPrivParm =
10174 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010175 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10176 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10177 // uses semantics of argument handles by value, but it should be passed by
10178 // reference. C lang does not support references, so pass all parameters as
10179 // pointers.
10180 // Create 'T omp_orig;' variable.
10181 auto *OmpOrigParm =
10182 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010183 if (S != nullptr) {
10184 PushOnScopeChains(OmpPrivParm, S);
10185 PushOnScopeChains(OmpOrigParm, S);
10186 } else {
10187 DRD->addDecl(OmpPrivParm);
10188 DRD->addDecl(OmpOrigParm);
10189 }
10190}
10191
10192void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10193 Expr *Initializer) {
10194 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10195 DiscardCleanupsInEvaluationContext();
10196 PopExpressionEvaluationContext();
10197
10198 PopDeclContext();
10199 PopFunctionScopeInfo();
10200
10201 if (Initializer != nullptr)
10202 DRD->setInitializer(Initializer);
10203 else
10204 DRD->setInvalidDecl();
10205}
10206
10207Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10208 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10209 for (auto *D : DeclReductions.get()) {
10210 if (IsValid) {
10211 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10212 if (S != nullptr)
10213 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10214 } else
10215 D->setInvalidDecl();
10216 }
10217 return DeclReductions;
10218}
10219
David Majnemer9d168222016-08-05 17:44:54 +000010220OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010221 SourceLocation StartLoc,
10222 SourceLocation LParenLoc,
10223 SourceLocation EndLoc) {
10224 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010225
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010226 // OpenMP [teams Constrcut, Restrictions]
10227 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010228 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10229 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010230 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010231
10232 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10233}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010234
10235OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10236 SourceLocation StartLoc,
10237 SourceLocation LParenLoc,
10238 SourceLocation EndLoc) {
10239 Expr *ValExpr = ThreadLimit;
10240
10241 // OpenMP [teams Constrcut, Restrictions]
10242 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010243 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10244 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010245 return nullptr;
10246
David Majnemer9d168222016-08-05 17:44:54 +000010247 return new (Context)
10248 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010249}
Alexey Bataeva0569352015-12-01 10:17:31 +000010250
10251OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10252 SourceLocation StartLoc,
10253 SourceLocation LParenLoc,
10254 SourceLocation EndLoc) {
10255 Expr *ValExpr = Priority;
10256
10257 // OpenMP [2.9.1, task Constrcut]
10258 // The priority-value is a non-negative numerical scalar expression.
10259 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10260 /*StrictlyPositive=*/false))
10261 return nullptr;
10262
10263 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10264}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010265
10266OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10267 SourceLocation StartLoc,
10268 SourceLocation LParenLoc,
10269 SourceLocation EndLoc) {
10270 Expr *ValExpr = Grainsize;
10271
10272 // OpenMP [2.9.2, taskloop Constrcut]
10273 // The parameter of the grainsize clause must be a positive integer
10274 // expression.
10275 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10276 /*StrictlyPositive=*/true))
10277 return nullptr;
10278
10279 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10280}
Alexey Bataev382967a2015-12-08 12:06:20 +000010281
10282OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10283 SourceLocation StartLoc,
10284 SourceLocation LParenLoc,
10285 SourceLocation EndLoc) {
10286 Expr *ValExpr = NumTasks;
10287
10288 // OpenMP [2.9.2, taskloop Constrcut]
10289 // The parameter of the num_tasks clause must be a positive integer
10290 // expression.
10291 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10292 /*StrictlyPositive=*/true))
10293 return nullptr;
10294
10295 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10296}
10297
Alexey Bataev28c75412015-12-15 08:19:24 +000010298OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10299 SourceLocation LParenLoc,
10300 SourceLocation EndLoc) {
10301 // OpenMP [2.13.2, critical construct, Description]
10302 // ... where hint-expression is an integer constant expression that evaluates
10303 // to a valid lock hint.
10304 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10305 if (HintExpr.isInvalid())
10306 return nullptr;
10307 return new (Context)
10308 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10309}
10310
Carlo Bertollib4adf552016-01-15 18:50:31 +000010311OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10312 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10313 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10314 SourceLocation EndLoc) {
10315 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10316 std::string Values;
10317 Values += "'";
10318 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10319 Values += "'";
10320 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10321 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10322 return nullptr;
10323 }
10324 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010325 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010326 if (ChunkSize) {
10327 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10328 !ChunkSize->isInstantiationDependent() &&
10329 !ChunkSize->containsUnexpandedParameterPack()) {
10330 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10331 ExprResult Val =
10332 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10333 if (Val.isInvalid())
10334 return nullptr;
10335
10336 ValExpr = Val.get();
10337
10338 // OpenMP [2.7.1, Restrictions]
10339 // chunk_size must be a loop invariant integer expression with a positive
10340 // value.
10341 llvm::APSInt Result;
10342 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10343 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10344 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10345 << "dist_schedule" << ChunkSize->getSourceRange();
10346 return nullptr;
10347 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010348 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10349 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010350 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10351 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10352 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010353 }
10354 }
10355 }
10356
10357 return new (Context)
10358 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010359 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010360}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010361
10362OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10363 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10364 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10365 SourceLocation KindLoc, SourceLocation EndLoc) {
10366 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010367 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010368 std::string Value;
10369 SourceLocation Loc;
10370 Value += "'";
10371 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10372 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010373 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010374 Loc = MLoc;
10375 } else {
10376 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010377 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010378 Loc = KindLoc;
10379 }
10380 Value += "'";
10381 Diag(Loc, diag::err_omp_unexpected_clause_value)
10382 << Value << getOpenMPClauseName(OMPC_defaultmap);
10383 return nullptr;
10384 }
10385
10386 return new (Context)
10387 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10388}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010389
10390bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10391 DeclContext *CurLexicalContext = getCurLexicalContext();
10392 if (!CurLexicalContext->isFileContext() &&
10393 !CurLexicalContext->isExternCContext() &&
10394 !CurLexicalContext->isExternCXXContext()) {
10395 Diag(Loc, diag::err_omp_region_not_file_context);
10396 return false;
10397 }
10398 if (IsInOpenMPDeclareTargetContext) {
10399 Diag(Loc, diag::err_omp_enclosed_declare_target);
10400 return false;
10401 }
10402
10403 IsInOpenMPDeclareTargetContext = true;
10404 return true;
10405}
10406
10407void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10408 assert(IsInOpenMPDeclareTargetContext &&
10409 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10410
10411 IsInOpenMPDeclareTargetContext = false;
10412}
10413
David Majnemer9d168222016-08-05 17:44:54 +000010414void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10415 CXXScopeSpec &ScopeSpec,
10416 const DeclarationNameInfo &Id,
10417 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10418 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010419 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10420 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10421
10422 if (Lookup.isAmbiguous())
10423 return;
10424 Lookup.suppressDiagnostics();
10425
10426 if (!Lookup.isSingleResult()) {
10427 if (TypoCorrection Corrected =
10428 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10429 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10430 CTK_ErrorRecovery)) {
10431 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10432 << Id.getName());
10433 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10434 return;
10435 }
10436
10437 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10438 return;
10439 }
10440
10441 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10442 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10443 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10444 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10445
10446 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10447 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10448 ND->addAttr(A);
10449 if (ASTMutationListener *ML = Context.getASTMutationListener())
10450 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10451 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10452 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10453 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10454 << Id.getName();
10455 }
10456 } else
10457 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10458}
10459
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010460static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10461 Sema &SemaRef, Decl *D) {
10462 if (!D)
10463 return;
10464 Decl *LD = nullptr;
10465 if (isa<TagDecl>(D)) {
10466 LD = cast<TagDecl>(D)->getDefinition();
10467 } else if (isa<VarDecl>(D)) {
10468 LD = cast<VarDecl>(D)->getDefinition();
10469
10470 // If this is an implicit variable that is legal and we do not need to do
10471 // anything.
10472 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010473 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10474 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10475 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010476 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010477 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010478 return;
10479 }
10480
10481 } else if (isa<FunctionDecl>(D)) {
10482 const FunctionDecl *FD = nullptr;
10483 if (cast<FunctionDecl>(D)->hasBody(FD))
10484 LD = const_cast<FunctionDecl *>(FD);
10485
10486 // If the definition is associated with the current declaration in the
10487 // target region (it can be e.g. a lambda) that is legal and we do not need
10488 // to do anything else.
10489 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010490 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10491 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10492 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010493 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010494 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010495 return;
10496 }
10497 }
10498 if (!LD)
10499 LD = D;
10500 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10501 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10502 // Outlined declaration is not declared target.
10503 if (LD->isOutOfLine()) {
10504 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10505 SemaRef.Diag(SL, diag::note_used_here) << SR;
10506 } else {
10507 DeclContext *DC = LD->getDeclContext();
10508 while (DC) {
10509 if (isa<FunctionDecl>(DC) &&
10510 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10511 break;
10512 DC = DC->getParent();
10513 }
10514 if (DC)
10515 return;
10516
10517 // Is not declared in target context.
10518 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10519 SemaRef.Diag(SL, diag::note_used_here) << SR;
10520 }
10521 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010522 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10523 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10524 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010525 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010526 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010527 }
10528}
10529
10530static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10531 Sema &SemaRef, DSAStackTy *Stack,
10532 ValueDecl *VD) {
10533 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10534 return true;
10535 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10536 return false;
10537 return true;
10538}
10539
10540void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10541 if (!D || D->isInvalidDecl())
10542 return;
10543 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10544 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10545 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10546 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10547 if (DSAStack->isThreadPrivate(VD)) {
10548 Diag(SL, diag::err_omp_threadprivate_in_target);
10549 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10550 return;
10551 }
10552 }
10553 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10554 // Problem if any with var declared with incomplete type will be reported
10555 // as normal, so no need to check it here.
10556 if ((E || !VD->getType()->isIncompleteType()) &&
10557 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10558 // Mark decl as declared target to prevent further diagnostic.
10559 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010560 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10561 Context, OMPDeclareTargetDeclAttr::MT_To);
10562 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010563 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010564 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010565 }
10566 return;
10567 }
10568 }
10569 if (!E) {
10570 // Checking declaration inside declare target region.
10571 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10572 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010573 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10574 Context, OMPDeclareTargetDeclAttr::MT_To);
10575 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010576 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010577 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010578 }
10579 return;
10580 }
10581 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10582}
Samuel Antao661c0902016-05-26 17:39:58 +000010583
10584OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10585 SourceLocation StartLoc,
10586 SourceLocation LParenLoc,
10587 SourceLocation EndLoc) {
10588 MappableVarListInfo MVLI(VarList);
10589 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10590 if (MVLI.ProcessedVarList.empty())
10591 return nullptr;
10592
10593 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10594 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10595 MVLI.VarComponents);
10596}
Samuel Antaoec172c62016-05-26 17:49:04 +000010597
10598OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10599 SourceLocation StartLoc,
10600 SourceLocation LParenLoc,
10601 SourceLocation EndLoc) {
10602 MappableVarListInfo MVLI(VarList);
10603 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10604 if (MVLI.ProcessedVarList.empty())
10605 return nullptr;
10606
10607 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10608 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10609 MVLI.VarComponents);
10610}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010611
10612OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10613 SourceLocation StartLoc,
10614 SourceLocation LParenLoc,
10615 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010616 MappableVarListInfo MVLI(VarList);
10617 SmallVector<Expr *, 8> PrivateCopies;
10618 SmallVector<Expr *, 8> Inits;
10619
Carlo Bertolli2404b172016-07-13 15:37:16 +000010620 for (auto &RefExpr : VarList) {
10621 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10622 SourceLocation ELoc;
10623 SourceRange ERange;
10624 Expr *SimpleRefExpr = RefExpr;
10625 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10626 if (Res.second) {
10627 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010628 MVLI.ProcessedVarList.push_back(RefExpr);
10629 PrivateCopies.push_back(nullptr);
10630 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010631 }
10632 ValueDecl *D = Res.first;
10633 if (!D)
10634 continue;
10635
10636 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010637 Type = Type.getNonReferenceType().getUnqualifiedType();
10638
10639 auto *VD = dyn_cast<VarDecl>(D);
10640
10641 // Item should be a pointer or reference to pointer.
10642 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010643 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10644 << 0 << RefExpr->getSourceRange();
10645 continue;
10646 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010647
10648 // Build the private variable and the expression that refers to it.
10649 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10650 D->hasAttrs() ? &D->getAttrs() : nullptr);
10651 if (VDPrivate->isInvalidDecl())
10652 continue;
10653
10654 CurContext->addDecl(VDPrivate);
10655 auto VDPrivateRefExpr = buildDeclRefExpr(
10656 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10657
10658 // Add temporary variable to initialize the private copy of the pointer.
10659 auto *VDInit =
10660 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10661 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10662 RefExpr->getExprLoc());
10663 AddInitializerToDecl(VDPrivate,
10664 DefaultLvalueConversion(VDInitRefExpr).get(),
10665 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10666
10667 // If required, build a capture to implement the privatization initialized
10668 // with the current list item value.
10669 DeclRefExpr *Ref = nullptr;
10670 if (!VD)
10671 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10672 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10673 PrivateCopies.push_back(VDPrivateRefExpr);
10674 Inits.push_back(VDInitRefExpr);
10675
10676 // We need to add a data sharing attribute for this variable to make sure it
10677 // is correctly captured. A variable that shows up in a use_device_ptr has
10678 // similar properties of a first private variable.
10679 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10680
10681 // Create a mappable component for the list item. List items in this clause
10682 // only need a component.
10683 MVLI.VarBaseDeclarations.push_back(D);
10684 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10685 MVLI.VarComponents.back().push_back(
10686 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000010687 }
10688
Samuel Antaocc10b852016-07-28 14:23:26 +000010689 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000010690 return nullptr;
10691
Samuel Antaocc10b852016-07-28 14:23:26 +000010692 return OMPUseDevicePtrClause::Create(
10693 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10694 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010695}
Carlo Bertolli70594e92016-07-13 17:16:49 +000010696
10697OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10698 SourceLocation StartLoc,
10699 SourceLocation LParenLoc,
10700 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000010701 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010702 for (auto &RefExpr : VarList) {
10703 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10704 SourceLocation ELoc;
10705 SourceRange ERange;
10706 Expr *SimpleRefExpr = RefExpr;
10707 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10708 if (Res.second) {
10709 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000010710 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010711 }
10712 ValueDecl *D = Res.first;
10713 if (!D)
10714 continue;
10715
10716 QualType Type = D->getType();
10717 // item should be a pointer or array or reference to pointer or array
10718 if (!Type.getNonReferenceType()->isPointerType() &&
10719 !Type.getNonReferenceType()->isArrayType()) {
10720 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10721 << 0 << RefExpr->getSourceRange();
10722 continue;
10723 }
Samuel Antao6890b092016-07-28 14:25:09 +000010724
10725 // Check if the declaration in the clause does not show up in any data
10726 // sharing attribute.
10727 auto DVar = DSAStack->getTopDSA(D, false);
10728 if (isOpenMPPrivate(DVar.CKind)) {
10729 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10730 << getOpenMPClauseName(DVar.CKind)
10731 << getOpenMPClauseName(OMPC_is_device_ptr)
10732 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10733 ReportOriginalDSA(*this, DSAStack, D, DVar);
10734 continue;
10735 }
10736
10737 Expr *ConflictExpr;
10738 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010739 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010740 [&ConflictExpr](
10741 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10742 OpenMPClauseKind) -> bool {
10743 ConflictExpr = R.front().getAssociatedExpression();
10744 return true;
10745 })) {
10746 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10747 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10748 << ConflictExpr->getSourceRange();
10749 continue;
10750 }
10751
10752 // Store the components in the stack so that they can be used to check
10753 // against other clauses later on.
10754 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
10755 DSAStack->addMappableExpressionComponents(
10756 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
10757
10758 // Record the expression we've just processed.
10759 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
10760
10761 // Create a mappable component for the list item. List items in this clause
10762 // only need a component. We use a null declaration to signal fields in
10763 // 'this'.
10764 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
10765 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
10766 "Unexpected device pointer expression!");
10767 MVLI.VarBaseDeclarations.push_back(
10768 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
10769 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10770 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010771 }
10772
Samuel Antao6890b092016-07-28 14:25:09 +000010773 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000010774 return nullptr;
10775
Samuel Antao6890b092016-07-28 14:25:09 +000010776 return OMPIsDevicePtrClause::Create(
10777 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10778 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010779}