blob: 55a188701d5f5bdbdc4e49586c0b94288b17390f [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Kelvin Libf594a52016-12-17 05:48:59 +00001597 case OMPD_teams:
1598 case OMPD_target_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001611 case OMPD_simd:
1612 case OMPD_for:
1613 case OMPD_for_simd:
1614 case OMPD_sections:
1615 case OMPD_section:
1616 case OMPD_single:
1617 case OMPD_master:
1618 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001619 case OMPD_taskgroup:
1620 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001621 case OMPD_ordered:
1622 case OMPD_atomic:
1623 case OMPD_target_data:
1624 case OMPD_target:
1625 case OMPD_target_parallel:
1626 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001627 case OMPD_target_parallel_for_simd:
1628 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001629 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001630 std::make_pair(StringRef(), QualType()) // __context with shared vars
1631 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001632 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1633 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001634 break;
1635 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001636 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001637 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001638 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1639 FunctionProtoType::ExtProtoInfo EPI;
1640 EPI.Variadic = true;
1641 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001642 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001643 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001644 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1645 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1646 std::make_pair(".copy_fn.",
1647 Context.getPointerType(CopyFnType).withConst()),
1648 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1650 };
1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001653 // Mark this captured region as inlined, because we don't use outlined
1654 // function directly.
1655 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1656 AlwaysInlineAttr::CreateImplicit(
1657 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001658 break;
1659 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001660 case OMPD_taskloop:
1661 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001662 QualType KmpInt32Ty =
1663 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1664 QualType KmpUInt64Ty =
1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1666 QualType KmpInt64Ty =
1667 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1668 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1669 FunctionProtoType::ExtProtoInfo EPI;
1670 EPI.Variadic = true;
1671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001672 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001673 std::make_pair(".global_tid.", KmpInt32Ty),
1674 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1675 std::make_pair(".privates.",
1676 Context.VoidPtrTy.withConst().withRestrict()),
1677 std::make_pair(
1678 ".copy_fn.",
1679 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1680 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1681 std::make_pair(".lb.", KmpUInt64Ty),
1682 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1683 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001684 std::make_pair(StringRef(), QualType()) // __context with shared vars
1685 };
1686 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1687 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001688 // Mark this captured region as inlined, because we don't use outlined
1689 // function directly.
1690 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1691 AlwaysInlineAttr::CreateImplicit(
1692 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001693 break;
1694 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001695 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001696 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001697 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001698 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001699 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001700 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001701 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001702 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001703 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001704 case OMPD_target_teams_distribute_parallel_for_simd:
1705 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001706 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1707 QualType KmpInt32PtrTy =
1708 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1709 Sema::CapturedParamNameType Params[] = {
1710 std::make_pair(".global_tid.", KmpInt32PtrTy),
1711 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1712 std::make_pair(".previous.lb.", Context.getSizeType()),
1713 std::make_pair(".previous.ub.", Context.getSizeType()),
1714 std::make_pair(StringRef(), QualType()) // __context with shared vars
1715 };
1716 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1717 Params);
1718 break;
1719 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001720 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001721 case OMPD_taskyield:
1722 case OMPD_barrier:
1723 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001724 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001725 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001726 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001727 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001728 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001729 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001730 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001731 case OMPD_declare_target:
1732 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001733 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001734 llvm_unreachable("OpenMP Directive is not allowed");
1735 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001736 llvm_unreachable("Unknown OpenMP directive");
1737 }
1738}
1739
Alexey Bataev3392d762016-02-16 11:18:12 +00001740static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001741 Expr *CaptureExpr, bool WithInit,
1742 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001743 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001744 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001745 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001746 QualType Ty = Init->getType();
1747 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1748 if (S.getLangOpts().CPlusPlus)
1749 Ty = C.getLValueReferenceType(Ty);
1750 else {
1751 Ty = C.getPointerType(Ty);
1752 ExprResult Res =
1753 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1754 if (!Res.isUsable())
1755 return nullptr;
1756 Init = Res.get();
1757 }
Alexey Bataev61205072016-03-02 04:57:40 +00001758 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001759 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001760 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1761 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001762 if (!WithInit)
1763 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001764 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001765 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1766 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001767 return CED;
1768}
1769
Alexey Bataev61205072016-03-02 04:57:40 +00001770static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1771 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001772 OMPCapturedExprDecl *CD;
1773 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1774 CD = cast<OMPCapturedExprDecl>(VD);
1775 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001776 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1777 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001778 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001779 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001780}
1781
Alexey Bataev5a3af132016-03-29 08:58:54 +00001782static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1783 if (!Ref) {
1784 auto *CD =
1785 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1786 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1787 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1788 CaptureExpr->getExprLoc());
1789 }
1790 ExprResult Res = Ref;
1791 if (!S.getLangOpts().CPlusPlus &&
1792 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1793 Ref->getType()->isPointerType())
1794 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1795 if (!Res.isUsable())
1796 return ExprError();
1797 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001798}
1799
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001800StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1801 ArrayRef<OMPClause *> Clauses) {
1802 if (!S.isUsable()) {
1803 ActOnCapturedRegionError();
1804 return StmtError();
1805 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001806
1807 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001808 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001809 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001810 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001811 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001812 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001813 Clause->getClauseKind() == OMPC_copyprivate ||
1814 (getLangOpts().OpenMPUseTLS &&
1815 getASTContext().getTargetInfo().isTLSSupported() &&
1816 Clause->getClauseKind() == OMPC_copyin)) {
1817 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001818 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001819 for (auto *VarRef : Clause->children()) {
1820 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001821 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001822 }
1823 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001824 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001825 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001826 // Mark all variables in private list clauses as used in inner region.
1827 // Required for proper codegen of combined directives.
1828 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001829 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001830 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1831 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001832 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1833 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001834 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001835 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1836 if (auto *E = C->getPostUpdateExpr())
1837 MarkDeclarationsReferencedInExpr(E);
1838 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001839 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001840 if (Clause->getClauseKind() == OMPC_schedule)
1841 SC = cast<OMPScheduleClause>(Clause);
1842 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001843 OC = cast<OMPOrderedClause>(Clause);
1844 else if (Clause->getClauseKind() == OMPC_linear)
1845 LCs.push_back(cast<OMPLinearClause>(Clause));
1846 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001847 bool ErrorFound = false;
1848 // OpenMP, 2.7.1 Loop Construct, Restrictions
1849 // The nonmonotonic modifier cannot be specified if an ordered clause is
1850 // specified.
1851 if (SC &&
1852 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1853 SC->getSecondScheduleModifier() ==
1854 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1855 OC) {
1856 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1857 ? SC->getFirstScheduleModifierLoc()
1858 : SC->getSecondScheduleModifierLoc(),
1859 diag::err_omp_schedule_nonmonotonic_ordered)
1860 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1861 ErrorFound = true;
1862 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001863 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1864 for (auto *C : LCs) {
1865 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1866 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1867 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001868 ErrorFound = true;
1869 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001870 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1871 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1872 OC->getNumForLoops()) {
1873 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1874 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1875 ErrorFound = true;
1876 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001877 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001878 ActOnCapturedRegionError();
1879 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001880 }
1881 return ActOnCapturedRegionEnd(S.get());
1882}
1883
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001884static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1885 OpenMPDirectiveKind CurrentRegion,
1886 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001887 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001888 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001889 if (Stack->getCurScope()) {
1890 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001891 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001892 bool NestingProhibited = false;
1893 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001894 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001895 enum {
1896 NoRecommend,
1897 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001898 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001899 ShouldBeInTargetRegion,
1900 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001901 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001902 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001903 // OpenMP [2.16, Nesting of Regions]
1904 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001905 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001906 // An ordered construct with the simd clause is the only OpenMP
1907 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001908 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001909 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1910 // message.
1911 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1912 ? diag::err_omp_prohibited_region_simd
1913 : diag::warn_omp_nesting_simd);
1914 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001915 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001916 if (ParentRegion == OMPD_atomic) {
1917 // OpenMP [2.16, Nesting of Regions]
1918 // OpenMP constructs may not be nested inside an atomic region.
1919 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1920 return true;
1921 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001922 if (CurrentRegion == OMPD_section) {
1923 // OpenMP [2.7.2, sections Construct, Restrictions]
1924 // Orphaned section directives are prohibited. That is, the section
1925 // directives must appear within the sections construct and must not be
1926 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001927 if (ParentRegion != OMPD_sections &&
1928 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001929 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1930 << (ParentRegion != OMPD_unknown)
1931 << getOpenMPDirectiveName(ParentRegion);
1932 return true;
1933 }
1934 return false;
1935 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001936 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001937 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001938 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00001939 if (ParentRegion == OMPD_unknown &&
1940 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001941 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001942 if (CurrentRegion == OMPD_cancellation_point ||
1943 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001944 // OpenMP [2.16, Nesting of Regions]
1945 // A cancellation point construct for which construct-type-clause is
1946 // taskgroup must be nested inside a task construct. A cancellation
1947 // point construct for which construct-type-clause is not taskgroup must
1948 // be closely nested inside an OpenMP construct that matches the type
1949 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001950 // A cancel construct for which construct-type-clause is taskgroup must be
1951 // nested inside a task construct. A cancel construct for which
1952 // construct-type-clause is not taskgroup must be closely nested inside an
1953 // OpenMP construct that matches the type specified in
1954 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001955 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001956 !((CancelRegion == OMPD_parallel &&
1957 (ParentRegion == OMPD_parallel ||
1958 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001959 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001960 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1961 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001962 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1963 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001964 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1965 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001966 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001967 // OpenMP [2.16, Nesting of Regions]
1968 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001969 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001970 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001971 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001972 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1973 // OpenMP [2.16, Nesting of Regions]
1974 // A critical region may not be nested (closely or otherwise) inside a
1975 // critical region with the same name. Note that this restriction is not
1976 // sufficient to prevent deadlock.
1977 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001978 bool DeadLock = Stack->hasDirective(
1979 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1980 const DeclarationNameInfo &DNI,
1981 SourceLocation Loc) -> bool {
1982 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1983 PreviousCriticalLoc = Loc;
1984 return true;
1985 } else
1986 return false;
1987 },
1988 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001989 if (DeadLock) {
1990 SemaRef.Diag(StartLoc,
1991 diag::err_omp_prohibited_region_critical_same_name)
1992 << CurrentName.getName();
1993 if (PreviousCriticalLoc.isValid())
1994 SemaRef.Diag(PreviousCriticalLoc,
1995 diag::note_omp_previous_critical_region);
1996 return true;
1997 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001998 } else if (CurrentRegion == OMPD_barrier) {
1999 // OpenMP [2.16, Nesting of Regions]
2000 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002001 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002002 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2003 isOpenMPTaskingDirective(ParentRegion) ||
2004 ParentRegion == OMPD_master ||
2005 ParentRegion == OMPD_critical ||
2006 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002007 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002008 !isOpenMPParallelDirective(CurrentRegion) &&
2009 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002010 // OpenMP [2.16, Nesting of Regions]
2011 // A worksharing region may not be closely nested inside a worksharing,
2012 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002013 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2014 isOpenMPTaskingDirective(ParentRegion) ||
2015 ParentRegion == OMPD_master ||
2016 ParentRegion == OMPD_critical ||
2017 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002018 Recommend = ShouldBeInParallelRegion;
2019 } else if (CurrentRegion == OMPD_ordered) {
2020 // OpenMP [2.16, Nesting of Regions]
2021 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002022 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002023 // An ordered region must be closely nested inside a loop region (or
2024 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002025 // OpenMP [2.8.1,simd Construct, Restrictions]
2026 // An ordered construct with the simd clause is the only OpenMP construct
2027 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002028 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002029 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002030 !(isOpenMPSimdDirective(ParentRegion) ||
2031 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002032 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002033 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002034 // OpenMP [2.16, Nesting of Regions]
2035 // If specified, a teams construct must be contained within a target
2036 // construct.
2037 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002038 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002039 Recommend = ShouldBeInTargetRegion;
2040 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2041 }
Kelvin Libf594a52016-12-17 05:48:59 +00002042 if (!NestingProhibited &&
2043 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2044 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2045 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002046 // OpenMP [2.16, Nesting of Regions]
2047 // distribute, parallel, parallel sections, parallel workshare, and the
2048 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2049 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002050 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2051 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002052 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002053 }
David Majnemer9d168222016-08-05 17:44:54 +00002054 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002055 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002056 // OpenMP 4.5 [2.17 Nesting of Regions]
2057 // The region associated with the distribute construct must be strictly
2058 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002059 NestingProhibited =
2060 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002061 Recommend = ShouldBeInTeamsRegion;
2062 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002063 if (!NestingProhibited &&
2064 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2065 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2066 // OpenMP 4.5 [2.17 Nesting of Regions]
2067 // If a target, target update, target data, target enter data, or
2068 // target exit data construct is encountered during execution of a
2069 // target region, the behavior is unspecified.
2070 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002071 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2072 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002073 if (isOpenMPTargetExecutionDirective(K)) {
2074 OffendingRegion = K;
2075 return true;
2076 } else
2077 return false;
2078 },
2079 false /* don't skip top directive */);
2080 CloseNesting = false;
2081 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002082 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002083 if (OrphanSeen) {
2084 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2085 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2086 } else {
2087 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2088 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2089 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2090 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002091 return true;
2092 }
2093 }
2094 return false;
2095}
2096
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002097static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2098 ArrayRef<OMPClause *> Clauses,
2099 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2100 bool ErrorFound = false;
2101 unsigned NamedModifiersNumber = 0;
2102 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2103 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002104 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002105 for (const auto *C : Clauses) {
2106 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2107 // At most one if clause without a directive-name-modifier can appear on
2108 // the directive.
2109 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2110 if (FoundNameModifiers[CurNM]) {
2111 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2112 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2113 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2114 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002115 } else if (CurNM != OMPD_unknown) {
2116 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002117 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002118 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002119 FoundNameModifiers[CurNM] = IC;
2120 if (CurNM == OMPD_unknown)
2121 continue;
2122 // Check if the specified name modifier is allowed for the current
2123 // directive.
2124 // At most one if clause with the particular directive-name-modifier can
2125 // appear on the directive.
2126 bool MatchFound = false;
2127 for (auto NM : AllowedNameModifiers) {
2128 if (CurNM == NM) {
2129 MatchFound = true;
2130 break;
2131 }
2132 }
2133 if (!MatchFound) {
2134 S.Diag(IC->getNameModifierLoc(),
2135 diag::err_omp_wrong_if_directive_name_modifier)
2136 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2137 ErrorFound = true;
2138 }
2139 }
2140 }
2141 // If any if clause on the directive includes a directive-name-modifier then
2142 // all if clauses on the directive must include a directive-name-modifier.
2143 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2144 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2145 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2146 diag::err_omp_no_more_if_clause);
2147 } else {
2148 std::string Values;
2149 std::string Sep(", ");
2150 unsigned AllowedCnt = 0;
2151 unsigned TotalAllowedNum =
2152 AllowedNameModifiers.size() - NamedModifiersNumber;
2153 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2154 ++Cnt) {
2155 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2156 if (!FoundNameModifiers[NM]) {
2157 Values += "'";
2158 Values += getOpenMPDirectiveName(NM);
2159 Values += "'";
2160 if (AllowedCnt + 2 == TotalAllowedNum)
2161 Values += " or ";
2162 else if (AllowedCnt + 1 != TotalAllowedNum)
2163 Values += Sep;
2164 ++AllowedCnt;
2165 }
2166 }
2167 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2168 diag::err_omp_unnamed_if_clause)
2169 << (TotalAllowedNum > 1) << Values;
2170 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002171 for (auto Loc : NameModifierLoc) {
2172 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2173 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002174 ErrorFound = true;
2175 }
2176 return ErrorFound;
2177}
2178
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002179StmtResult Sema::ActOnOpenMPExecutableDirective(
2180 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2181 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2182 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002183 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002184 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2185 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002186 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002187
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002188 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002189 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002190 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002191 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002192 if (AStmt) {
2193 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2194
2195 // Check default data sharing attributes for referenced variables.
2196 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2197 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2198 if (DSAChecker.isErrorFound())
2199 return StmtError();
2200 // Generate list of implicitly defined firstprivate variables.
2201 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002202
2203 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2204 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2205 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2206 SourceLocation(), SourceLocation())) {
2207 ClausesWithImplicit.push_back(Implicit);
2208 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2209 DSAChecker.getImplicitFirstprivate().size();
2210 } else
2211 ErrorFound = true;
2212 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002213 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002214
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002215 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002216 switch (Kind) {
2217 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002218 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2219 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002220 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002221 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002222 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002223 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2224 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002225 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002226 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002227 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2228 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002229 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002230 case OMPD_for_simd:
2231 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2232 EndLoc, VarsWithInheritedDSA);
2233 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002234 case OMPD_sections:
2235 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2236 EndLoc);
2237 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002238 case OMPD_section:
2239 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002240 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002241 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2242 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002243 case OMPD_single:
2244 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2245 EndLoc);
2246 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002247 case OMPD_master:
2248 assert(ClausesWithImplicit.empty() &&
2249 "No clauses are allowed for 'omp master' directive");
2250 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2251 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002252 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002253 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2254 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002255 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002256 case OMPD_parallel_for:
2257 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2258 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002259 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002260 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002261 case OMPD_parallel_for_simd:
2262 Res = ActOnOpenMPParallelForSimdDirective(
2263 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002264 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002265 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002266 case OMPD_parallel_sections:
2267 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2268 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002269 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002270 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002271 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002272 Res =
2273 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002274 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002275 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002276 case OMPD_taskyield:
2277 assert(ClausesWithImplicit.empty() &&
2278 "No clauses are allowed for 'omp taskyield' directive");
2279 assert(AStmt == nullptr &&
2280 "No associated statement allowed for 'omp taskyield' directive");
2281 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2282 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002283 case OMPD_barrier:
2284 assert(ClausesWithImplicit.empty() &&
2285 "No clauses are allowed for 'omp barrier' directive");
2286 assert(AStmt == nullptr &&
2287 "No associated statement allowed for 'omp barrier' directive");
2288 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2289 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002290 case OMPD_taskwait:
2291 assert(ClausesWithImplicit.empty() &&
2292 "No clauses are allowed for 'omp taskwait' directive");
2293 assert(AStmt == nullptr &&
2294 "No associated statement allowed for 'omp taskwait' directive");
2295 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2296 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002297 case OMPD_taskgroup:
2298 assert(ClausesWithImplicit.empty() &&
2299 "No clauses are allowed for 'omp taskgroup' directive");
2300 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2301 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002302 case OMPD_flush:
2303 assert(AStmt == nullptr &&
2304 "No associated statement allowed for 'omp flush' directive");
2305 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2306 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002307 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002308 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2309 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002310 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002311 case OMPD_atomic:
2312 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2313 EndLoc);
2314 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002315 case OMPD_teams:
2316 Res =
2317 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2318 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002319 case OMPD_target:
2320 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2321 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002322 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002323 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002324 case OMPD_target_parallel:
2325 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2326 StartLoc, EndLoc);
2327 AllowedNameModifiers.push_back(OMPD_target);
2328 AllowedNameModifiers.push_back(OMPD_parallel);
2329 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002330 case OMPD_target_parallel_for:
2331 Res = ActOnOpenMPTargetParallelForDirective(
2332 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2333 AllowedNameModifiers.push_back(OMPD_target);
2334 AllowedNameModifiers.push_back(OMPD_parallel);
2335 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002336 case OMPD_cancellation_point:
2337 assert(ClausesWithImplicit.empty() &&
2338 "No clauses are allowed for 'omp cancellation point' directive");
2339 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2340 "cancellation point' directive");
2341 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2342 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002343 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002344 assert(AStmt == nullptr &&
2345 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002346 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2347 CancelRegion);
2348 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002349 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002350 case OMPD_target_data:
2351 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2352 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002353 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002354 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002355 case OMPD_target_enter_data:
2356 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2357 EndLoc);
2358 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2359 break;
Samuel Antao72590762016-01-19 20:04:50 +00002360 case OMPD_target_exit_data:
2361 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2362 EndLoc);
2363 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2364 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002365 case OMPD_taskloop:
2366 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2367 EndLoc, VarsWithInheritedDSA);
2368 AllowedNameModifiers.push_back(OMPD_taskloop);
2369 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002370 case OMPD_taskloop_simd:
2371 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2372 EndLoc, VarsWithInheritedDSA);
2373 AllowedNameModifiers.push_back(OMPD_taskloop);
2374 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002375 case OMPD_distribute:
2376 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2377 EndLoc, VarsWithInheritedDSA);
2378 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002379 case OMPD_target_update:
2380 assert(!AStmt && "Statement is not allowed for target update");
2381 Res =
2382 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2383 AllowedNameModifiers.push_back(OMPD_target_update);
2384 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002385 case OMPD_distribute_parallel_for:
2386 Res = ActOnOpenMPDistributeParallelForDirective(
2387 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2388 AllowedNameModifiers.push_back(OMPD_parallel);
2389 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002390 case OMPD_distribute_parallel_for_simd:
2391 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2392 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2393 AllowedNameModifiers.push_back(OMPD_parallel);
2394 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002395 case OMPD_distribute_simd:
2396 Res = ActOnOpenMPDistributeSimdDirective(
2397 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2398 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002399 case OMPD_target_parallel_for_simd:
2400 Res = ActOnOpenMPTargetParallelForSimdDirective(
2401 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2402 AllowedNameModifiers.push_back(OMPD_target);
2403 AllowedNameModifiers.push_back(OMPD_parallel);
2404 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002405 case OMPD_target_simd:
2406 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2407 EndLoc, VarsWithInheritedDSA);
2408 AllowedNameModifiers.push_back(OMPD_target);
2409 break;
Kelvin Li02532872016-08-05 14:37:37 +00002410 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002411 Res = ActOnOpenMPTeamsDistributeDirective(
2412 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002413 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002414 case OMPD_teams_distribute_simd:
2415 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2416 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2417 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002418 case OMPD_teams_distribute_parallel_for_simd:
2419 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2420 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2421 AllowedNameModifiers.push_back(OMPD_parallel);
2422 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002423 case OMPD_teams_distribute_parallel_for:
2424 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2425 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2426 AllowedNameModifiers.push_back(OMPD_parallel);
2427 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002428 case OMPD_target_teams:
2429 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2430 EndLoc);
2431 AllowedNameModifiers.push_back(OMPD_target);
2432 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002433 case OMPD_target_teams_distribute:
2434 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2435 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2436 AllowedNameModifiers.push_back(OMPD_target);
2437 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002438 case OMPD_target_teams_distribute_parallel_for:
2439 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2440 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2441 AllowedNameModifiers.push_back(OMPD_target);
2442 AllowedNameModifiers.push_back(OMPD_parallel);
2443 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002444 case OMPD_target_teams_distribute_parallel_for_simd:
2445 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2446 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_target);
2448 AllowedNameModifiers.push_back(OMPD_parallel);
2449 break;
Kelvin Lida681182017-01-10 18:08:18 +00002450 case OMPD_target_teams_distribute_simd:
2451 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2452 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2453 AllowedNameModifiers.push_back(OMPD_target);
2454 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002455 case OMPD_declare_target:
2456 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002457 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002458 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002459 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002460 llvm_unreachable("OpenMP Directive is not allowed");
2461 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002462 llvm_unreachable("Unknown OpenMP directive");
2463 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002464
Alexey Bataev4acb8592014-07-07 13:01:15 +00002465 for (auto P : VarsWithInheritedDSA) {
2466 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2467 << P.first << P.second->getSourceRange();
2468 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002469 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2470
2471 if (!AllowedNameModifiers.empty())
2472 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2473 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002474
Alexey Bataeved09d242014-05-28 05:53:51 +00002475 if (ErrorFound)
2476 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002477 return Res;
2478}
2479
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002480Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2481 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002482 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002483 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2484 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002485 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002486 assert(Linears.size() == LinModifiers.size());
2487 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002488 if (!DG || DG.get().isNull())
2489 return DeclGroupPtrTy();
2490
2491 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002492 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002493 return DG;
2494 }
2495 auto *ADecl = DG.get().getSingleDecl();
2496 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2497 ADecl = FTD->getTemplatedDecl();
2498
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002499 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2500 if (!FD) {
2501 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002502 return DeclGroupPtrTy();
2503 }
2504
Alexey Bataev2af33e32016-04-07 12:45:37 +00002505 // OpenMP [2.8.2, declare simd construct, Description]
2506 // The parameter of the simdlen clause must be a constant positive integer
2507 // expression.
2508 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002509 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002510 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002511 // OpenMP [2.8.2, declare simd construct, Description]
2512 // The special this pointer can be used as if was one of the arguments to the
2513 // function in any of the linear, aligned, or uniform clauses.
2514 // The uniform clause declares one or more arguments to have an invariant
2515 // value for all concurrent invocations of the function in the execution of a
2516 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002517 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2518 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002519 for (auto *E : Uniforms) {
2520 E = E->IgnoreParenImpCasts();
2521 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2522 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2523 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2524 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002525 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2526 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002527 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002528 }
2529 if (isa<CXXThisExpr>(E)) {
2530 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002531 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002532 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002533 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2534 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002535 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002536 // OpenMP [2.8.2, declare simd construct, Description]
2537 // The aligned clause declares that the object to which each list item points
2538 // is aligned to the number of bytes expressed in the optional parameter of
2539 // the aligned clause.
2540 // The special this pointer can be used as if was one of the arguments to the
2541 // function in any of the linear, aligned, or uniform clauses.
2542 // The type of list items appearing in the aligned clause must be array,
2543 // pointer, reference to array, or reference to pointer.
2544 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2545 Expr *AlignedThis = nullptr;
2546 for (auto *E : Aligneds) {
2547 E = E->IgnoreParenImpCasts();
2548 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2549 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2550 auto *CanonPVD = PVD->getCanonicalDecl();
2551 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2552 FD->getParamDecl(PVD->getFunctionScopeIndex())
2553 ->getCanonicalDecl() == CanonPVD) {
2554 // OpenMP [2.8.1, simd construct, Restrictions]
2555 // A list-item cannot appear in more than one aligned clause.
2556 if (AlignedArgs.count(CanonPVD) > 0) {
2557 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2558 << 1 << E->getSourceRange();
2559 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2560 diag::note_omp_explicit_dsa)
2561 << getOpenMPClauseName(OMPC_aligned);
2562 continue;
2563 }
2564 AlignedArgs[CanonPVD] = E;
2565 QualType QTy = PVD->getType()
2566 .getNonReferenceType()
2567 .getUnqualifiedType()
2568 .getCanonicalType();
2569 const Type *Ty = QTy.getTypePtrOrNull();
2570 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2571 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2572 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2573 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2574 }
2575 continue;
2576 }
2577 }
2578 if (isa<CXXThisExpr>(E)) {
2579 if (AlignedThis) {
2580 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2581 << 2 << E->getSourceRange();
2582 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2583 << getOpenMPClauseName(OMPC_aligned);
2584 }
2585 AlignedThis = E;
2586 continue;
2587 }
2588 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2589 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2590 }
2591 // The optional parameter of the aligned clause, alignment, must be a constant
2592 // positive integer expression. If no optional parameter is specified,
2593 // implementation-defined default alignments for SIMD instructions on the
2594 // target platforms are assumed.
2595 SmallVector<Expr *, 4> NewAligns;
2596 for (auto *E : Alignments) {
2597 ExprResult Align;
2598 if (E)
2599 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2600 NewAligns.push_back(Align.get());
2601 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002602 // OpenMP [2.8.2, declare simd construct, Description]
2603 // The linear clause declares one or more list items to be private to a SIMD
2604 // lane and to have a linear relationship with respect to the iteration space
2605 // of a loop.
2606 // The special this pointer can be used as if was one of the arguments to the
2607 // function in any of the linear, aligned, or uniform clauses.
2608 // When a linear-step expression is specified in a linear clause it must be
2609 // either a constant integer expression or an integer-typed parameter that is
2610 // specified in a uniform clause on the directive.
2611 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2612 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2613 auto MI = LinModifiers.begin();
2614 for (auto *E : Linears) {
2615 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2616 ++MI;
2617 E = E->IgnoreParenImpCasts();
2618 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2619 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2620 auto *CanonPVD = PVD->getCanonicalDecl();
2621 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2622 FD->getParamDecl(PVD->getFunctionScopeIndex())
2623 ->getCanonicalDecl() == CanonPVD) {
2624 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2625 // A list-item cannot appear in more than one linear clause.
2626 if (LinearArgs.count(CanonPVD) > 0) {
2627 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2628 << getOpenMPClauseName(OMPC_linear)
2629 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2630 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2631 diag::note_omp_explicit_dsa)
2632 << getOpenMPClauseName(OMPC_linear);
2633 continue;
2634 }
2635 // Each argument can appear in at most one uniform or linear clause.
2636 if (UniformedArgs.count(CanonPVD) > 0) {
2637 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2638 << getOpenMPClauseName(OMPC_linear)
2639 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2640 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2641 diag::note_omp_explicit_dsa)
2642 << getOpenMPClauseName(OMPC_uniform);
2643 continue;
2644 }
2645 LinearArgs[CanonPVD] = E;
2646 if (E->isValueDependent() || E->isTypeDependent() ||
2647 E->isInstantiationDependent() ||
2648 E->containsUnexpandedParameterPack())
2649 continue;
2650 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2651 PVD->getOriginalType());
2652 continue;
2653 }
2654 }
2655 if (isa<CXXThisExpr>(E)) {
2656 if (UniformedLinearThis) {
2657 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2658 << getOpenMPClauseName(OMPC_linear)
2659 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2660 << E->getSourceRange();
2661 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2662 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2663 : OMPC_linear);
2664 continue;
2665 }
2666 UniformedLinearThis = E;
2667 if (E->isValueDependent() || E->isTypeDependent() ||
2668 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2669 continue;
2670 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2671 E->getType());
2672 continue;
2673 }
2674 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2675 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2676 }
2677 Expr *Step = nullptr;
2678 Expr *NewStep = nullptr;
2679 SmallVector<Expr *, 4> NewSteps;
2680 for (auto *E : Steps) {
2681 // Skip the same step expression, it was checked already.
2682 if (Step == E || !E) {
2683 NewSteps.push_back(E ? NewStep : nullptr);
2684 continue;
2685 }
2686 Step = E;
2687 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2688 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2689 auto *CanonPVD = PVD->getCanonicalDecl();
2690 if (UniformedArgs.count(CanonPVD) == 0) {
2691 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2692 << Step->getSourceRange();
2693 } else if (E->isValueDependent() || E->isTypeDependent() ||
2694 E->isInstantiationDependent() ||
2695 E->containsUnexpandedParameterPack() ||
2696 CanonPVD->getType()->hasIntegerRepresentation())
2697 NewSteps.push_back(Step);
2698 else {
2699 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2700 << Step->getSourceRange();
2701 }
2702 continue;
2703 }
2704 NewStep = Step;
2705 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2706 !Step->isInstantiationDependent() &&
2707 !Step->containsUnexpandedParameterPack()) {
2708 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2709 .get();
2710 if (NewStep)
2711 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2712 }
2713 NewSteps.push_back(NewStep);
2714 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002715 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2716 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002717 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002718 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2719 const_cast<Expr **>(Linears.data()), Linears.size(),
2720 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2721 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002722 ADecl->addAttr(NewAttr);
2723 return ConvertDeclToDeclGroup(ADecl);
2724}
2725
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002726StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2727 Stmt *AStmt,
2728 SourceLocation StartLoc,
2729 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002730 if (!AStmt)
2731 return StmtError();
2732
Alexey Bataev9959db52014-05-06 10:08:46 +00002733 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2734 // 1.2.2 OpenMP Language Terminology
2735 // Structured block - An executable statement with a single entry at the
2736 // top and a single exit at the bottom.
2737 // The point of exit cannot be a branch out of the structured block.
2738 // longjmp() and throw() must not violate the entry/exit criteria.
2739 CS->getCapturedDecl()->setNothrow();
2740
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002741 getCurFunction()->setHasBranchProtectedScope();
2742
Alexey Bataev25e5b442015-09-15 12:52:43 +00002743 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2744 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002745}
2746
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002747namespace {
2748/// \brief Helper class for checking canonical form of the OpenMP loops and
2749/// extracting iteration space of each loop in the loop nest, that will be used
2750/// for IR generation.
2751class OpenMPIterationSpaceChecker {
2752 /// \brief Reference to Sema.
2753 Sema &SemaRef;
2754 /// \brief A location for diagnostics (when there is no some better location).
2755 SourceLocation DefaultLoc;
2756 /// \brief A location for diagnostics (when increment is not compatible).
2757 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002758 /// \brief A source location for referring to loop init later.
2759 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002760 /// \brief A source location for referring to condition later.
2761 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002762 /// \brief A source location for referring to increment later.
2763 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002764 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002765 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002766 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002767 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002768 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002769 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002770 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002771 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002772 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002773 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002774 /// \brief This flag is true when condition is one of:
2775 /// Var < UB
2776 /// Var <= UB
2777 /// UB > Var
2778 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002779 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002780 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002781 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002782 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002783 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002784
2785public:
2786 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002787 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002788 /// \brief Check init-expr for canonical loop form and save loop counter
2789 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002790 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002791 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2792 /// for less/greater and for strict/non-strict comparison.
2793 bool CheckCond(Expr *S);
2794 /// \brief Check incr-expr for canonical loop form and return true if it
2795 /// does not conform, otherwise save loop step (#Step).
2796 bool CheckInc(Expr *S);
2797 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002798 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002799 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002800 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002801 /// \brief Source range of the loop init.
2802 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2803 /// \brief Source range of the loop condition.
2804 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2805 /// \brief Source range of the loop increment.
2806 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2807 /// \brief True if the step should be subtracted.
2808 bool ShouldSubtractStep() const { return SubtractStep; }
2809 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002810 Expr *
2811 BuildNumIterations(Scope *S, const bool LimitedType,
2812 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002813 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002814 Expr *BuildPreCond(Scope *S, Expr *Cond,
2815 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002816 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002817 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2818 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002819 /// \brief Build reference expression to the private counter be used for
2820 /// codegen.
2821 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002822 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002823 Expr *BuildCounterInit() const;
2824 /// \brief Build step of the counter be used for codegen.
2825 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002826 /// \brief Return true if any expression is dependent.
2827 bool Dependent() const;
2828
2829private:
2830 /// \brief Check the right-hand side of an assignment in the increment
2831 /// expression.
2832 bool CheckIncRHS(Expr *RHS);
2833 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002834 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002835 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002836 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002837 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002838 /// \brief Helper to set loop increment.
2839 bool SetStep(Expr *NewStep, bool Subtract);
2840};
2841
2842bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002843 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002844 assert(!LB && !UB && !Step);
2845 return false;
2846 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002847 return LCDecl->getType()->isDependentType() ||
2848 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2849 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002850}
2851
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002852static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002853 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2854 E = ExprTemp->getSubExpr();
2855
2856 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2857 E = MTE->GetTemporaryExpr();
2858
2859 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2860 E = Binder->getSubExpr();
2861
2862 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2863 E = ICE->getSubExprAsWritten();
2864 return E->IgnoreParens();
2865}
2866
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002867bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2868 Expr *NewLCRefExpr,
2869 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002870 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002871 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002872 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002873 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002874 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002875 LCDecl = getCanonicalDecl(NewLCDecl);
2876 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002877 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2878 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002879 if ((Ctor->isCopyOrMoveConstructor() ||
2880 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2881 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002882 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002883 LB = NewLB;
2884 return false;
2885}
2886
2887bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002888 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002889 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002890 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2891 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002892 if (!NewUB)
2893 return true;
2894 UB = NewUB;
2895 TestIsLessOp = LessOp;
2896 TestIsStrictOp = StrictOp;
2897 ConditionSrcRange = SR;
2898 ConditionLoc = SL;
2899 return false;
2900}
2901
2902bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2903 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002904 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002905 if (!NewStep)
2906 return true;
2907 if (!NewStep->isValueDependent()) {
2908 // Check that the step is integer expression.
2909 SourceLocation StepLoc = NewStep->getLocStart();
2910 ExprResult Val =
2911 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2912 if (Val.isInvalid())
2913 return true;
2914 NewStep = Val.get();
2915
2916 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2917 // If test-expr is of form var relational-op b and relational-op is < or
2918 // <= then incr-expr must cause var to increase on each iteration of the
2919 // loop. If test-expr is of form var relational-op b and relational-op is
2920 // > or >= then incr-expr must cause var to decrease on each iteration of
2921 // the loop.
2922 // If test-expr is of form b relational-op var and relational-op is < or
2923 // <= then incr-expr must cause var to decrease on each iteration of the
2924 // loop. If test-expr is of form b relational-op var and relational-op is
2925 // > or >= then incr-expr must cause var to increase on each iteration of
2926 // the loop.
2927 llvm::APSInt Result;
2928 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2929 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2930 bool IsConstNeg =
2931 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002932 bool IsConstPos =
2933 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002934 bool IsConstZero = IsConstant && !Result.getBoolValue();
2935 if (UB && (IsConstZero ||
2936 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002937 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002938 SemaRef.Diag(NewStep->getExprLoc(),
2939 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002940 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002941 SemaRef.Diag(ConditionLoc,
2942 diag::note_omp_loop_cond_requres_compatible_incr)
2943 << TestIsLessOp << ConditionSrcRange;
2944 return true;
2945 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002946 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002947 NewStep =
2948 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2949 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002950 Subtract = !Subtract;
2951 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002952 }
2953
2954 Step = NewStep;
2955 SubtractStep = Subtract;
2956 return false;
2957}
2958
Alexey Bataev9c821032015-04-30 04:23:23 +00002959bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002960 // Check init-expr for canonical loop form and save loop counter
2961 // variable - #Var and its initialization value - #LB.
2962 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2963 // var = lb
2964 // integer-type var = lb
2965 // random-access-iterator-type var = lb
2966 // pointer-type var = lb
2967 //
2968 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002969 if (EmitDiags) {
2970 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2971 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002972 return true;
2973 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002974 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2975 if (!ExprTemp->cleanupsHaveSideEffects())
2976 S = ExprTemp->getSubExpr();
2977
Alexander Musmana5f070a2014-10-01 06:03:56 +00002978 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002979 if (Expr *E = dyn_cast<Expr>(S))
2980 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002981 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002982 if (BO->getOpcode() == BO_Assign) {
2983 auto *LHS = BO->getLHS()->IgnoreParens();
2984 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2985 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2986 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2987 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2988 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2989 }
2990 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2991 if (ME->isArrow() &&
2992 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2993 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2994 }
2995 }
David Majnemer9d168222016-08-05 17:44:54 +00002996 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002997 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002998 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002999 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003000 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003001 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003002 SemaRef.Diag(S->getLocStart(),
3003 diag::ext_omp_loop_not_canonical_init)
3004 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003005 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003006 }
3007 }
3008 }
David Majnemer9d168222016-08-05 17:44:54 +00003009 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003010 if (CE->getOperator() == OO_Equal) {
3011 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003012 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003013 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3014 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3015 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3016 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3017 }
3018 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3019 if (ME->isArrow() &&
3020 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3021 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3022 }
3023 }
3024 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003025
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003026 if (Dependent() || SemaRef.CurContext->isDependentContext())
3027 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003028 if (EmitDiags) {
3029 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3030 << S->getSourceRange();
3031 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003032 return true;
3033}
3034
Alexey Bataev23b69422014-06-18 07:08:49 +00003035/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003036/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003037static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003038 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003039 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003040 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003041 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3042 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003043 if ((Ctor->isCopyOrMoveConstructor() ||
3044 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3045 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003046 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003047 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3048 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3049 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3050 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3051 return getCanonicalDecl(ME->getMemberDecl());
3052 return getCanonicalDecl(VD);
3053 }
3054 }
3055 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3056 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3057 return getCanonicalDecl(ME->getMemberDecl());
3058 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003059}
3060
3061bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3062 // Check test-expr for canonical form, save upper-bound UB, flags for
3063 // less/greater and for strict/non-strict comparison.
3064 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3065 // var relational-op b
3066 // b relational-op var
3067 //
3068 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003069 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003070 return true;
3071 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003072 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003073 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003074 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003075 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003076 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003077 return SetUB(BO->getRHS(),
3078 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3079 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3080 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003081 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003082 return SetUB(BO->getLHS(),
3083 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3084 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3085 BO->getSourceRange(), BO->getOperatorLoc());
3086 }
David Majnemer9d168222016-08-05 17:44:54 +00003087 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003088 if (CE->getNumArgs() == 2) {
3089 auto Op = CE->getOperator();
3090 switch (Op) {
3091 case OO_Greater:
3092 case OO_GreaterEqual:
3093 case OO_Less:
3094 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003095 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003096 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3097 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3098 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003099 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003100 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3101 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3102 CE->getOperatorLoc());
3103 break;
3104 default:
3105 break;
3106 }
3107 }
3108 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003109 if (Dependent() || SemaRef.CurContext->isDependentContext())
3110 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003112 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003113 return true;
3114}
3115
3116bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3117 // RHS of canonical loop form increment can be:
3118 // var + incr
3119 // incr + var
3120 // var - incr
3121 //
3122 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003123 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003124 if (BO->isAdditiveOp()) {
3125 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003126 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003127 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003128 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 return SetStep(BO->getLHS(), false);
3130 }
David Majnemer9d168222016-08-05 17:44:54 +00003131 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003132 bool IsAdd = CE->getOperator() == OO_Plus;
3133 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003134 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003135 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003136 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003137 return SetStep(CE->getArg(0), false);
3138 }
3139 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003140 if (Dependent() || SemaRef.CurContext->isDependentContext())
3141 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003142 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003143 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003144 return true;
3145}
3146
3147bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3148 // Check incr-expr for canonical loop form and return true if it
3149 // does not conform.
3150 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3151 // ++var
3152 // var++
3153 // --var
3154 // var--
3155 // var += incr
3156 // var -= incr
3157 // var = var + incr
3158 // var = incr + var
3159 // var = var - incr
3160 //
3161 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003162 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003163 return true;
3164 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003165 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3166 if (!ExprTemp->cleanupsHaveSideEffects())
3167 S = ExprTemp->getSubExpr();
3168
Alexander Musmana5f070a2014-10-01 06:03:56 +00003169 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003170 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003171 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003172 if (UO->isIncrementDecrementOp() &&
3173 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003174 return SetStep(SemaRef
3175 .ActOnIntegerConstant(UO->getLocStart(),
3176 (UO->isDecrementOp() ? -1 : 1))
3177 .get(),
3178 false);
3179 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003180 switch (BO->getOpcode()) {
3181 case BO_AddAssign:
3182 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003183 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003184 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3185 break;
3186 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003187 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003188 return CheckIncRHS(BO->getRHS());
3189 break;
3190 default:
3191 break;
3192 }
David Majnemer9d168222016-08-05 17:44:54 +00003193 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003194 switch (CE->getOperator()) {
3195 case OO_PlusPlus:
3196 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003197 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003198 return SetStep(SemaRef
3199 .ActOnIntegerConstant(
3200 CE->getLocStart(),
3201 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3202 .get(),
3203 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003204 break;
3205 case OO_PlusEqual:
3206 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003207 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003208 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3209 break;
3210 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003211 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003212 return CheckIncRHS(CE->getArg(1));
3213 break;
3214 default:
3215 break;
3216 }
3217 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003218 if (Dependent() || SemaRef.CurContext->isDependentContext())
3219 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003220 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003221 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003222 return true;
3223}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003224
Alexey Bataev5a3af132016-03-29 08:58:54 +00003225static ExprResult
3226tryBuildCapture(Sema &SemaRef, Expr *Capture,
3227 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003228 if (SemaRef.CurContext->isDependentContext())
3229 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003230 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3231 return SemaRef.PerformImplicitConversion(
3232 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3233 /*AllowExplicit=*/true);
3234 auto I = Captures.find(Capture);
3235 if (I != Captures.end())
3236 return buildCapture(SemaRef, Capture, I->second);
3237 DeclRefExpr *Ref = nullptr;
3238 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3239 Captures[Capture] = Ref;
3240 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003241}
3242
Alexander Musmana5f070a2014-10-01 06:03:56 +00003243/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003244Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3245 Scope *S, const bool LimitedType,
3246 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003247 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003248 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003249 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003250 SemaRef.getLangOpts().CPlusPlus) {
3251 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003252 auto *UBExpr = TestIsLessOp ? UB : LB;
3253 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003254 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3255 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003256 if (!Upper || !Lower)
3257 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003258
3259 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3260
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003261 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003262 // BuildBinOp already emitted error, this one is to point user to upper
3263 // and lower bound, and to tell what is passed to 'operator-'.
3264 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3265 << Upper->getSourceRange() << Lower->getSourceRange();
3266 return nullptr;
3267 }
3268 }
3269
3270 if (!Diff.isUsable())
3271 return nullptr;
3272
3273 // Upper - Lower [- 1]
3274 if (TestIsStrictOp)
3275 Diff = SemaRef.BuildBinOp(
3276 S, DefaultLoc, BO_Sub, Diff.get(),
3277 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3278 if (!Diff.isUsable())
3279 return nullptr;
3280
3281 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003282 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3283 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003284 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003285 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003286 if (!Diff.isUsable())
3287 return nullptr;
3288
3289 // Parentheses (for dumping/debugging purposes only).
3290 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3291 if (!Diff.isUsable())
3292 return nullptr;
3293
3294 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003295 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003296 if (!Diff.isUsable())
3297 return nullptr;
3298
Alexander Musman174b3ca2014-10-06 11:16:29 +00003299 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003300 QualType Type = Diff.get()->getType();
3301 auto &C = SemaRef.Context;
3302 bool UseVarType = VarType->hasIntegerRepresentation() &&
3303 C.getTypeSize(Type) > C.getTypeSize(VarType);
3304 if (!Type->isIntegerType() || UseVarType) {
3305 unsigned NewSize =
3306 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3307 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3308 : Type->hasSignedIntegerRepresentation();
3309 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003310 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3311 Diff = SemaRef.PerformImplicitConversion(
3312 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3313 if (!Diff.isUsable())
3314 return nullptr;
3315 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003316 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003317 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003318 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3319 if (NewSize != C.getTypeSize(Type)) {
3320 if (NewSize < C.getTypeSize(Type)) {
3321 assert(NewSize == 64 && "incorrect loop var size");
3322 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3323 << InitSrcRange << ConditionSrcRange;
3324 }
3325 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003326 NewSize, Type->hasSignedIntegerRepresentation() ||
3327 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003328 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3329 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3330 Sema::AA_Converting, true);
3331 if (!Diff.isUsable())
3332 return nullptr;
3333 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003334 }
3335 }
3336
Alexander Musmana5f070a2014-10-01 06:03:56 +00003337 return Diff.get();
3338}
3339
Alexey Bataev5a3af132016-03-29 08:58:54 +00003340Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3341 Scope *S, Expr *Cond,
3342 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003343 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3344 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3345 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003346
Alexey Bataev5a3af132016-03-29 08:58:54 +00003347 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3348 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3349 if (!NewLB.isUsable() || !NewUB.isUsable())
3350 return nullptr;
3351
Alexey Bataev62dbb972015-04-22 11:59:37 +00003352 auto CondExpr = SemaRef.BuildBinOp(
3353 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3354 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003355 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003356 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003357 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3358 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003359 CondExpr = SemaRef.PerformImplicitConversion(
3360 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3361 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003362 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003363 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3364 // Otherwise use original loop conditon and evaluate it in runtime.
3365 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3366}
3367
Alexander Musmana5f070a2014-10-01 06:03:56 +00003368/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003369DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003370 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003371 auto *VD = dyn_cast<VarDecl>(LCDecl);
3372 if (!VD) {
3373 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3374 auto *Ref = buildDeclRefExpr(
3375 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003376 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3377 // If the loop control decl is explicitly marked as private, do not mark it
3378 // as captured again.
3379 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3380 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003381 return Ref;
3382 }
3383 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003384 DefaultLoc);
3385}
3386
3387Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003388 if (LCDecl && !LCDecl->isInvalidDecl()) {
3389 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003390 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003391 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3392 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003393 if (PrivateVar->isInvalidDecl())
3394 return nullptr;
3395 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3396 }
3397 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003398}
3399
Samuel Antao4c8035b2016-12-12 18:00:20 +00003400/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003401Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3402
3403/// \brief Build step of the counter be used for codegen.
3404Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3405
3406/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003407struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003408 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003409 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003410 /// \brief This expression calculates the number of iterations in the loop.
3411 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003412 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003413 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003414 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003415 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003416 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003417 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003418 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003419 /// \brief This is step for the #CounterVar used to generate its update:
3420 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003421 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003422 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003423 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003424 /// \brief Source range of the loop init.
3425 SourceRange InitSrcRange;
3426 /// \brief Source range of the loop condition.
3427 SourceRange CondSrcRange;
3428 /// \brief Source range of the loop increment.
3429 SourceRange IncSrcRange;
3430};
3431
Alexey Bataev23b69422014-06-18 07:08:49 +00003432} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003433
Alexey Bataev9c821032015-04-30 04:23:23 +00003434void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3435 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3436 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003437 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3438 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003439 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3440 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003441 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3442 if (auto *D = ISC.GetLoopDecl()) {
3443 auto *VD = dyn_cast<VarDecl>(D);
3444 if (!VD) {
3445 if (auto *Private = IsOpenMPCapturedDecl(D))
3446 VD = Private;
3447 else {
3448 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3449 /*WithInit=*/false);
3450 VD = cast<VarDecl>(Ref->getDecl());
3451 }
3452 }
3453 DSAStack->addLoopControlVariable(D, VD);
3454 }
3455 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003456 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003457 }
3458}
3459
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003460/// \brief Called on a for stmt to check and extract its iteration space
3461/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003462static bool CheckOpenMPIterationSpace(
3463 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3464 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003465 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003466 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003467 LoopIterationSpace &ResultIterSpace,
3468 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003469 // OpenMP [2.6, Canonical Loop Form]
3470 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003471 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003472 if (!For) {
3473 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003474 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3475 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3476 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3477 if (NestedLoopCount > 1) {
3478 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3479 SemaRef.Diag(DSA.getConstructLoc(),
3480 diag::note_omp_collapse_ordered_expr)
3481 << 2 << CollapseLoopCountExpr->getSourceRange()
3482 << OrderedLoopCountExpr->getSourceRange();
3483 else if (CollapseLoopCountExpr)
3484 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3485 diag::note_omp_collapse_ordered_expr)
3486 << 0 << CollapseLoopCountExpr->getSourceRange();
3487 else
3488 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3489 diag::note_omp_collapse_ordered_expr)
3490 << 1 << OrderedLoopCountExpr->getSourceRange();
3491 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003492 return true;
3493 }
3494 assert(For->getBody());
3495
3496 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3497
3498 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003499 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003500 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003501 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003502
3503 bool HasErrors = false;
3504
3505 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003506 if (auto *LCDecl = ISC.GetLoopDecl()) {
3507 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003508
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003509 // OpenMP [2.6, Canonical Loop Form]
3510 // Var is one of the following:
3511 // A variable of signed or unsigned integer type.
3512 // For C++, a variable of a random access iterator type.
3513 // For C, a variable of a pointer type.
3514 auto VarType = LCDecl->getType().getNonReferenceType();
3515 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3516 !VarType->isPointerType() &&
3517 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3518 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3519 << SemaRef.getLangOpts().CPlusPlus;
3520 HasErrors = true;
3521 }
3522
3523 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3524 // a Construct
3525 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3526 // parallel for construct is (are) private.
3527 // The loop iteration variable in the associated for-loop of a simd
3528 // construct with just one associated for-loop is linear with a
3529 // constant-linear-step that is the increment of the associated for-loop.
3530 // Exclude loop var from the list of variables with implicitly defined data
3531 // sharing attributes.
3532 VarsWithImplicitDSA.erase(LCDecl);
3533
3534 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3535 // in a Construct, C/C++].
3536 // The loop iteration variable in the associated for-loop of a simd
3537 // construct with just one associated for-loop may be listed in a linear
3538 // clause with a constant-linear-step that is the increment of the
3539 // associated for-loop.
3540 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3541 // parallel for construct may be listed in a private or lastprivate clause.
3542 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3543 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3544 // declared in the loop and it is predetermined as a private.
3545 auto PredeterminedCKind =
3546 isOpenMPSimdDirective(DKind)
3547 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3548 : OMPC_private;
3549 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3550 DVar.CKind != PredeterminedCKind) ||
3551 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3552 isOpenMPDistributeDirective(DKind)) &&
3553 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3554 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3555 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3556 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3557 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3558 << getOpenMPClauseName(PredeterminedCKind);
3559 if (DVar.RefExpr == nullptr)
3560 DVar.CKind = PredeterminedCKind;
3561 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3562 HasErrors = true;
3563 } else if (LoopDeclRefExpr != nullptr) {
3564 // Make the loop iteration variable private (for worksharing constructs),
3565 // linear (for simd directives with the only one associated loop) or
3566 // lastprivate (for simd directives with several collapsed or ordered
3567 // loops).
3568 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003569 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3570 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003571 /*FromParent=*/false);
3572 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3573 }
3574
3575 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3576
3577 // Check test-expr.
3578 HasErrors |= ISC.CheckCond(For->getCond());
3579
3580 // Check incr-expr.
3581 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003582 }
3583
Alexander Musmana5f070a2014-10-01 06:03:56 +00003584 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003585 return HasErrors;
3586
Alexander Musmana5f070a2014-10-01 06:03:56 +00003587 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003588 ResultIterSpace.PreCond =
3589 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003590 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003591 DSA.getCurScope(),
3592 (isOpenMPWorksharingDirective(DKind) ||
3593 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3594 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003595 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003596 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003597 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3598 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3599 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3600 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3601 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3602 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3603
Alexey Bataev62dbb972015-04-22 11:59:37 +00003604 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3605 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003606 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003607 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003608 ResultIterSpace.CounterInit == nullptr ||
3609 ResultIterSpace.CounterStep == nullptr);
3610
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003611 return HasErrors;
3612}
3613
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003614/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003615static ExprResult
3616BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3617 ExprResult Start,
3618 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003619 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003620 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3621 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003622 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003623 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003624 VarRef.get()->getType())) {
3625 NewStart = SemaRef.PerformImplicitConversion(
3626 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3627 /*AllowExplicit=*/true);
3628 if (!NewStart.isUsable())
3629 return ExprError();
3630 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003631
3632 auto Init =
3633 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3634 return Init;
3635}
3636
Alexander Musmana5f070a2014-10-01 06:03:56 +00003637/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003638static ExprResult
3639BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3640 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3641 ExprResult Step, bool Subtract,
3642 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003643 // Add parentheses (for debugging purposes only).
3644 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3645 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3646 !Step.isUsable())
3647 return ExprError();
3648
Alexey Bataev5a3af132016-03-29 08:58:54 +00003649 ExprResult NewStep = Step;
3650 if (Captures)
3651 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003652 if (NewStep.isInvalid())
3653 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003654 ExprResult Update =
3655 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003656 if (!Update.isUsable())
3657 return ExprError();
3658
Alexey Bataevc0214e02016-02-16 12:13:49 +00003659 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3660 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003661 ExprResult NewStart = Start;
3662 if (Captures)
3663 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003664 if (NewStart.isInvalid())
3665 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003666
Alexey Bataevc0214e02016-02-16 12:13:49 +00003667 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3668 ExprResult SavedUpdate = Update;
3669 ExprResult UpdateVal;
3670 if (VarRef.get()->getType()->isOverloadableType() ||
3671 NewStart.get()->getType()->isOverloadableType() ||
3672 Update.get()->getType()->isOverloadableType()) {
3673 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3674 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3675 Update =
3676 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3677 if (Update.isUsable()) {
3678 UpdateVal =
3679 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3680 VarRef.get(), SavedUpdate.get());
3681 if (UpdateVal.isUsable()) {
3682 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3683 UpdateVal.get());
3684 }
3685 }
3686 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3687 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003688
Alexey Bataevc0214e02016-02-16 12:13:49 +00003689 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3690 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3691 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3692 NewStart.get(), SavedUpdate.get());
3693 if (!Update.isUsable())
3694 return ExprError();
3695
Alexey Bataev11481f52016-02-17 10:29:05 +00003696 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3697 VarRef.get()->getType())) {
3698 Update = SemaRef.PerformImplicitConversion(
3699 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3700 if (!Update.isUsable())
3701 return ExprError();
3702 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003703
3704 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3705 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003706 return Update;
3707}
3708
3709/// \brief Convert integer expression \a E to make it have at least \a Bits
3710/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003711static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003712 if (E == nullptr)
3713 return ExprError();
3714 auto &C = SemaRef.Context;
3715 QualType OldType = E->getType();
3716 unsigned HasBits = C.getTypeSize(OldType);
3717 if (HasBits >= Bits)
3718 return ExprResult(E);
3719 // OK to convert to signed, because new type has more bits than old.
3720 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3721 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3722 true);
3723}
3724
3725/// \brief Check if the given expression \a E is a constant integer that fits
3726/// into \a Bits bits.
3727static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3728 if (E == nullptr)
3729 return false;
3730 llvm::APSInt Result;
3731 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3732 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3733 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003734}
3735
Alexey Bataev5a3af132016-03-29 08:58:54 +00003736/// Build preinits statement for the given declarations.
3737static Stmt *buildPreInits(ASTContext &Context,
3738 SmallVectorImpl<Decl *> &PreInits) {
3739 if (!PreInits.empty()) {
3740 return new (Context) DeclStmt(
3741 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3742 SourceLocation(), SourceLocation());
3743 }
3744 return nullptr;
3745}
3746
3747/// Build preinits statement for the given declarations.
3748static Stmt *buildPreInits(ASTContext &Context,
3749 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3750 if (!Captures.empty()) {
3751 SmallVector<Decl *, 16> PreInits;
3752 for (auto &Pair : Captures)
3753 PreInits.push_back(Pair.second->getDecl());
3754 return buildPreInits(Context, PreInits);
3755 }
3756 return nullptr;
3757}
3758
3759/// Build postupdate expression for the given list of postupdates expressions.
3760static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3761 Expr *PostUpdate = nullptr;
3762 if (!PostUpdates.empty()) {
3763 for (auto *E : PostUpdates) {
3764 Expr *ConvE = S.BuildCStyleCastExpr(
3765 E->getExprLoc(),
3766 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3767 E->getExprLoc(), E)
3768 .get();
3769 PostUpdate = PostUpdate
3770 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3771 PostUpdate, ConvE)
3772 .get()
3773 : ConvE;
3774 }
3775 }
3776 return PostUpdate;
3777}
3778
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003779/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003780/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3781/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003782static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003783CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3784 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3785 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003786 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003787 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003788 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003789 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003790 // Found 'collapse' clause - calculate collapse number.
3791 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003792 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003793 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003794 }
3795 if (OrderedLoopCountExpr) {
3796 // Found 'ordered' clause - calculate collapse number.
3797 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003798 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3799 if (Result.getLimitedValue() < NestedLoopCount) {
3800 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3801 diag::err_omp_wrong_ordered_loop_count)
3802 << OrderedLoopCountExpr->getSourceRange();
3803 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3804 diag::note_collapse_loop_count)
3805 << CollapseLoopCountExpr->getSourceRange();
3806 }
3807 NestedLoopCount = Result.getLimitedValue();
3808 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003809 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003810 // This is helper routine for loop directives (e.g., 'for', 'simd',
3811 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003812 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003813 SmallVector<LoopIterationSpace, 4> IterSpaces;
3814 IterSpaces.resize(NestedLoopCount);
3815 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003816 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003817 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003818 NestedLoopCount, CollapseLoopCountExpr,
3819 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003820 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003821 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003822 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003823 // OpenMP [2.8.1, simd construct, Restrictions]
3824 // All loops associated with the construct must be perfectly nested; that
3825 // is, there must be no intervening code nor any OpenMP directive between
3826 // any two loops.
3827 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003828 }
3829
Alexander Musmana5f070a2014-10-01 06:03:56 +00003830 Built.clear(/* size */ NestedLoopCount);
3831
3832 if (SemaRef.CurContext->isDependentContext())
3833 return NestedLoopCount;
3834
3835 // An example of what is generated for the following code:
3836 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003837 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003838 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003839 // for (k = 0; k < NK; ++k)
3840 // for (j = J0; j < NJ; j+=2) {
3841 // <loop body>
3842 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003843 //
3844 // We generate the code below.
3845 // Note: the loop body may be outlined in CodeGen.
3846 // Note: some counters may be C++ classes, operator- is used to find number of
3847 // iterations and operator+= to calculate counter value.
3848 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3849 // or i64 is currently supported).
3850 //
3851 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3852 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3853 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3854 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3855 // // similar updates for vars in clauses (e.g. 'linear')
3856 // <loop body (using local i and j)>
3857 // }
3858 // i = NI; // assign final values of counters
3859 // j = NJ;
3860 //
3861
3862 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3863 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003864 // Precondition tests if there is at least one iteration (all conditions are
3865 // true).
3866 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003867 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003868 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003869 32 /* Bits */, SemaRef
3870 .PerformImplicitConversion(
3871 N0->IgnoreImpCasts(), N0->getType(),
3872 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003873 .get(),
3874 SemaRef);
3875 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003876 64 /* Bits */, SemaRef
3877 .PerformImplicitConversion(
3878 N0->IgnoreImpCasts(), N0->getType(),
3879 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003880 .get(),
3881 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003882
3883 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3884 return NestedLoopCount;
3885
3886 auto &C = SemaRef.Context;
3887 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3888
3889 Scope *CurScope = DSA.getCurScope();
3890 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003891 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003892 PreCond =
3893 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3894 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003895 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003896 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003897 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003898 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3899 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003900 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003901 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003902 SemaRef
3903 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3904 Sema::AA_Converting,
3905 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003906 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003907 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003908 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003909 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003910 SemaRef
3911 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3912 Sema::AA_Converting,
3913 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003914 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003915 }
3916
3917 // Choose either the 32-bit or 64-bit version.
3918 ExprResult LastIteration = LastIteration64;
3919 if (LastIteration32.isUsable() &&
3920 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3921 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3922 FitsInto(
3923 32 /* Bits */,
3924 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3925 LastIteration64.get(), SemaRef)))
3926 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003927 QualType VType = LastIteration.get()->getType();
3928 QualType RealVType = VType;
3929 QualType StrideVType = VType;
3930 if (isOpenMPTaskLoopDirective(DKind)) {
3931 VType =
3932 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3933 StrideVType =
3934 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3935 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003936
3937 if (!LastIteration.isUsable())
3938 return 0;
3939
3940 // Save the number of iterations.
3941 ExprResult NumIterations = LastIteration;
3942 {
3943 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003944 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
3945 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003946 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3947 if (!LastIteration.isUsable())
3948 return 0;
3949 }
3950
3951 // Calculate the last iteration number beforehand instead of doing this on
3952 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3953 llvm::APSInt Result;
3954 bool IsConstant =
3955 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3956 ExprResult CalcLastIteration;
3957 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003958 ExprResult SaveRef =
3959 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003960 LastIteration = SaveRef;
3961
3962 // Prepare SaveRef + 1.
3963 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003964 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003965 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3966 if (!NumIterations.isUsable())
3967 return 0;
3968 }
3969
3970 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3971
David Majnemer9d168222016-08-05 17:44:54 +00003972 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003973 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003974 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3975 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003976 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003977 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3978 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003979 SemaRef.AddInitializerToDecl(
3980 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3981 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3982
3983 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003984 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3985 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003986 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3987 /*DirectInit*/ false,
3988 /*TypeMayContainAuto*/ false);
3989
3990 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3991 // This will be used to implement clause 'lastprivate'.
3992 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003993 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3994 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003995 SemaRef.AddInitializerToDecl(
3996 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3997 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3998
3999 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004000 VarDecl *STDecl =
4001 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4002 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004003 SemaRef.AddInitializerToDecl(
4004 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4005 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4006
4007 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004008 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004009 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4010 UB.get(), LastIteration.get());
4011 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4012 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4013 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4014 CondOp.get());
4015 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004016
4017 // If we have a combined directive that combines 'distribute', 'for' or
4018 // 'simd' we need to be able to access the bounds of the schedule of the
4019 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4020 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4021 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4022 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4023
4024 // We expect to have at least 2 more parameters than the 'parallel'
4025 // directive does - the lower and upper bounds of the previous schedule.
4026 assert(CD->getNumParams() >= 4 &&
4027 "Unexpected number of parameters in loop combined directive");
4028
4029 // Set the proper type for the bounds given what we learned from the
4030 // enclosed loops.
4031 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4032 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4033
4034 // Previous lower and upper bounds are obtained from the region
4035 // parameters.
4036 PrevLB =
4037 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4038 PrevUB =
4039 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4040 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004041 }
4042
4043 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044 ExprResult IV;
4045 ExprResult Init;
4046 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004047 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4048 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004049 Expr *RHS =
4050 (isOpenMPWorksharingDirective(DKind) ||
4051 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4052 ? LB.get()
4053 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004054 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4055 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004056 }
4057
Alexander Musmanc6388682014-12-15 07:07:06 +00004058 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004059 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004060 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004061 (isOpenMPWorksharingDirective(DKind) ||
4062 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004063 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4064 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4065 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004066
4067 // Loop increment (IV = IV + 1)
4068 SourceLocation IncLoc;
4069 ExprResult Inc =
4070 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4071 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4072 if (!Inc.isUsable())
4073 return 0;
4074 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004075 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4076 if (!Inc.isUsable())
4077 return 0;
4078
4079 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4080 // Used for directives with static scheduling.
4081 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004082 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4083 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004084 // LB + ST
4085 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4086 if (!NextLB.isUsable())
4087 return 0;
4088 // LB = LB + ST
4089 NextLB =
4090 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4091 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4092 if (!NextLB.isUsable())
4093 return 0;
4094 // UB + ST
4095 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4096 if (!NextUB.isUsable())
4097 return 0;
4098 // UB = UB + ST
4099 NextUB =
4100 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4101 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4102 if (!NextUB.isUsable())
4103 return 0;
4104 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004105
4106 // Build updates and final values of the loop counters.
4107 bool HasErrors = false;
4108 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004109 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004110 Built.Updates.resize(NestedLoopCount);
4111 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004112 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004113 {
4114 ExprResult Div;
4115 // Go from inner nested loop to outer.
4116 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4117 LoopIterationSpace &IS = IterSpaces[Cnt];
4118 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4119 // Build: Iter = (IV / Div) % IS.NumIters
4120 // where Div is product of previous iterations' IS.NumIters.
4121 ExprResult Iter;
4122 if (Div.isUsable()) {
4123 Iter =
4124 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4125 } else {
4126 Iter = IV;
4127 assert((Cnt == (int)NestedLoopCount - 1) &&
4128 "unusable div expected on first iteration only");
4129 }
4130
4131 if (Cnt != 0 && Iter.isUsable())
4132 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4133 IS.NumIterations);
4134 if (!Iter.isUsable()) {
4135 HasErrors = true;
4136 break;
4137 }
4138
Alexey Bataev39f915b82015-05-08 10:41:21 +00004139 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004140 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4141 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4142 IS.CounterVar->getExprLoc(),
4143 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004144 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004145 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004146 if (!Init.isUsable()) {
4147 HasErrors = true;
4148 break;
4149 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004150 ExprResult Update = BuildCounterUpdate(
4151 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4152 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004153 if (!Update.isUsable()) {
4154 HasErrors = true;
4155 break;
4156 }
4157
4158 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4159 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004160 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004161 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004162 if (!Final.isUsable()) {
4163 HasErrors = true;
4164 break;
4165 }
4166
4167 // Build Div for the next iteration: Div <- Div * IS.NumIters
4168 if (Cnt != 0) {
4169 if (Div.isUnset())
4170 Div = IS.NumIterations;
4171 else
4172 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4173 IS.NumIterations);
4174
4175 // Add parentheses (for debugging purposes only).
4176 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004177 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004178 if (!Div.isUsable()) {
4179 HasErrors = true;
4180 break;
4181 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004182 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183 }
4184 if (!Update.isUsable() || !Final.isUsable()) {
4185 HasErrors = true;
4186 break;
4187 }
4188 // Save results
4189 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004190 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004191 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004192 Built.Updates[Cnt] = Update.get();
4193 Built.Finals[Cnt] = Final.get();
4194 }
4195 }
4196
4197 if (HasErrors)
4198 return 0;
4199
4200 // Save results
4201 Built.IterationVarRef = IV.get();
4202 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004203 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004204 Built.CalcLastIteration =
4205 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004206 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004207 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004208 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004209 Built.Init = Init.get();
4210 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004211 Built.LB = LB.get();
4212 Built.UB = UB.get();
4213 Built.IL = IL.get();
4214 Built.ST = ST.get();
4215 Built.EUB = EUB.get();
4216 Built.NLB = NextLB.get();
4217 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004218 Built.PrevLB = PrevLB.get();
4219 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004220
Alexey Bataev8b427062016-05-25 12:36:08 +00004221 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4222 // Fill data for doacross depend clauses.
4223 for (auto Pair : DSA.getDoacrossDependClauses()) {
4224 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4225 Pair.first->setCounterValue(CounterVal);
4226 else {
4227 if (NestedLoopCount != Pair.second.size() ||
4228 NestedLoopCount != LoopMultipliers.size() + 1) {
4229 // Erroneous case - clause has some problems.
4230 Pair.first->setCounterValue(CounterVal);
4231 continue;
4232 }
4233 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4234 auto I = Pair.second.rbegin();
4235 auto IS = IterSpaces.rbegin();
4236 auto ILM = LoopMultipliers.rbegin();
4237 Expr *UpCounterVal = CounterVal;
4238 Expr *Multiplier = nullptr;
4239 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4240 if (I->first) {
4241 assert(IS->CounterStep);
4242 Expr *NormalizedOffset =
4243 SemaRef
4244 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4245 I->first, IS->CounterStep)
4246 .get();
4247 if (Multiplier) {
4248 NormalizedOffset =
4249 SemaRef
4250 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4251 NormalizedOffset, Multiplier)
4252 .get();
4253 }
4254 assert(I->second == OO_Plus || I->second == OO_Minus);
4255 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004256 UpCounterVal = SemaRef
4257 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4258 UpCounterVal, NormalizedOffset)
4259 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004260 }
4261 Multiplier = *ILM;
4262 ++I;
4263 ++IS;
4264 ++ILM;
4265 }
4266 Pair.first->setCounterValue(UpCounterVal);
4267 }
4268 }
4269
Alexey Bataevabfc0692014-06-25 06:52:00 +00004270 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004271}
4272
Alexey Bataev10e775f2015-07-30 11:36:16 +00004273static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004274 auto CollapseClauses =
4275 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4276 if (CollapseClauses.begin() != CollapseClauses.end())
4277 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004278 return nullptr;
4279}
4280
Alexey Bataev10e775f2015-07-30 11:36:16 +00004281static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004282 auto OrderedClauses =
4283 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4284 if (OrderedClauses.begin() != OrderedClauses.end())
4285 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004286 return nullptr;
4287}
4288
Kelvin Lic5609492016-07-15 04:39:07 +00004289static bool checkSimdlenSafelenSpecified(Sema &S,
4290 const ArrayRef<OMPClause *> Clauses) {
4291 OMPSafelenClause *Safelen = nullptr;
4292 OMPSimdlenClause *Simdlen = nullptr;
4293
4294 for (auto *Clause : Clauses) {
4295 if (Clause->getClauseKind() == OMPC_safelen)
4296 Safelen = cast<OMPSafelenClause>(Clause);
4297 else if (Clause->getClauseKind() == OMPC_simdlen)
4298 Simdlen = cast<OMPSimdlenClause>(Clause);
4299 if (Safelen && Simdlen)
4300 break;
4301 }
4302
4303 if (Simdlen && Safelen) {
4304 llvm::APSInt SimdlenRes, SafelenRes;
4305 auto SimdlenLength = Simdlen->getSimdlen();
4306 auto SafelenLength = Safelen->getSafelen();
4307 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4308 SimdlenLength->isInstantiationDependent() ||
4309 SimdlenLength->containsUnexpandedParameterPack())
4310 return false;
4311 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4312 SafelenLength->isInstantiationDependent() ||
4313 SafelenLength->containsUnexpandedParameterPack())
4314 return false;
4315 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4316 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4317 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4318 // If both simdlen and safelen clauses are specified, the value of the
4319 // simdlen parameter must be less than or equal to the value of the safelen
4320 // parameter.
4321 if (SimdlenRes > SafelenRes) {
4322 S.Diag(SimdlenLength->getExprLoc(),
4323 diag::err_omp_wrong_simdlen_safelen_values)
4324 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4325 return true;
4326 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004327 }
4328 return false;
4329}
4330
Alexey Bataev4acb8592014-07-07 13:01:15 +00004331StmtResult Sema::ActOnOpenMPSimdDirective(
4332 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4333 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004334 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004335 if (!AStmt)
4336 return StmtError();
4337
4338 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004339 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004340 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4341 // define the nested loops number.
4342 unsigned NestedLoopCount = CheckOpenMPLoop(
4343 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4344 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004345 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004346 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004347
Alexander Musmana5f070a2014-10-01 06:03:56 +00004348 assert((CurContext->isDependentContext() || B.builtAll()) &&
4349 "omp simd loop exprs were not built");
4350
Alexander Musman3276a272015-03-21 10:12:56 +00004351 if (!CurContext->isDependentContext()) {
4352 // Finalize the clauses that need pre-built expressions for CodeGen.
4353 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004354 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004355 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004356 B.NumIterations, *this, CurScope,
4357 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004358 return StmtError();
4359 }
4360 }
4361
Kelvin Lic5609492016-07-15 04:39:07 +00004362 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004363 return StmtError();
4364
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004365 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004366 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4367 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004368}
4369
Alexey Bataev4acb8592014-07-07 13:01:15 +00004370StmtResult Sema::ActOnOpenMPForDirective(
4371 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4372 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004373 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004374 if (!AStmt)
4375 return StmtError();
4376
4377 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004378 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004379 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4380 // define the nested loops number.
4381 unsigned NestedLoopCount = CheckOpenMPLoop(
4382 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4383 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004384 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004385 return StmtError();
4386
Alexander Musmana5f070a2014-10-01 06:03:56 +00004387 assert((CurContext->isDependentContext() || B.builtAll()) &&
4388 "omp for loop exprs were not built");
4389
Alexey Bataev54acd402015-08-04 11:18:19 +00004390 if (!CurContext->isDependentContext()) {
4391 // Finalize the clauses that need pre-built expressions for CodeGen.
4392 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004393 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004394 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004395 B.NumIterations, *this, CurScope,
4396 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004397 return StmtError();
4398 }
4399 }
4400
Alexey Bataevf29276e2014-06-18 04:14:57 +00004401 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004402 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004403 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004404}
4405
Alexander Musmanf82886e2014-09-18 05:12:34 +00004406StmtResult Sema::ActOnOpenMPForSimdDirective(
4407 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4408 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004409 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004410 if (!AStmt)
4411 return StmtError();
4412
4413 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004414 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004415 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4416 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004417 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004418 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4419 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4420 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004421 if (NestedLoopCount == 0)
4422 return StmtError();
4423
Alexander Musmanc6388682014-12-15 07:07:06 +00004424 assert((CurContext->isDependentContext() || B.builtAll()) &&
4425 "omp for simd loop exprs were not built");
4426
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004427 if (!CurContext->isDependentContext()) {
4428 // Finalize the clauses that need pre-built expressions for CodeGen.
4429 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004430 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004431 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004432 B.NumIterations, *this, CurScope,
4433 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004434 return StmtError();
4435 }
4436 }
4437
Kelvin Lic5609492016-07-15 04:39:07 +00004438 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004439 return StmtError();
4440
Alexander Musmanf82886e2014-09-18 05:12:34 +00004441 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004442 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4443 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004444}
4445
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004446StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4447 Stmt *AStmt,
4448 SourceLocation StartLoc,
4449 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004450 if (!AStmt)
4451 return StmtError();
4452
4453 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004454 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004455 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004456 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004457 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004458 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004459 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004460 return StmtError();
4461 // All associated statements must be '#pragma omp section' except for
4462 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004463 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004464 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4465 if (SectionStmt)
4466 Diag(SectionStmt->getLocStart(),
4467 diag::err_omp_sections_substmt_not_section);
4468 return StmtError();
4469 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004470 cast<OMPSectionDirective>(SectionStmt)
4471 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004472 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004473 } else {
4474 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4475 return StmtError();
4476 }
4477
4478 getCurFunction()->setHasBranchProtectedScope();
4479
Alexey Bataev25e5b442015-09-15 12:52:43 +00004480 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4481 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004482}
4483
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004484StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4485 SourceLocation StartLoc,
4486 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004487 if (!AStmt)
4488 return StmtError();
4489
4490 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004491
4492 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004493 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004494
Alexey Bataev25e5b442015-09-15 12:52:43 +00004495 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4496 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004497}
4498
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004499StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4500 Stmt *AStmt,
4501 SourceLocation StartLoc,
4502 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004503 if (!AStmt)
4504 return StmtError();
4505
4506 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004507
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004508 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004509
Alexey Bataev3255bf32015-01-19 05:20:46 +00004510 // OpenMP [2.7.3, single Construct, Restrictions]
4511 // The copyprivate clause must not be used with the nowait clause.
4512 OMPClause *Nowait = nullptr;
4513 OMPClause *Copyprivate = nullptr;
4514 for (auto *Clause : Clauses) {
4515 if (Clause->getClauseKind() == OMPC_nowait)
4516 Nowait = Clause;
4517 else if (Clause->getClauseKind() == OMPC_copyprivate)
4518 Copyprivate = Clause;
4519 if (Copyprivate && Nowait) {
4520 Diag(Copyprivate->getLocStart(),
4521 diag::err_omp_single_copyprivate_with_nowait);
4522 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4523 return StmtError();
4524 }
4525 }
4526
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004527 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4528}
4529
Alexander Musman80c22892014-07-17 08:54:58 +00004530StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4531 SourceLocation StartLoc,
4532 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004533 if (!AStmt)
4534 return StmtError();
4535
4536 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004537
4538 getCurFunction()->setHasBranchProtectedScope();
4539
4540 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4541}
4542
Alexey Bataev28c75412015-12-15 08:19:24 +00004543StmtResult Sema::ActOnOpenMPCriticalDirective(
4544 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4545 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004546 if (!AStmt)
4547 return StmtError();
4548
4549 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004550
Alexey Bataev28c75412015-12-15 08:19:24 +00004551 bool ErrorFound = false;
4552 llvm::APSInt Hint;
4553 SourceLocation HintLoc;
4554 bool DependentHint = false;
4555 for (auto *C : Clauses) {
4556 if (C->getClauseKind() == OMPC_hint) {
4557 if (!DirName.getName()) {
4558 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4559 ErrorFound = true;
4560 }
4561 Expr *E = cast<OMPHintClause>(C)->getHint();
4562 if (E->isTypeDependent() || E->isValueDependent() ||
4563 E->isInstantiationDependent())
4564 DependentHint = true;
4565 else {
4566 Hint = E->EvaluateKnownConstInt(Context);
4567 HintLoc = C->getLocStart();
4568 }
4569 }
4570 }
4571 if (ErrorFound)
4572 return StmtError();
4573 auto Pair = DSAStack->getCriticalWithHint(DirName);
4574 if (Pair.first && DirName.getName() && !DependentHint) {
4575 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4576 Diag(StartLoc, diag::err_omp_critical_with_hint);
4577 if (HintLoc.isValid()) {
4578 Diag(HintLoc, diag::note_omp_critical_hint_here)
4579 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4580 } else
4581 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4582 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4583 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4584 << 1
4585 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4586 /*Radix=*/10, /*Signed=*/false);
4587 } else
4588 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4589 }
4590 }
4591
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004592 getCurFunction()->setHasBranchProtectedScope();
4593
Alexey Bataev28c75412015-12-15 08:19:24 +00004594 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4595 Clauses, AStmt);
4596 if (!Pair.first && DirName.getName() && !DependentHint)
4597 DSAStack->addCriticalWithHint(Dir, Hint);
4598 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004599}
4600
Alexey Bataev4acb8592014-07-07 13:01:15 +00004601StmtResult Sema::ActOnOpenMPParallelForDirective(
4602 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4603 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004604 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004605 if (!AStmt)
4606 return StmtError();
4607
Alexey Bataev4acb8592014-07-07 13:01:15 +00004608 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4609 // 1.2.2 OpenMP Language Terminology
4610 // Structured block - An executable statement with a single entry at the
4611 // top and a single exit at the bottom.
4612 // The point of exit cannot be a branch out of the structured block.
4613 // longjmp() and throw() must not violate the entry/exit criteria.
4614 CS->getCapturedDecl()->setNothrow();
4615
Alexander Musmanc6388682014-12-15 07:07:06 +00004616 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004617 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4618 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004619 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004620 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4621 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4622 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004623 if (NestedLoopCount == 0)
4624 return StmtError();
4625
Alexander Musmana5f070a2014-10-01 06:03:56 +00004626 assert((CurContext->isDependentContext() || B.builtAll()) &&
4627 "omp parallel for loop exprs were not built");
4628
Alexey Bataev54acd402015-08-04 11:18:19 +00004629 if (!CurContext->isDependentContext()) {
4630 // Finalize the clauses that need pre-built expressions for CodeGen.
4631 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004632 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004633 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004634 B.NumIterations, *this, CurScope,
4635 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004636 return StmtError();
4637 }
4638 }
4639
Alexey Bataev4acb8592014-07-07 13:01:15 +00004640 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004641 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004642 NestedLoopCount, Clauses, AStmt, B,
4643 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004644}
4645
Alexander Musmane4e893b2014-09-23 09:33:00 +00004646StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4647 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4648 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004649 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004650 if (!AStmt)
4651 return StmtError();
4652
Alexander Musmane4e893b2014-09-23 09:33:00 +00004653 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4654 // 1.2.2 OpenMP Language Terminology
4655 // Structured block - An executable statement with a single entry at the
4656 // top and a single exit at the bottom.
4657 // The point of exit cannot be a branch out of the structured block.
4658 // longjmp() and throw() must not violate the entry/exit criteria.
4659 CS->getCapturedDecl()->setNothrow();
4660
Alexander Musmanc6388682014-12-15 07:07:06 +00004661 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004662 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4663 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004664 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004665 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4666 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4667 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004668 if (NestedLoopCount == 0)
4669 return StmtError();
4670
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004671 if (!CurContext->isDependentContext()) {
4672 // Finalize the clauses that need pre-built expressions for CodeGen.
4673 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004674 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004675 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004676 B.NumIterations, *this, CurScope,
4677 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004678 return StmtError();
4679 }
4680 }
4681
Kelvin Lic5609492016-07-15 04:39:07 +00004682 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004683 return StmtError();
4684
Alexander Musmane4e893b2014-09-23 09:33:00 +00004685 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004686 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004687 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004688}
4689
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004690StmtResult
4691Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4692 Stmt *AStmt, SourceLocation StartLoc,
4693 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004694 if (!AStmt)
4695 return StmtError();
4696
4697 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004698 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004699 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004700 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004701 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004702 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004703 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004704 return StmtError();
4705 // All associated statements must be '#pragma omp section' except for
4706 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004707 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004708 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4709 if (SectionStmt)
4710 Diag(SectionStmt->getLocStart(),
4711 diag::err_omp_parallel_sections_substmt_not_section);
4712 return StmtError();
4713 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004714 cast<OMPSectionDirective>(SectionStmt)
4715 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004716 }
4717 } else {
4718 Diag(AStmt->getLocStart(),
4719 diag::err_omp_parallel_sections_not_compound_stmt);
4720 return StmtError();
4721 }
4722
4723 getCurFunction()->setHasBranchProtectedScope();
4724
Alexey Bataev25e5b442015-09-15 12:52:43 +00004725 return OMPParallelSectionsDirective::Create(
4726 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004727}
4728
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004729StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4730 Stmt *AStmt, SourceLocation StartLoc,
4731 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004732 if (!AStmt)
4733 return StmtError();
4734
David Majnemer9d168222016-08-05 17:44:54 +00004735 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004736 // 1.2.2 OpenMP Language Terminology
4737 // Structured block - An executable statement with a single entry at the
4738 // top and a single exit at the bottom.
4739 // The point of exit cannot be a branch out of the structured block.
4740 // longjmp() and throw() must not violate the entry/exit criteria.
4741 CS->getCapturedDecl()->setNothrow();
4742
4743 getCurFunction()->setHasBranchProtectedScope();
4744
Alexey Bataev25e5b442015-09-15 12:52:43 +00004745 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4746 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004747}
4748
Alexey Bataev68446b72014-07-18 07:47:19 +00004749StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4750 SourceLocation EndLoc) {
4751 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4752}
4753
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004754StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4755 SourceLocation EndLoc) {
4756 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4757}
4758
Alexey Bataev2df347a2014-07-18 10:17:07 +00004759StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4760 SourceLocation EndLoc) {
4761 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4762}
4763
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004764StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4765 SourceLocation StartLoc,
4766 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004767 if (!AStmt)
4768 return StmtError();
4769
4770 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004771
4772 getCurFunction()->setHasBranchProtectedScope();
4773
4774 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4775}
4776
Alexey Bataev6125da92014-07-21 11:26:11 +00004777StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4778 SourceLocation StartLoc,
4779 SourceLocation EndLoc) {
4780 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4781 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4782}
4783
Alexey Bataev346265e2015-09-25 10:37:12 +00004784StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4785 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004786 SourceLocation StartLoc,
4787 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004788 OMPClause *DependFound = nullptr;
4789 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004790 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004791 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004792 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004793 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004794 for (auto *C : Clauses) {
4795 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4796 DependFound = C;
4797 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4798 if (DependSourceClause) {
4799 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4800 << getOpenMPDirectiveName(OMPD_ordered)
4801 << getOpenMPClauseName(OMPC_depend) << 2;
4802 ErrorFound = true;
4803 } else
4804 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004805 if (DependSinkClause) {
4806 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4807 << 0;
4808 ErrorFound = true;
4809 }
4810 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4811 if (DependSourceClause) {
4812 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4813 << 1;
4814 ErrorFound = true;
4815 }
4816 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004817 }
4818 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004819 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004820 else if (C->getClauseKind() == OMPC_simd)
4821 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004822 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004823 if (!ErrorFound && !SC &&
4824 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004825 // OpenMP [2.8.1,simd Construct, Restrictions]
4826 // An ordered construct with the simd clause is the only OpenMP construct
4827 // that can appear in the simd region.
4828 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004829 ErrorFound = true;
4830 } else if (DependFound && (TC || SC)) {
4831 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4832 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4833 ErrorFound = true;
4834 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4835 Diag(DependFound->getLocStart(),
4836 diag::err_omp_ordered_directive_without_param);
4837 ErrorFound = true;
4838 } else if (TC || Clauses.empty()) {
4839 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4840 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4841 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4842 << (TC != nullptr);
4843 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4844 ErrorFound = true;
4845 }
4846 }
4847 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004848 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004849
4850 if (AStmt) {
4851 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4852
4853 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004854 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004855
4856 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004857}
4858
Alexey Bataev1d160b12015-03-13 12:27:31 +00004859namespace {
4860/// \brief Helper class for checking expression in 'omp atomic [update]'
4861/// construct.
4862class OpenMPAtomicUpdateChecker {
4863 /// \brief Error results for atomic update expressions.
4864 enum ExprAnalysisErrorCode {
4865 /// \brief A statement is not an expression statement.
4866 NotAnExpression,
4867 /// \brief Expression is not builtin binary or unary operation.
4868 NotABinaryOrUnaryExpression,
4869 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4870 NotAnUnaryIncDecExpression,
4871 /// \brief An expression is not of scalar type.
4872 NotAScalarType,
4873 /// \brief A binary operation is not an assignment operation.
4874 NotAnAssignmentOp,
4875 /// \brief RHS part of the binary operation is not a binary expression.
4876 NotABinaryExpression,
4877 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4878 /// expression.
4879 NotABinaryOperator,
4880 /// \brief RHS binary operation does not have reference to the updated LHS
4881 /// part.
4882 NotAnUpdateExpression,
4883 /// \brief No errors is found.
4884 NoError
4885 };
4886 /// \brief Reference to Sema.
4887 Sema &SemaRef;
4888 /// \brief A location for note diagnostics (when error is found).
4889 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004890 /// \brief 'x' lvalue part of the source atomic expression.
4891 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004892 /// \brief 'expr' rvalue part of the source atomic expression.
4893 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004894 /// \brief Helper expression of the form
4895 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4896 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4897 Expr *UpdateExpr;
4898 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4899 /// important for non-associative operations.
4900 bool IsXLHSInRHSPart;
4901 BinaryOperatorKind Op;
4902 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004903 /// \brief true if the source expression is a postfix unary operation, false
4904 /// if it is a prefix unary operation.
4905 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004906
4907public:
4908 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004909 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004910 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004911 /// \brief Check specified statement that it is suitable for 'atomic update'
4912 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004913 /// expression. If DiagId and NoteId == 0, then only check is performed
4914 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004915 /// \param DiagId Diagnostic which should be emitted if error is found.
4916 /// \param NoteId Diagnostic note for the main error message.
4917 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004918 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004919 /// \brief Return the 'x' lvalue part of the source atomic expression.
4920 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004921 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4922 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004923 /// \brief Return the update expression used in calculation of the updated
4924 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4925 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4926 Expr *getUpdateExpr() const { return UpdateExpr; }
4927 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4928 /// false otherwise.
4929 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4930
Alexey Bataevb78ca832015-04-01 03:33:17 +00004931 /// \brief true if the source expression is a postfix unary operation, false
4932 /// if it is a prefix unary operation.
4933 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4934
Alexey Bataev1d160b12015-03-13 12:27:31 +00004935private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004936 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4937 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004938};
4939} // namespace
4940
4941bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4942 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4943 ExprAnalysisErrorCode ErrorFound = NoError;
4944 SourceLocation ErrorLoc, NoteLoc;
4945 SourceRange ErrorRange, NoteRange;
4946 // Allowed constructs are:
4947 // x = x binop expr;
4948 // x = expr binop x;
4949 if (AtomicBinOp->getOpcode() == BO_Assign) {
4950 X = AtomicBinOp->getLHS();
4951 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4952 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4953 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4954 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4955 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004956 Op = AtomicInnerBinOp->getOpcode();
4957 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004958 auto *LHS = AtomicInnerBinOp->getLHS();
4959 auto *RHS = AtomicInnerBinOp->getRHS();
4960 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4961 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4962 /*Canonical=*/true);
4963 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4964 /*Canonical=*/true);
4965 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4966 /*Canonical=*/true);
4967 if (XId == LHSId) {
4968 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004969 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004970 } else if (XId == RHSId) {
4971 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004972 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004973 } else {
4974 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4975 ErrorRange = AtomicInnerBinOp->getSourceRange();
4976 NoteLoc = X->getExprLoc();
4977 NoteRange = X->getSourceRange();
4978 ErrorFound = NotAnUpdateExpression;
4979 }
4980 } else {
4981 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4982 ErrorRange = AtomicInnerBinOp->getSourceRange();
4983 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4984 NoteRange = SourceRange(NoteLoc, NoteLoc);
4985 ErrorFound = NotABinaryOperator;
4986 }
4987 } else {
4988 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4989 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4990 ErrorFound = NotABinaryExpression;
4991 }
4992 } else {
4993 ErrorLoc = AtomicBinOp->getExprLoc();
4994 ErrorRange = AtomicBinOp->getSourceRange();
4995 NoteLoc = AtomicBinOp->getOperatorLoc();
4996 NoteRange = SourceRange(NoteLoc, NoteLoc);
4997 ErrorFound = NotAnAssignmentOp;
4998 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004999 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005000 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5001 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5002 return true;
5003 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005004 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005005 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005006}
5007
5008bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5009 unsigned NoteId) {
5010 ExprAnalysisErrorCode ErrorFound = NoError;
5011 SourceLocation ErrorLoc, NoteLoc;
5012 SourceRange ErrorRange, NoteRange;
5013 // Allowed constructs are:
5014 // x++;
5015 // x--;
5016 // ++x;
5017 // --x;
5018 // x binop= expr;
5019 // x = x binop expr;
5020 // x = expr binop x;
5021 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5022 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5023 if (AtomicBody->getType()->isScalarType() ||
5024 AtomicBody->isInstantiationDependent()) {
5025 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5026 AtomicBody->IgnoreParenImpCasts())) {
5027 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005028 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005029 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005030 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005031 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005032 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005033 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005034 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5035 AtomicBody->IgnoreParenImpCasts())) {
5036 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005037 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005038 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005039 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5040 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005041 // Check for Unary Operation
5042 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005043 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005044 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5045 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005046 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005047 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5048 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005049 } else {
5050 ErrorFound = NotAnUnaryIncDecExpression;
5051 ErrorLoc = AtomicUnaryOp->getExprLoc();
5052 ErrorRange = AtomicUnaryOp->getSourceRange();
5053 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5054 NoteRange = SourceRange(NoteLoc, NoteLoc);
5055 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005056 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005057 ErrorFound = NotABinaryOrUnaryExpression;
5058 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5059 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5060 }
5061 } else {
5062 ErrorFound = NotAScalarType;
5063 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5064 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5065 }
5066 } else {
5067 ErrorFound = NotAnExpression;
5068 NoteLoc = ErrorLoc = S->getLocStart();
5069 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5070 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005071 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005072 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5073 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5074 return true;
5075 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005076 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005077 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005078 // Build an update expression of form 'OpaqueValueExpr(x) binop
5079 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5080 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5081 auto *OVEX = new (SemaRef.getASTContext())
5082 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5083 auto *OVEExpr = new (SemaRef.getASTContext())
5084 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5085 auto Update =
5086 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5087 IsXLHSInRHSPart ? OVEExpr : OVEX);
5088 if (Update.isInvalid())
5089 return true;
5090 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5091 Sema::AA_Casting);
5092 if (Update.isInvalid())
5093 return true;
5094 UpdateExpr = Update.get();
5095 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005096 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005097}
5098
Alexey Bataev0162e452014-07-22 10:10:35 +00005099StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5100 Stmt *AStmt,
5101 SourceLocation StartLoc,
5102 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005103 if (!AStmt)
5104 return StmtError();
5105
David Majnemer9d168222016-08-05 17:44:54 +00005106 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005107 // 1.2.2 OpenMP Language Terminology
5108 // Structured block - An executable statement with a single entry at the
5109 // top and a single exit at the bottom.
5110 // The point of exit cannot be a branch out of the structured block.
5111 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005112 OpenMPClauseKind AtomicKind = OMPC_unknown;
5113 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005114 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005115 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005116 C->getClauseKind() == OMPC_update ||
5117 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005118 if (AtomicKind != OMPC_unknown) {
5119 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5120 << SourceRange(C->getLocStart(), C->getLocEnd());
5121 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5122 << getOpenMPClauseName(AtomicKind);
5123 } else {
5124 AtomicKind = C->getClauseKind();
5125 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005126 }
5127 }
5128 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005129
Alexey Bataev459dec02014-07-24 06:46:57 +00005130 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005131 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5132 Body = EWC->getSubExpr();
5133
Alexey Bataev62cec442014-11-18 10:14:22 +00005134 Expr *X = nullptr;
5135 Expr *V = nullptr;
5136 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005137 Expr *UE = nullptr;
5138 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005139 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005140 // OpenMP [2.12.6, atomic Construct]
5141 // In the next expressions:
5142 // * x and v (as applicable) are both l-value expressions with scalar type.
5143 // * During the execution of an atomic region, multiple syntactic
5144 // occurrences of x must designate the same storage location.
5145 // * Neither of v and expr (as applicable) may access the storage location
5146 // designated by x.
5147 // * Neither of x and expr (as applicable) may access the storage location
5148 // designated by v.
5149 // * expr is an expression with scalar type.
5150 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5151 // * binop, binop=, ++, and -- are not overloaded operators.
5152 // * The expression x binop expr must be numerically equivalent to x binop
5153 // (expr). This requirement is satisfied if the operators in expr have
5154 // precedence greater than binop, or by using parentheses around expr or
5155 // subexpressions of expr.
5156 // * The expression expr binop x must be numerically equivalent to (expr)
5157 // binop x. This requirement is satisfied if the operators in expr have
5158 // precedence equal to or greater than binop, or by using parentheses around
5159 // expr or subexpressions of expr.
5160 // * For forms that allow multiple occurrences of x, the number of times
5161 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005162 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005163 enum {
5164 NotAnExpression,
5165 NotAnAssignmentOp,
5166 NotAScalarType,
5167 NotAnLValue,
5168 NoError
5169 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005170 SourceLocation ErrorLoc, NoteLoc;
5171 SourceRange ErrorRange, NoteRange;
5172 // If clause is read:
5173 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005174 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5175 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005176 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5177 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5178 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5179 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5180 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5181 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5182 if (!X->isLValue() || !V->isLValue()) {
5183 auto NotLValueExpr = X->isLValue() ? V : X;
5184 ErrorFound = NotAnLValue;
5185 ErrorLoc = AtomicBinOp->getExprLoc();
5186 ErrorRange = AtomicBinOp->getSourceRange();
5187 NoteLoc = NotLValueExpr->getExprLoc();
5188 NoteRange = NotLValueExpr->getSourceRange();
5189 }
5190 } else if (!X->isInstantiationDependent() ||
5191 !V->isInstantiationDependent()) {
5192 auto NotScalarExpr =
5193 (X->isInstantiationDependent() || X->getType()->isScalarType())
5194 ? V
5195 : X;
5196 ErrorFound = NotAScalarType;
5197 ErrorLoc = AtomicBinOp->getExprLoc();
5198 ErrorRange = AtomicBinOp->getSourceRange();
5199 NoteLoc = NotScalarExpr->getExprLoc();
5200 NoteRange = NotScalarExpr->getSourceRange();
5201 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005202 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005203 ErrorFound = NotAnAssignmentOp;
5204 ErrorLoc = AtomicBody->getExprLoc();
5205 ErrorRange = AtomicBody->getSourceRange();
5206 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5207 : AtomicBody->getExprLoc();
5208 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5209 : AtomicBody->getSourceRange();
5210 }
5211 } else {
5212 ErrorFound = NotAnExpression;
5213 NoteLoc = ErrorLoc = Body->getLocStart();
5214 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005215 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005216 if (ErrorFound != NoError) {
5217 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5218 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005219 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5220 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005221 return StmtError();
5222 } else if (CurContext->isDependentContext())
5223 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005224 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005225 enum {
5226 NotAnExpression,
5227 NotAnAssignmentOp,
5228 NotAScalarType,
5229 NotAnLValue,
5230 NoError
5231 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005232 SourceLocation ErrorLoc, NoteLoc;
5233 SourceRange ErrorRange, NoteRange;
5234 // If clause is write:
5235 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005236 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5237 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005238 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5239 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005240 X = AtomicBinOp->getLHS();
5241 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005242 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5243 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5244 if (!X->isLValue()) {
5245 ErrorFound = NotAnLValue;
5246 ErrorLoc = AtomicBinOp->getExprLoc();
5247 ErrorRange = AtomicBinOp->getSourceRange();
5248 NoteLoc = X->getExprLoc();
5249 NoteRange = X->getSourceRange();
5250 }
5251 } else if (!X->isInstantiationDependent() ||
5252 !E->isInstantiationDependent()) {
5253 auto NotScalarExpr =
5254 (X->isInstantiationDependent() || X->getType()->isScalarType())
5255 ? E
5256 : X;
5257 ErrorFound = NotAScalarType;
5258 ErrorLoc = AtomicBinOp->getExprLoc();
5259 ErrorRange = AtomicBinOp->getSourceRange();
5260 NoteLoc = NotScalarExpr->getExprLoc();
5261 NoteRange = NotScalarExpr->getSourceRange();
5262 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005263 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005264 ErrorFound = NotAnAssignmentOp;
5265 ErrorLoc = AtomicBody->getExprLoc();
5266 ErrorRange = AtomicBody->getSourceRange();
5267 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5268 : AtomicBody->getExprLoc();
5269 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5270 : AtomicBody->getSourceRange();
5271 }
5272 } else {
5273 ErrorFound = NotAnExpression;
5274 NoteLoc = ErrorLoc = Body->getLocStart();
5275 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005276 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005277 if (ErrorFound != NoError) {
5278 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5279 << ErrorRange;
5280 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5281 << NoteRange;
5282 return StmtError();
5283 } else if (CurContext->isDependentContext())
5284 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005285 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005286 // If clause is update:
5287 // x++;
5288 // x--;
5289 // ++x;
5290 // --x;
5291 // x binop= expr;
5292 // x = x binop expr;
5293 // x = expr binop x;
5294 OpenMPAtomicUpdateChecker Checker(*this);
5295 if (Checker.checkStatement(
5296 Body, (AtomicKind == OMPC_update)
5297 ? diag::err_omp_atomic_update_not_expression_statement
5298 : diag::err_omp_atomic_not_expression_statement,
5299 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005300 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005301 if (!CurContext->isDependentContext()) {
5302 E = Checker.getExpr();
5303 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005304 UE = Checker.getUpdateExpr();
5305 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005306 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005307 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005308 enum {
5309 NotAnAssignmentOp,
5310 NotACompoundStatement,
5311 NotTwoSubstatements,
5312 NotASpecificExpression,
5313 NoError
5314 } ErrorFound = NoError;
5315 SourceLocation ErrorLoc, NoteLoc;
5316 SourceRange ErrorRange, NoteRange;
5317 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5318 // If clause is a capture:
5319 // v = x++;
5320 // v = x--;
5321 // v = ++x;
5322 // v = --x;
5323 // v = x binop= expr;
5324 // v = x = x binop expr;
5325 // v = x = expr binop x;
5326 auto *AtomicBinOp =
5327 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5328 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5329 V = AtomicBinOp->getLHS();
5330 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5331 OpenMPAtomicUpdateChecker Checker(*this);
5332 if (Checker.checkStatement(
5333 Body, diag::err_omp_atomic_capture_not_expression_statement,
5334 diag::note_omp_atomic_update))
5335 return StmtError();
5336 E = Checker.getExpr();
5337 X = Checker.getX();
5338 UE = Checker.getUpdateExpr();
5339 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5340 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005341 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005342 ErrorLoc = AtomicBody->getExprLoc();
5343 ErrorRange = AtomicBody->getSourceRange();
5344 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5345 : AtomicBody->getExprLoc();
5346 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5347 : AtomicBody->getSourceRange();
5348 ErrorFound = NotAnAssignmentOp;
5349 }
5350 if (ErrorFound != NoError) {
5351 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5352 << ErrorRange;
5353 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5354 return StmtError();
5355 } else if (CurContext->isDependentContext()) {
5356 UE = V = E = X = nullptr;
5357 }
5358 } else {
5359 // If clause is a capture:
5360 // { v = x; x = expr; }
5361 // { v = x; x++; }
5362 // { v = x; x--; }
5363 // { v = x; ++x; }
5364 // { v = x; --x; }
5365 // { v = x; x binop= expr; }
5366 // { v = x; x = x binop expr; }
5367 // { v = x; x = expr binop x; }
5368 // { x++; v = x; }
5369 // { x--; v = x; }
5370 // { ++x; v = x; }
5371 // { --x; v = x; }
5372 // { x binop= expr; v = x; }
5373 // { x = x binop expr; v = x; }
5374 // { x = expr binop x; v = x; }
5375 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5376 // Check that this is { expr1; expr2; }
5377 if (CS->size() == 2) {
5378 auto *First = CS->body_front();
5379 auto *Second = CS->body_back();
5380 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5381 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5382 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5383 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5384 // Need to find what subexpression is 'v' and what is 'x'.
5385 OpenMPAtomicUpdateChecker Checker(*this);
5386 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5387 BinaryOperator *BinOp = nullptr;
5388 if (IsUpdateExprFound) {
5389 BinOp = dyn_cast<BinaryOperator>(First);
5390 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5391 }
5392 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5393 // { v = x; x++; }
5394 // { v = x; x--; }
5395 // { v = x; ++x; }
5396 // { v = x; --x; }
5397 // { v = x; x binop= expr; }
5398 // { v = x; x = x binop expr; }
5399 // { v = x; x = expr binop x; }
5400 // Check that the first expression has form v = x.
5401 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5402 llvm::FoldingSetNodeID XId, PossibleXId;
5403 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5404 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5405 IsUpdateExprFound = XId == PossibleXId;
5406 if (IsUpdateExprFound) {
5407 V = BinOp->getLHS();
5408 X = Checker.getX();
5409 E = Checker.getExpr();
5410 UE = Checker.getUpdateExpr();
5411 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005412 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005413 }
5414 }
5415 if (!IsUpdateExprFound) {
5416 IsUpdateExprFound = !Checker.checkStatement(First);
5417 BinOp = nullptr;
5418 if (IsUpdateExprFound) {
5419 BinOp = dyn_cast<BinaryOperator>(Second);
5420 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5421 }
5422 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5423 // { x++; v = x; }
5424 // { x--; v = x; }
5425 // { ++x; v = x; }
5426 // { --x; v = x; }
5427 // { x binop= expr; v = x; }
5428 // { x = x binop expr; v = x; }
5429 // { x = expr binop x; v = x; }
5430 // Check that the second expression has form v = x.
5431 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5432 llvm::FoldingSetNodeID XId, PossibleXId;
5433 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5434 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5435 IsUpdateExprFound = XId == PossibleXId;
5436 if (IsUpdateExprFound) {
5437 V = BinOp->getLHS();
5438 X = Checker.getX();
5439 E = Checker.getExpr();
5440 UE = Checker.getUpdateExpr();
5441 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005442 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005443 }
5444 }
5445 }
5446 if (!IsUpdateExprFound) {
5447 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005448 auto *FirstExpr = dyn_cast<Expr>(First);
5449 auto *SecondExpr = dyn_cast<Expr>(Second);
5450 if (!FirstExpr || !SecondExpr ||
5451 !(FirstExpr->isInstantiationDependent() ||
5452 SecondExpr->isInstantiationDependent())) {
5453 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5454 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005455 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005456 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5457 : First->getLocStart();
5458 NoteRange = ErrorRange = FirstBinOp
5459 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005460 : SourceRange(ErrorLoc, ErrorLoc);
5461 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005462 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5463 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5464 ErrorFound = NotAnAssignmentOp;
5465 NoteLoc = ErrorLoc = SecondBinOp
5466 ? SecondBinOp->getOperatorLoc()
5467 : Second->getLocStart();
5468 NoteRange = ErrorRange =
5469 SecondBinOp ? SecondBinOp->getSourceRange()
5470 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005471 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005472 auto *PossibleXRHSInFirst =
5473 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5474 auto *PossibleXLHSInSecond =
5475 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5476 llvm::FoldingSetNodeID X1Id, X2Id;
5477 PossibleXRHSInFirst->Profile(X1Id, Context,
5478 /*Canonical=*/true);
5479 PossibleXLHSInSecond->Profile(X2Id, Context,
5480 /*Canonical=*/true);
5481 IsUpdateExprFound = X1Id == X2Id;
5482 if (IsUpdateExprFound) {
5483 V = FirstBinOp->getLHS();
5484 X = SecondBinOp->getLHS();
5485 E = SecondBinOp->getRHS();
5486 UE = nullptr;
5487 IsXLHSInRHSPart = false;
5488 IsPostfixUpdate = true;
5489 } else {
5490 ErrorFound = NotASpecificExpression;
5491 ErrorLoc = FirstBinOp->getExprLoc();
5492 ErrorRange = FirstBinOp->getSourceRange();
5493 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5494 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5495 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005496 }
5497 }
5498 }
5499 }
5500 } else {
5501 NoteLoc = ErrorLoc = Body->getLocStart();
5502 NoteRange = ErrorRange =
5503 SourceRange(Body->getLocStart(), Body->getLocStart());
5504 ErrorFound = NotTwoSubstatements;
5505 }
5506 } else {
5507 NoteLoc = ErrorLoc = Body->getLocStart();
5508 NoteRange = ErrorRange =
5509 SourceRange(Body->getLocStart(), Body->getLocStart());
5510 ErrorFound = NotACompoundStatement;
5511 }
5512 if (ErrorFound != NoError) {
5513 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5514 << ErrorRange;
5515 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5516 return StmtError();
5517 } else if (CurContext->isDependentContext()) {
5518 UE = V = E = X = nullptr;
5519 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005520 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005521 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005522
5523 getCurFunction()->setHasBranchProtectedScope();
5524
Alexey Bataev62cec442014-11-18 10:14:22 +00005525 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005526 X, V, E, UE, IsXLHSInRHSPart,
5527 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005528}
5529
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005530StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5531 Stmt *AStmt,
5532 SourceLocation StartLoc,
5533 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005534 if (!AStmt)
5535 return StmtError();
5536
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005537 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5538 // 1.2.2 OpenMP Language Terminology
5539 // Structured block - An executable statement with a single entry at the
5540 // top and a single exit at the bottom.
5541 // The point of exit cannot be a branch out of the structured block.
5542 // longjmp() and throw() must not violate the entry/exit criteria.
5543 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005544
Alexey Bataev13314bf2014-10-09 04:18:56 +00005545 // OpenMP [2.16, Nesting of Regions]
5546 // If specified, a teams construct must be contained within a target
5547 // construct. That target construct must contain no statements or directives
5548 // outside of the teams construct.
5549 if (DSAStack->hasInnerTeamsRegion()) {
5550 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5551 bool OMPTeamsFound = true;
5552 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5553 auto I = CS->body_begin();
5554 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005555 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005556 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5557 OMPTeamsFound = false;
5558 break;
5559 }
5560 ++I;
5561 }
5562 assert(I != CS->body_end() && "Not found statement");
5563 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005564 } else {
5565 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5566 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005567 }
5568 if (!OMPTeamsFound) {
5569 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5570 Diag(DSAStack->getInnerTeamsRegionLoc(),
5571 diag::note_omp_nested_teams_construct_here);
5572 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5573 << isa<OMPExecutableDirective>(S);
5574 return StmtError();
5575 }
5576 }
5577
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005578 getCurFunction()->setHasBranchProtectedScope();
5579
5580 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5581}
5582
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005583StmtResult
5584Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5585 Stmt *AStmt, SourceLocation StartLoc,
5586 SourceLocation EndLoc) {
5587 if (!AStmt)
5588 return StmtError();
5589
5590 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5591 // 1.2.2 OpenMP Language Terminology
5592 // Structured block - An executable statement with a single entry at the
5593 // top and a single exit at the bottom.
5594 // The point of exit cannot be a branch out of the structured block.
5595 // longjmp() and throw() must not violate the entry/exit criteria.
5596 CS->getCapturedDecl()->setNothrow();
5597
5598 getCurFunction()->setHasBranchProtectedScope();
5599
5600 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5601 AStmt);
5602}
5603
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005604StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5605 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5606 SourceLocation EndLoc,
5607 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5608 if (!AStmt)
5609 return StmtError();
5610
5611 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5612 // 1.2.2 OpenMP Language Terminology
5613 // Structured block - An executable statement with a single entry at the
5614 // top and a single exit at the bottom.
5615 // The point of exit cannot be a branch out of the structured block.
5616 // longjmp() and throw() must not violate the entry/exit criteria.
5617 CS->getCapturedDecl()->setNothrow();
5618
5619 OMPLoopDirective::HelperExprs B;
5620 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5621 // define the nested loops number.
5622 unsigned NestedLoopCount =
5623 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5624 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5625 VarsWithImplicitDSA, B);
5626 if (NestedLoopCount == 0)
5627 return StmtError();
5628
5629 assert((CurContext->isDependentContext() || B.builtAll()) &&
5630 "omp target parallel for loop exprs were not built");
5631
5632 if (!CurContext->isDependentContext()) {
5633 // Finalize the clauses that need pre-built expressions for CodeGen.
5634 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005635 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005636 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005637 B.NumIterations, *this, CurScope,
5638 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005639 return StmtError();
5640 }
5641 }
5642
5643 getCurFunction()->setHasBranchProtectedScope();
5644 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5645 NestedLoopCount, Clauses, AStmt,
5646 B, DSAStack->isCancelRegion());
5647}
5648
Samuel Antaodf67fc42016-01-19 19:15:56 +00005649/// \brief Check for existence of a map clause in the list of clauses.
5650static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5651 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5652 I != E; ++I) {
5653 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5654 return true;
5655 }
5656 }
5657
5658 return false;
5659}
5660
Michael Wong65f367f2015-07-21 13:44:28 +00005661StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5662 Stmt *AStmt,
5663 SourceLocation StartLoc,
5664 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005665 if (!AStmt)
5666 return StmtError();
5667
5668 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5669
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005670 // OpenMP [2.10.1, Restrictions, p. 97]
5671 // At least one map clause must appear on the directive.
5672 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005673 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5674 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005675 return StmtError();
5676 }
5677
Michael Wong65f367f2015-07-21 13:44:28 +00005678 getCurFunction()->setHasBranchProtectedScope();
5679
5680 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5681 AStmt);
5682}
5683
Samuel Antaodf67fc42016-01-19 19:15:56 +00005684StmtResult
5685Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5686 SourceLocation StartLoc,
5687 SourceLocation EndLoc) {
5688 // OpenMP [2.10.2, Restrictions, p. 99]
5689 // At least one map clause must appear on the directive.
5690 if (!HasMapClause(Clauses)) {
5691 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5692 << getOpenMPDirectiveName(OMPD_target_enter_data);
5693 return StmtError();
5694 }
5695
5696 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5697 Clauses);
5698}
5699
Samuel Antao72590762016-01-19 20:04:50 +00005700StmtResult
5701Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5702 SourceLocation StartLoc,
5703 SourceLocation EndLoc) {
5704 // OpenMP [2.10.3, Restrictions, p. 102]
5705 // At least one map clause must appear on the directive.
5706 if (!HasMapClause(Clauses)) {
5707 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5708 << getOpenMPDirectiveName(OMPD_target_exit_data);
5709 return StmtError();
5710 }
5711
5712 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5713}
5714
Samuel Antao686c70c2016-05-26 17:30:50 +00005715StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5716 SourceLocation StartLoc,
5717 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005718 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005719 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005720 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005721 seenMotionClause = true;
5722 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005723 if (!seenMotionClause) {
5724 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5725 return StmtError();
5726 }
5727 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5728}
5729
Alexey Bataev13314bf2014-10-09 04:18:56 +00005730StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5731 Stmt *AStmt, SourceLocation StartLoc,
5732 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005733 if (!AStmt)
5734 return StmtError();
5735
Alexey Bataev13314bf2014-10-09 04:18:56 +00005736 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5737 // 1.2.2 OpenMP Language Terminology
5738 // Structured block - An executable statement with a single entry at the
5739 // top and a single exit at the bottom.
5740 // The point of exit cannot be a branch out of the structured block.
5741 // longjmp() and throw() must not violate the entry/exit criteria.
5742 CS->getCapturedDecl()->setNothrow();
5743
5744 getCurFunction()->setHasBranchProtectedScope();
5745
5746 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5747}
5748
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005749StmtResult
5750Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5751 SourceLocation EndLoc,
5752 OpenMPDirectiveKind CancelRegion) {
5753 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5754 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5755 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5756 << getOpenMPDirectiveName(CancelRegion);
5757 return StmtError();
5758 }
5759 if (DSAStack->isParentNowaitRegion()) {
5760 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5761 return StmtError();
5762 }
5763 if (DSAStack->isParentOrderedRegion()) {
5764 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5765 return StmtError();
5766 }
5767 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5768 CancelRegion);
5769}
5770
Alexey Bataev87933c72015-09-18 08:07:34 +00005771StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5772 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005773 SourceLocation EndLoc,
5774 OpenMPDirectiveKind CancelRegion) {
5775 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5776 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5777 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5778 << getOpenMPDirectiveName(CancelRegion);
5779 return StmtError();
5780 }
5781 if (DSAStack->isParentNowaitRegion()) {
5782 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5783 return StmtError();
5784 }
5785 if (DSAStack->isParentOrderedRegion()) {
5786 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5787 return StmtError();
5788 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005789 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005790 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5791 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005792}
5793
Alexey Bataev382967a2015-12-08 12:06:20 +00005794static bool checkGrainsizeNumTasksClauses(Sema &S,
5795 ArrayRef<OMPClause *> Clauses) {
5796 OMPClause *PrevClause = nullptr;
5797 bool ErrorFound = false;
5798 for (auto *C : Clauses) {
5799 if (C->getClauseKind() == OMPC_grainsize ||
5800 C->getClauseKind() == OMPC_num_tasks) {
5801 if (!PrevClause)
5802 PrevClause = C;
5803 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5804 S.Diag(C->getLocStart(),
5805 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5806 << getOpenMPClauseName(C->getClauseKind())
5807 << getOpenMPClauseName(PrevClause->getClauseKind());
5808 S.Diag(PrevClause->getLocStart(),
5809 diag::note_omp_previous_grainsize_num_tasks)
5810 << getOpenMPClauseName(PrevClause->getClauseKind());
5811 ErrorFound = true;
5812 }
5813 }
5814 }
5815 return ErrorFound;
5816}
5817
Alexey Bataev49f6e782015-12-01 04:18:41 +00005818StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5820 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005821 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005822 if (!AStmt)
5823 return StmtError();
5824
5825 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5826 OMPLoopDirective::HelperExprs B;
5827 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5828 // define the nested loops number.
5829 unsigned NestedLoopCount =
5830 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005831 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005832 VarsWithImplicitDSA, B);
5833 if (NestedLoopCount == 0)
5834 return StmtError();
5835
5836 assert((CurContext->isDependentContext() || B.builtAll()) &&
5837 "omp for loop exprs were not built");
5838
Alexey Bataev382967a2015-12-08 12:06:20 +00005839 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5840 // The grainsize clause and num_tasks clause are mutually exclusive and may
5841 // not appear on the same taskloop directive.
5842 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5843 return StmtError();
5844
Alexey Bataev49f6e782015-12-01 04:18:41 +00005845 getCurFunction()->setHasBranchProtectedScope();
5846 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5847 NestedLoopCount, Clauses, AStmt, B);
5848}
5849
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005850StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5851 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5852 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005853 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005854 if (!AStmt)
5855 return StmtError();
5856
5857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5858 OMPLoopDirective::HelperExprs B;
5859 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5860 // define the nested loops number.
5861 unsigned NestedLoopCount =
5862 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5863 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5864 VarsWithImplicitDSA, B);
5865 if (NestedLoopCount == 0)
5866 return StmtError();
5867
5868 assert((CurContext->isDependentContext() || B.builtAll()) &&
5869 "omp for loop exprs were not built");
5870
Alexey Bataev5a3af132016-03-29 08:58:54 +00005871 if (!CurContext->isDependentContext()) {
5872 // Finalize the clauses that need pre-built expressions for CodeGen.
5873 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005874 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005875 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005876 B.NumIterations, *this, CurScope,
5877 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005878 return StmtError();
5879 }
5880 }
5881
Alexey Bataev382967a2015-12-08 12:06:20 +00005882 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5883 // The grainsize clause and num_tasks clause are mutually exclusive and may
5884 // not appear on the same taskloop directive.
5885 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5886 return StmtError();
5887
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005888 getCurFunction()->setHasBranchProtectedScope();
5889 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5890 NestedLoopCount, Clauses, AStmt, B);
5891}
5892
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005893StmtResult Sema::ActOnOpenMPDistributeDirective(
5894 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5895 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005896 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005897 if (!AStmt)
5898 return StmtError();
5899
5900 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5901 OMPLoopDirective::HelperExprs B;
5902 // In presence of clause 'collapse' with number of loops, it will
5903 // define the nested loops number.
5904 unsigned NestedLoopCount =
5905 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5906 nullptr /*ordered not a clause on distribute*/, AStmt,
5907 *this, *DSAStack, VarsWithImplicitDSA, B);
5908 if (NestedLoopCount == 0)
5909 return StmtError();
5910
5911 assert((CurContext->isDependentContext() || B.builtAll()) &&
5912 "omp for loop exprs were not built");
5913
5914 getCurFunction()->setHasBranchProtectedScope();
5915 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5916 NestedLoopCount, Clauses, AStmt, B);
5917}
5918
Carlo Bertolli9925f152016-06-27 14:55:37 +00005919StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5920 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5921 SourceLocation EndLoc,
5922 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5923 if (!AStmt)
5924 return StmtError();
5925
5926 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5927 // 1.2.2 OpenMP Language Terminology
5928 // Structured block - An executable statement with a single entry at the
5929 // top and a single exit at the bottom.
5930 // The point of exit cannot be a branch out of the structured block.
5931 // longjmp() and throw() must not violate the entry/exit criteria.
5932 CS->getCapturedDecl()->setNothrow();
5933
5934 OMPLoopDirective::HelperExprs B;
5935 // In presence of clause 'collapse' with number of loops, it will
5936 // define the nested loops number.
5937 unsigned NestedLoopCount = CheckOpenMPLoop(
5938 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5939 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5940 VarsWithImplicitDSA, B);
5941 if (NestedLoopCount == 0)
5942 return StmtError();
5943
5944 assert((CurContext->isDependentContext() || B.builtAll()) &&
5945 "omp for loop exprs were not built");
5946
5947 getCurFunction()->setHasBranchProtectedScope();
5948 return OMPDistributeParallelForDirective::Create(
5949 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5950}
5951
Kelvin Li4a39add2016-07-05 05:00:15 +00005952StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5953 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5954 SourceLocation EndLoc,
5955 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5956 if (!AStmt)
5957 return StmtError();
5958
5959 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5960 // 1.2.2 OpenMP Language Terminology
5961 // Structured block - An executable statement with a single entry at the
5962 // top and a single exit at the bottom.
5963 // The point of exit cannot be a branch out of the structured block.
5964 // longjmp() and throw() must not violate the entry/exit criteria.
5965 CS->getCapturedDecl()->setNothrow();
5966
5967 OMPLoopDirective::HelperExprs B;
5968 // In presence of clause 'collapse' with number of loops, it will
5969 // define the nested loops number.
5970 unsigned NestedLoopCount = CheckOpenMPLoop(
5971 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5972 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5973 VarsWithImplicitDSA, B);
5974 if (NestedLoopCount == 0)
5975 return StmtError();
5976
5977 assert((CurContext->isDependentContext() || B.builtAll()) &&
5978 "omp for loop exprs were not built");
5979
Kelvin Lic5609492016-07-15 04:39:07 +00005980 if (checkSimdlenSafelenSpecified(*this, Clauses))
5981 return StmtError();
5982
Kelvin Li4a39add2016-07-05 05:00:15 +00005983 getCurFunction()->setHasBranchProtectedScope();
5984 return OMPDistributeParallelForSimdDirective::Create(
5985 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5986}
5987
Kelvin Li787f3fc2016-07-06 04:45:38 +00005988StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5989 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5990 SourceLocation EndLoc,
5991 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5992 if (!AStmt)
5993 return StmtError();
5994
5995 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5996 // 1.2.2 OpenMP Language Terminology
5997 // Structured block - An executable statement with a single entry at the
5998 // top and a single exit at the bottom.
5999 // The point of exit cannot be a branch out of the structured block.
6000 // longjmp() and throw() must not violate the entry/exit criteria.
6001 CS->getCapturedDecl()->setNothrow();
6002
6003 OMPLoopDirective::HelperExprs B;
6004 // In presence of clause 'collapse' with number of loops, it will
6005 // define the nested loops number.
6006 unsigned NestedLoopCount =
6007 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6008 nullptr /*ordered not a clause on distribute*/, AStmt,
6009 *this, *DSAStack, VarsWithImplicitDSA, B);
6010 if (NestedLoopCount == 0)
6011 return StmtError();
6012
6013 assert((CurContext->isDependentContext() || B.builtAll()) &&
6014 "omp for loop exprs were not built");
6015
Kelvin Lic5609492016-07-15 04:39:07 +00006016 if (checkSimdlenSafelenSpecified(*this, Clauses))
6017 return StmtError();
6018
Kelvin Li787f3fc2016-07-06 04:45:38 +00006019 getCurFunction()->setHasBranchProtectedScope();
6020 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6021 NestedLoopCount, Clauses, AStmt, B);
6022}
6023
Kelvin Lia579b912016-07-14 02:54:56 +00006024StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6025 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6026 SourceLocation EndLoc,
6027 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6028 if (!AStmt)
6029 return StmtError();
6030
6031 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6032 // 1.2.2 OpenMP Language Terminology
6033 // Structured block - An executable statement with a single entry at the
6034 // top and a single exit at the bottom.
6035 // The point of exit cannot be a branch out of the structured block.
6036 // longjmp() and throw() must not violate the entry/exit criteria.
6037 CS->getCapturedDecl()->setNothrow();
6038
6039 OMPLoopDirective::HelperExprs B;
6040 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6041 // define the nested loops number.
6042 unsigned NestedLoopCount = CheckOpenMPLoop(
6043 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6044 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6045 VarsWithImplicitDSA, B);
6046 if (NestedLoopCount == 0)
6047 return StmtError();
6048
6049 assert((CurContext->isDependentContext() || B.builtAll()) &&
6050 "omp target parallel for simd loop exprs were not built");
6051
6052 if (!CurContext->isDependentContext()) {
6053 // Finalize the clauses that need pre-built expressions for CodeGen.
6054 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006055 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006056 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6057 B.NumIterations, *this, CurScope,
6058 DSAStack))
6059 return StmtError();
6060 }
6061 }
Kelvin Lic5609492016-07-15 04:39:07 +00006062 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006063 return StmtError();
6064
6065 getCurFunction()->setHasBranchProtectedScope();
6066 return OMPTargetParallelForSimdDirective::Create(
6067 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6068}
6069
Kelvin Li986330c2016-07-20 22:57:10 +00006070StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6071 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6072 SourceLocation EndLoc,
6073 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6074 if (!AStmt)
6075 return StmtError();
6076
6077 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6078 // 1.2.2 OpenMP Language Terminology
6079 // Structured block - An executable statement with a single entry at the
6080 // top and a single exit at the bottom.
6081 // The point of exit cannot be a branch out of the structured block.
6082 // longjmp() and throw() must not violate the entry/exit criteria.
6083 CS->getCapturedDecl()->setNothrow();
6084
6085 OMPLoopDirective::HelperExprs B;
6086 // In presence of clause 'collapse' with number of loops, it will define the
6087 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006088 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006089 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6090 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6091 VarsWithImplicitDSA, B);
6092 if (NestedLoopCount == 0)
6093 return StmtError();
6094
6095 assert((CurContext->isDependentContext() || B.builtAll()) &&
6096 "omp target simd loop exprs were not built");
6097
6098 if (!CurContext->isDependentContext()) {
6099 // Finalize the clauses that need pre-built expressions for CodeGen.
6100 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006101 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006102 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6103 B.NumIterations, *this, CurScope,
6104 DSAStack))
6105 return StmtError();
6106 }
6107 }
6108
6109 if (checkSimdlenSafelenSpecified(*this, Clauses))
6110 return StmtError();
6111
6112 getCurFunction()->setHasBranchProtectedScope();
6113 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6114 NestedLoopCount, Clauses, AStmt, B);
6115}
6116
Kelvin Li02532872016-08-05 14:37:37 +00006117StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6118 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6119 SourceLocation EndLoc,
6120 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6121 if (!AStmt)
6122 return StmtError();
6123
6124 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6125 // 1.2.2 OpenMP Language Terminology
6126 // Structured block - An executable statement with a single entry at the
6127 // top and a single exit at the bottom.
6128 // The point of exit cannot be a branch out of the structured block.
6129 // longjmp() and throw() must not violate the entry/exit criteria.
6130 CS->getCapturedDecl()->setNothrow();
6131
6132 OMPLoopDirective::HelperExprs B;
6133 // In presence of clause 'collapse' with number of loops, it will
6134 // define the nested loops number.
6135 unsigned NestedLoopCount =
6136 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6137 nullptr /*ordered not a clause on distribute*/, AStmt,
6138 *this, *DSAStack, VarsWithImplicitDSA, B);
6139 if (NestedLoopCount == 0)
6140 return StmtError();
6141
6142 assert((CurContext->isDependentContext() || B.builtAll()) &&
6143 "omp teams distribute loop exprs were not built");
6144
6145 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006146 return OMPTeamsDistributeDirective::Create(
6147 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006148}
6149
Kelvin Li4e325f72016-10-25 12:50:55 +00006150StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6151 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6152 SourceLocation EndLoc,
6153 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6154 if (!AStmt)
6155 return StmtError();
6156
6157 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6158 // 1.2.2 OpenMP Language Terminology
6159 // Structured block - An executable statement with a single entry at the
6160 // top and a single exit at the bottom.
6161 // The point of exit cannot be a branch out of the structured block.
6162 // longjmp() and throw() must not violate the entry/exit criteria.
6163 CS->getCapturedDecl()->setNothrow();
6164
6165 OMPLoopDirective::HelperExprs B;
6166 // In presence of clause 'collapse' with number of loops, it will
6167 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006168 unsigned NestedLoopCount = CheckOpenMPLoop(
6169 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6170 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6171 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006172
6173 if (NestedLoopCount == 0)
6174 return StmtError();
6175
6176 assert((CurContext->isDependentContext() || B.builtAll()) &&
6177 "omp teams distribute simd loop exprs were not built");
6178
6179 if (!CurContext->isDependentContext()) {
6180 // Finalize the clauses that need pre-built expressions for CodeGen.
6181 for (auto C : Clauses) {
6182 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6183 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6184 B.NumIterations, *this, CurScope,
6185 DSAStack))
6186 return StmtError();
6187 }
6188 }
6189
6190 if (checkSimdlenSafelenSpecified(*this, Clauses))
6191 return StmtError();
6192
6193 getCurFunction()->setHasBranchProtectedScope();
6194 return OMPTeamsDistributeSimdDirective::Create(
6195 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6196}
6197
Kelvin Li579e41c2016-11-30 23:51:03 +00006198StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6199 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6200 SourceLocation EndLoc,
6201 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6202 if (!AStmt)
6203 return StmtError();
6204
6205 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6206 // 1.2.2 OpenMP Language Terminology
6207 // Structured block - An executable statement with a single entry at the
6208 // top and a single exit at the bottom.
6209 // The point of exit cannot be a branch out of the structured block.
6210 // longjmp() and throw() must not violate the entry/exit criteria.
6211 CS->getCapturedDecl()->setNothrow();
6212
6213 OMPLoopDirective::HelperExprs B;
6214 // In presence of clause 'collapse' with number of loops, it will
6215 // define the nested loops number.
6216 auto NestedLoopCount = CheckOpenMPLoop(
6217 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6218 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6219 VarsWithImplicitDSA, B);
6220
6221 if (NestedLoopCount == 0)
6222 return StmtError();
6223
6224 assert((CurContext->isDependentContext() || B.builtAll()) &&
6225 "omp for loop exprs were not built");
6226
6227 if (!CurContext->isDependentContext()) {
6228 // Finalize the clauses that need pre-built expressions for CodeGen.
6229 for (auto C : Clauses) {
6230 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6231 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6232 B.NumIterations, *this, CurScope,
6233 DSAStack))
6234 return StmtError();
6235 }
6236 }
6237
6238 if (checkSimdlenSafelenSpecified(*this, Clauses))
6239 return StmtError();
6240
6241 getCurFunction()->setHasBranchProtectedScope();
6242 return OMPTeamsDistributeParallelForSimdDirective::Create(
6243 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6244}
6245
Kelvin Li7ade93f2016-12-09 03:24:30 +00006246StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6247 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6248 SourceLocation EndLoc,
6249 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6250 if (!AStmt)
6251 return StmtError();
6252
6253 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6254 // 1.2.2 OpenMP Language Terminology
6255 // Structured block - An executable statement with a single entry at the
6256 // top and a single exit at the bottom.
6257 // The point of exit cannot be a branch out of the structured block.
6258 // longjmp() and throw() must not violate the entry/exit criteria.
6259 CS->getCapturedDecl()->setNothrow();
6260
6261 OMPLoopDirective::HelperExprs B;
6262 // In presence of clause 'collapse' with number of loops, it will
6263 // define the nested loops number.
6264 unsigned NestedLoopCount = CheckOpenMPLoop(
6265 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6266 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6267 VarsWithImplicitDSA, B);
6268
6269 if (NestedLoopCount == 0)
6270 return StmtError();
6271
6272 assert((CurContext->isDependentContext() || B.builtAll()) &&
6273 "omp for loop exprs were not built");
6274
6275 if (!CurContext->isDependentContext()) {
6276 // Finalize the clauses that need pre-built expressions for CodeGen.
6277 for (auto C : Clauses) {
6278 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6279 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6280 B.NumIterations, *this, CurScope,
6281 DSAStack))
6282 return StmtError();
6283 }
6284 }
6285
6286 getCurFunction()->setHasBranchProtectedScope();
6287 return OMPTeamsDistributeParallelForDirective::Create(
6288 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6289}
6290
Kelvin Libf594a52016-12-17 05:48:59 +00006291StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6292 Stmt *AStmt,
6293 SourceLocation StartLoc,
6294 SourceLocation EndLoc) {
6295 if (!AStmt)
6296 return StmtError();
6297
6298 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6299 // 1.2.2 OpenMP Language Terminology
6300 // Structured block - An executable statement with a single entry at the
6301 // top and a single exit at the bottom.
6302 // The point of exit cannot be a branch out of the structured block.
6303 // longjmp() and throw() must not violate the entry/exit criteria.
6304 CS->getCapturedDecl()->setNothrow();
6305
6306 getCurFunction()->setHasBranchProtectedScope();
6307
6308 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6309 AStmt);
6310}
6311
Kelvin Li83c451e2016-12-25 04:52:54 +00006312StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6313 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6314 SourceLocation EndLoc,
6315 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6316 if (!AStmt)
6317 return StmtError();
6318
6319 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6320 // 1.2.2 OpenMP Language Terminology
6321 // Structured block - An executable statement with a single entry at the
6322 // top and a single exit at the bottom.
6323 // The point of exit cannot be a branch out of the structured block.
6324 // longjmp() and throw() must not violate the entry/exit criteria.
6325 CS->getCapturedDecl()->setNothrow();
6326
6327 OMPLoopDirective::HelperExprs B;
6328 // In presence of clause 'collapse' with number of loops, it will
6329 // define the nested loops number.
6330 auto NestedLoopCount = CheckOpenMPLoop(
6331 OMPD_target_teams_distribute,
6332 getCollapseNumberExpr(Clauses),
6333 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6334 VarsWithImplicitDSA, B);
6335 if (NestedLoopCount == 0)
6336 return StmtError();
6337
6338 assert((CurContext->isDependentContext() || B.builtAll()) &&
6339 "omp target teams distribute loop exprs were not built");
6340
6341 getCurFunction()->setHasBranchProtectedScope();
6342 return OMPTargetTeamsDistributeDirective::Create(
6343 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6344}
6345
Kelvin Li80e8f562016-12-29 22:16:30 +00006346StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6347 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6348 SourceLocation EndLoc,
6349 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6350 if (!AStmt)
6351 return StmtError();
6352
6353 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6354 // 1.2.2 OpenMP Language Terminology
6355 // Structured block - An executable statement with a single entry at the
6356 // top and a single exit at the bottom.
6357 // The point of exit cannot be a branch out of the structured block.
6358 // longjmp() and throw() must not violate the entry/exit criteria.
6359 CS->getCapturedDecl()->setNothrow();
6360
6361 OMPLoopDirective::HelperExprs B;
6362 // In presence of clause 'collapse' with number of loops, it will
6363 // define the nested loops number.
6364 auto NestedLoopCount = CheckOpenMPLoop(
6365 OMPD_target_teams_distribute_parallel_for,
6366 getCollapseNumberExpr(Clauses),
6367 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6368 VarsWithImplicitDSA, B);
6369 if (NestedLoopCount == 0)
6370 return StmtError();
6371
6372 assert((CurContext->isDependentContext() || B.builtAll()) &&
6373 "omp target teams distribute parallel for loop exprs were not built");
6374
6375 if (!CurContext->isDependentContext()) {
6376 // Finalize the clauses that need pre-built expressions for CodeGen.
6377 for (auto C : Clauses) {
6378 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6379 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6380 B.NumIterations, *this, CurScope,
6381 DSAStack))
6382 return StmtError();
6383 }
6384 }
6385
6386 getCurFunction()->setHasBranchProtectedScope();
6387 return OMPTargetTeamsDistributeParallelForDirective::Create(
6388 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6389}
6390
Kelvin Li1851df52017-01-03 05:23:48 +00006391StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6392 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6393 SourceLocation EndLoc,
6394 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6395 if (!AStmt)
6396 return StmtError();
6397
6398 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6399 // 1.2.2 OpenMP Language Terminology
6400 // Structured block - An executable statement with a single entry at the
6401 // top and a single exit at the bottom.
6402 // The point of exit cannot be a branch out of the structured block.
6403 // longjmp() and throw() must not violate the entry/exit criteria.
6404 CS->getCapturedDecl()->setNothrow();
6405
6406 OMPLoopDirective::HelperExprs B;
6407 // In presence of clause 'collapse' with number of loops, it will
6408 // define the nested loops number.
6409 auto NestedLoopCount = CheckOpenMPLoop(
6410 OMPD_target_teams_distribute_parallel_for_simd,
6411 getCollapseNumberExpr(Clauses),
6412 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6413 VarsWithImplicitDSA, B);
6414 if (NestedLoopCount == 0)
6415 return StmtError();
6416
6417 assert((CurContext->isDependentContext() || B.builtAll()) &&
6418 "omp target teams distribute parallel for simd loop exprs were not "
6419 "built");
6420
6421 if (!CurContext->isDependentContext()) {
6422 // Finalize the clauses that need pre-built expressions for CodeGen.
6423 for (auto C : Clauses) {
6424 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6425 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6426 B.NumIterations, *this, CurScope,
6427 DSAStack))
6428 return StmtError();
6429 }
6430 }
6431
6432 getCurFunction()->setHasBranchProtectedScope();
6433 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6434 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6435}
6436
Kelvin Lida681182017-01-10 18:08:18 +00006437StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6438 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6439 SourceLocation EndLoc,
6440 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6441 if (!AStmt)
6442 return StmtError();
6443
6444 auto *CS = cast<CapturedStmt>(AStmt);
6445 // 1.2.2 OpenMP Language Terminology
6446 // Structured block - An executable statement with a single entry at the
6447 // top and a single exit at the bottom.
6448 // The point of exit cannot be a branch out of the structured block.
6449 // longjmp() and throw() must not violate the entry/exit criteria.
6450 CS->getCapturedDecl()->setNothrow();
6451
6452 OMPLoopDirective::HelperExprs B;
6453 // In presence of clause 'collapse' with number of loops, it will
6454 // define the nested loops number.
6455 auto NestedLoopCount = CheckOpenMPLoop(
6456 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6457 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6458 VarsWithImplicitDSA, B);
6459 if (NestedLoopCount == 0)
6460 return StmtError();
6461
6462 assert((CurContext->isDependentContext() || B.builtAll()) &&
6463 "omp target teams distribute simd loop exprs were not built");
6464
6465 getCurFunction()->setHasBranchProtectedScope();
6466 return OMPTargetTeamsDistributeSimdDirective::Create(
6467 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6468}
6469
Alexey Bataeved09d242014-05-28 05:53:51 +00006470OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006471 SourceLocation StartLoc,
6472 SourceLocation LParenLoc,
6473 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006474 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006475 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006476 case OMPC_final:
6477 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6478 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006479 case OMPC_num_threads:
6480 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6481 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006482 case OMPC_safelen:
6483 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6484 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006485 case OMPC_simdlen:
6486 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6487 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006488 case OMPC_collapse:
6489 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6490 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006491 case OMPC_ordered:
6492 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6493 break;
Michael Wonge710d542015-08-07 16:16:36 +00006494 case OMPC_device:
6495 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6496 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006497 case OMPC_num_teams:
6498 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6499 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006500 case OMPC_thread_limit:
6501 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6502 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006503 case OMPC_priority:
6504 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6505 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006506 case OMPC_grainsize:
6507 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6508 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006509 case OMPC_num_tasks:
6510 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6511 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006512 case OMPC_hint:
6513 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6514 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006515 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006516 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006517 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006518 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006519 case OMPC_private:
6520 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006521 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006522 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006523 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006524 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006525 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006526 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006527 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006528 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006529 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006530 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006531 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006532 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006533 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006534 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006535 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006536 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006537 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006538 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006539 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006540 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006541 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006542 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006543 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006544 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006545 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006546 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006547 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006548 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006549 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006550 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006551 llvm_unreachable("Clause is not allowed.");
6552 }
6553 return Res;
6554}
6555
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006556OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6557 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006558 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006559 SourceLocation NameModifierLoc,
6560 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006561 SourceLocation EndLoc) {
6562 Expr *ValExpr = Condition;
6563 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6564 !Condition->isInstantiationDependent() &&
6565 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006566 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006567 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006568 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006569
Richard Smith03a4aa32016-06-23 19:02:52 +00006570 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006571 }
6572
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006573 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6574 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006575}
6576
Alexey Bataev3778b602014-07-17 07:32:53 +00006577OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6578 SourceLocation StartLoc,
6579 SourceLocation LParenLoc,
6580 SourceLocation EndLoc) {
6581 Expr *ValExpr = Condition;
6582 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6583 !Condition->isInstantiationDependent() &&
6584 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006585 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006586 if (Val.isInvalid())
6587 return nullptr;
6588
Richard Smith03a4aa32016-06-23 19:02:52 +00006589 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006590 }
6591
6592 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6593}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006594ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6595 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006596 if (!Op)
6597 return ExprError();
6598
6599 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6600 public:
6601 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006602 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006603 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6604 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006605 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6606 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006607 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6608 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006609 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6610 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006611 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6612 QualType T,
6613 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006614 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6615 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006616 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6617 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006618 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006619 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006620 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006621 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6622 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006623 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6624 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006625 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6626 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006627 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006628 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006629 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006630 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6631 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006632 llvm_unreachable("conversion functions are permitted");
6633 }
6634 } ConvertDiagnoser;
6635 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6636}
6637
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006638static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006639 OpenMPClauseKind CKind,
6640 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006641 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6642 !ValExpr->isInstantiationDependent()) {
6643 SourceLocation Loc = ValExpr->getExprLoc();
6644 ExprResult Value =
6645 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6646 if (Value.isInvalid())
6647 return false;
6648
6649 ValExpr = Value.get();
6650 // The expression must evaluate to a non-negative integer value.
6651 llvm::APSInt Result;
6652 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006653 Result.isSigned() &&
6654 !((!StrictlyPositive && Result.isNonNegative()) ||
6655 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006656 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006657 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6658 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006659 return false;
6660 }
6661 }
6662 return true;
6663}
6664
Alexey Bataev568a8332014-03-06 06:15:19 +00006665OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6666 SourceLocation StartLoc,
6667 SourceLocation LParenLoc,
6668 SourceLocation EndLoc) {
6669 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006670
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006671 // OpenMP [2.5, Restrictions]
6672 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006673 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6674 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006675 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006676
Alexey Bataeved09d242014-05-28 05:53:51 +00006677 return new (Context)
6678 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006679}
6680
Alexey Bataev62c87d22014-03-21 04:51:18 +00006681ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006682 OpenMPClauseKind CKind,
6683 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006684 if (!E)
6685 return ExprError();
6686 if (E->isValueDependent() || E->isTypeDependent() ||
6687 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006688 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006689 llvm::APSInt Result;
6690 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6691 if (ICE.isInvalid())
6692 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006693 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6694 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006695 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006696 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6697 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006698 return ExprError();
6699 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006700 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6701 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6702 << E->getSourceRange();
6703 return ExprError();
6704 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006705 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6706 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006707 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006708 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006709 return ICE;
6710}
6711
6712OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6713 SourceLocation LParenLoc,
6714 SourceLocation EndLoc) {
6715 // OpenMP [2.8.1, simd construct, Description]
6716 // The parameter of the safelen clause must be a constant
6717 // positive integer expression.
6718 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6719 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006720 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006721 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006722 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006723}
6724
Alexey Bataev66b15b52015-08-21 11:14:16 +00006725OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6726 SourceLocation LParenLoc,
6727 SourceLocation EndLoc) {
6728 // OpenMP [2.8.1, simd construct, Description]
6729 // The parameter of the simdlen clause must be a constant
6730 // positive integer expression.
6731 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6732 if (Simdlen.isInvalid())
6733 return nullptr;
6734 return new (Context)
6735 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6736}
6737
Alexander Musman64d33f12014-06-04 07:53:32 +00006738OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6739 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006740 SourceLocation LParenLoc,
6741 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006742 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006743 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006744 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006745 // The parameter of the collapse clause must be a constant
6746 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006747 ExprResult NumForLoopsResult =
6748 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6749 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006750 return nullptr;
6751 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006752 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006753}
6754
Alexey Bataev10e775f2015-07-30 11:36:16 +00006755OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6756 SourceLocation EndLoc,
6757 SourceLocation LParenLoc,
6758 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006759 // OpenMP [2.7.1, loop construct, Description]
6760 // OpenMP [2.8.1, simd construct, Description]
6761 // OpenMP [2.9.6, distribute construct, Description]
6762 // The parameter of the ordered clause must be a constant
6763 // positive integer expression if any.
6764 if (NumForLoops && LParenLoc.isValid()) {
6765 ExprResult NumForLoopsResult =
6766 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6767 if (NumForLoopsResult.isInvalid())
6768 return nullptr;
6769 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006770 } else
6771 NumForLoops = nullptr;
6772 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006773 return new (Context)
6774 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6775}
6776
Alexey Bataeved09d242014-05-28 05:53:51 +00006777OMPClause *Sema::ActOnOpenMPSimpleClause(
6778 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6779 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006780 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006781 switch (Kind) {
6782 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006783 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006784 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6785 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006786 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006787 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006788 Res = ActOnOpenMPProcBindClause(
6789 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6790 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006791 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006792 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006793 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006794 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006795 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006796 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006797 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006798 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006799 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006800 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006801 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006802 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006803 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006804 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006805 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006806 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006807 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006808 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006809 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006810 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006811 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006812 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006813 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006814 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006815 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006816 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006817 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006818 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006819 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006820 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006821 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006822 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006823 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006824 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006825 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006826 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006827 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006828 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006829 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006830 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006831 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006832 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006833 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006834 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006835 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006836 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006837 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006838 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006839 llvm_unreachable("Clause is not allowed.");
6840 }
6841 return Res;
6842}
6843
Alexey Bataev6402bca2015-12-28 07:25:51 +00006844static std::string
6845getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6846 ArrayRef<unsigned> Exclude = llvm::None) {
6847 std::string Values;
6848 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6849 unsigned Skipped = Exclude.size();
6850 auto S = Exclude.begin(), E = Exclude.end();
6851 for (unsigned i = First; i < Last; ++i) {
6852 if (std::find(S, E, i) != E) {
6853 --Skipped;
6854 continue;
6855 }
6856 Values += "'";
6857 Values += getOpenMPSimpleClauseTypeName(K, i);
6858 Values += "'";
6859 if (i == Bound - Skipped)
6860 Values += " or ";
6861 else if (i != Bound + 1 - Skipped)
6862 Values += ", ";
6863 }
6864 return Values;
6865}
6866
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006867OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6868 SourceLocation KindKwLoc,
6869 SourceLocation StartLoc,
6870 SourceLocation LParenLoc,
6871 SourceLocation EndLoc) {
6872 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006873 static_assert(OMPC_DEFAULT_unknown > 0,
6874 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006875 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006876 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6877 /*Last=*/OMPC_DEFAULT_unknown)
6878 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006879 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006880 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006881 switch (Kind) {
6882 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006883 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006884 break;
6885 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006886 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006887 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006888 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006889 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006890 break;
6891 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006892 return new (Context)
6893 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006894}
6895
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006896OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6897 SourceLocation KindKwLoc,
6898 SourceLocation StartLoc,
6899 SourceLocation LParenLoc,
6900 SourceLocation EndLoc) {
6901 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006902 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006903 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6904 /*Last=*/OMPC_PROC_BIND_unknown)
6905 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006906 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006907 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006908 return new (Context)
6909 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006910}
6911
Alexey Bataev56dafe82014-06-20 07:16:17 +00006912OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006913 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006914 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006915 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006916 SourceLocation EndLoc) {
6917 OMPClause *Res = nullptr;
6918 switch (Kind) {
6919 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006920 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6921 assert(Argument.size() == NumberOfElements &&
6922 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006923 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006924 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6925 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6926 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6927 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6928 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006929 break;
6930 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006931 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6932 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6933 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6934 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006935 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006936 case OMPC_dist_schedule:
6937 Res = ActOnOpenMPDistScheduleClause(
6938 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6939 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6940 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006941 case OMPC_defaultmap:
6942 enum { Modifier, DefaultmapKind };
6943 Res = ActOnOpenMPDefaultmapClause(
6944 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6945 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006946 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6947 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006948 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006949 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006950 case OMPC_num_threads:
6951 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006952 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006953 case OMPC_collapse:
6954 case OMPC_default:
6955 case OMPC_proc_bind:
6956 case OMPC_private:
6957 case OMPC_firstprivate:
6958 case OMPC_lastprivate:
6959 case OMPC_shared:
6960 case OMPC_reduction:
6961 case OMPC_linear:
6962 case OMPC_aligned:
6963 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006964 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006965 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006966 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006967 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006968 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006969 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006970 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006971 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006972 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006973 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006974 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006975 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006976 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006977 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006978 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006979 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006980 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006981 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006982 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006983 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006984 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006985 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006986 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006987 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006988 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006989 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006990 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006991 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006992 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006993 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006994 llvm_unreachable("Clause is not allowed.");
6995 }
6996 return Res;
6997}
6998
Alexey Bataev6402bca2015-12-28 07:25:51 +00006999static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7000 OpenMPScheduleClauseModifier M2,
7001 SourceLocation M1Loc, SourceLocation M2Loc) {
7002 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7003 SmallVector<unsigned, 2> Excluded;
7004 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7005 Excluded.push_back(M2);
7006 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7007 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7008 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7009 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7010 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7011 << getListOfPossibleValues(OMPC_schedule,
7012 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7013 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7014 Excluded)
7015 << getOpenMPClauseName(OMPC_schedule);
7016 return true;
7017 }
7018 return false;
7019}
7020
Alexey Bataev56dafe82014-06-20 07:16:17 +00007021OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007022 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007023 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007024 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7025 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7026 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7027 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7028 return nullptr;
7029 // OpenMP, 2.7.1, Loop Construct, Restrictions
7030 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7031 // but not both.
7032 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7033 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7034 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7035 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7036 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7037 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7038 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7039 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7040 return nullptr;
7041 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007042 if (Kind == OMPC_SCHEDULE_unknown) {
7043 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007044 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7045 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7046 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7047 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7048 Exclude);
7049 } else {
7050 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7051 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007052 }
7053 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7054 << Values << getOpenMPClauseName(OMPC_schedule);
7055 return nullptr;
7056 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007057 // OpenMP, 2.7.1, Loop Construct, Restrictions
7058 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7059 // schedule(guided).
7060 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7061 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7062 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7063 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7064 diag::err_omp_schedule_nonmonotonic_static);
7065 return nullptr;
7066 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007067 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007068 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007069 if (ChunkSize) {
7070 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7071 !ChunkSize->isInstantiationDependent() &&
7072 !ChunkSize->containsUnexpandedParameterPack()) {
7073 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7074 ExprResult Val =
7075 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7076 if (Val.isInvalid())
7077 return nullptr;
7078
7079 ValExpr = Val.get();
7080
7081 // OpenMP [2.7.1, Restrictions]
7082 // chunk_size must be a loop invariant integer expression with a positive
7083 // value.
7084 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007085 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7086 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7087 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007088 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007089 return nullptr;
7090 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007091 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7092 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007093 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7094 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7095 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007096 }
7097 }
7098 }
7099
Alexey Bataev6402bca2015-12-28 07:25:51 +00007100 return new (Context)
7101 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007102 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007103}
7104
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007105OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7106 SourceLocation StartLoc,
7107 SourceLocation EndLoc) {
7108 OMPClause *Res = nullptr;
7109 switch (Kind) {
7110 case OMPC_ordered:
7111 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7112 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007113 case OMPC_nowait:
7114 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7115 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007116 case OMPC_untied:
7117 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7118 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007119 case OMPC_mergeable:
7120 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7121 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007122 case OMPC_read:
7123 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7124 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007125 case OMPC_write:
7126 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7127 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007128 case OMPC_update:
7129 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7130 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007131 case OMPC_capture:
7132 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7133 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007134 case OMPC_seq_cst:
7135 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7136 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007137 case OMPC_threads:
7138 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7139 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007140 case OMPC_simd:
7141 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7142 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007143 case OMPC_nogroup:
7144 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7145 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007146 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007147 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007148 case OMPC_num_threads:
7149 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007150 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007151 case OMPC_collapse:
7152 case OMPC_schedule:
7153 case OMPC_private:
7154 case OMPC_firstprivate:
7155 case OMPC_lastprivate:
7156 case OMPC_shared:
7157 case OMPC_reduction:
7158 case OMPC_linear:
7159 case OMPC_aligned:
7160 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007161 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007162 case OMPC_default:
7163 case OMPC_proc_bind:
7164 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007165 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007166 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007167 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007168 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007169 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007170 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007171 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007172 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007173 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007174 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007175 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007176 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007177 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007178 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007179 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007180 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007181 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007182 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007183 llvm_unreachable("Clause is not allowed.");
7184 }
7185 return Res;
7186}
7187
Alexey Bataev236070f2014-06-20 11:19:47 +00007188OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7189 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007190 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007191 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7192}
7193
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007194OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7195 SourceLocation EndLoc) {
7196 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7197}
7198
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007199OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7200 SourceLocation EndLoc) {
7201 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7202}
7203
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007204OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7205 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007206 return new (Context) OMPReadClause(StartLoc, EndLoc);
7207}
7208
Alexey Bataevdea47612014-07-23 07:46:59 +00007209OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7210 SourceLocation EndLoc) {
7211 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7212}
7213
Alexey Bataev67a4f222014-07-23 10:25:33 +00007214OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7215 SourceLocation EndLoc) {
7216 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7217}
7218
Alexey Bataev459dec02014-07-24 06:46:57 +00007219OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7220 SourceLocation EndLoc) {
7221 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7222}
7223
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007224OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7225 SourceLocation EndLoc) {
7226 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7227}
7228
Alexey Bataev346265e2015-09-25 10:37:12 +00007229OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7230 SourceLocation EndLoc) {
7231 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7232}
7233
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007234OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7235 SourceLocation EndLoc) {
7236 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7237}
7238
Alexey Bataevb825de12015-12-07 10:51:44 +00007239OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7240 SourceLocation EndLoc) {
7241 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7242}
7243
Alexey Bataevc5e02582014-06-16 07:08:35 +00007244OMPClause *Sema::ActOnOpenMPVarListClause(
7245 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7246 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7247 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007248 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007249 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7250 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7251 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007252 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007253 switch (Kind) {
7254 case OMPC_private:
7255 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7256 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007257 case OMPC_firstprivate:
7258 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7259 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007260 case OMPC_lastprivate:
7261 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7262 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007263 case OMPC_shared:
7264 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7265 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007266 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007267 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7268 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007269 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007270 case OMPC_linear:
7271 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007272 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007273 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007274 case OMPC_aligned:
7275 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7276 ColonLoc, EndLoc);
7277 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007278 case OMPC_copyin:
7279 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7280 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007281 case OMPC_copyprivate:
7282 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7283 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007284 case OMPC_flush:
7285 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7286 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007287 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007288 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007289 StartLoc, LParenLoc, EndLoc);
7290 break;
7291 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007292 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7293 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7294 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007295 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007296 case OMPC_to:
7297 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7298 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007299 case OMPC_from:
7300 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7301 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007302 case OMPC_use_device_ptr:
7303 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7304 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007305 case OMPC_is_device_ptr:
7306 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7307 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007308 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007309 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007310 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007311 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007312 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007313 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007314 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007315 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007316 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007317 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007318 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007319 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007320 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007321 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007322 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007323 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007324 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007325 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007326 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007327 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007328 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007329 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007330 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007331 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007332 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007333 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007334 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007335 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007336 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007337 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007338 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007339 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007340 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007341 llvm_unreachable("Clause is not allowed.");
7342 }
7343 return Res;
7344}
7345
Alexey Bataev90c228f2016-02-08 09:29:13 +00007346ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007347 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007348 ExprResult Res = BuildDeclRefExpr(
7349 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7350 if (!Res.isUsable())
7351 return ExprError();
7352 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7353 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7354 if (!Res.isUsable())
7355 return ExprError();
7356 }
7357 if (VK != VK_LValue && Res.get()->isGLValue()) {
7358 Res = DefaultLvalueConversion(Res.get());
7359 if (!Res.isUsable())
7360 return ExprError();
7361 }
7362 return Res;
7363}
7364
Alexey Bataev60da77e2016-02-29 05:54:20 +00007365static std::pair<ValueDecl *, bool>
7366getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7367 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007368 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7369 RefExpr->containsUnexpandedParameterPack())
7370 return std::make_pair(nullptr, true);
7371
Alexey Bataevd985eda2016-02-10 11:29:16 +00007372 // OpenMP [3.1, C/C++]
7373 // A list item is a variable name.
7374 // OpenMP [2.9.3.3, Restrictions, p.1]
7375 // A variable that is part of another variable (as an array or
7376 // structure element) cannot appear in a private clause.
7377 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007378 enum {
7379 NoArrayExpr = -1,
7380 ArraySubscript = 0,
7381 OMPArraySection = 1
7382 } IsArrayExpr = NoArrayExpr;
7383 if (AllowArraySection) {
7384 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7385 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7386 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7387 Base = TempASE->getBase()->IgnoreParenImpCasts();
7388 RefExpr = Base;
7389 IsArrayExpr = ArraySubscript;
7390 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7391 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7392 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7393 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7394 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7395 Base = TempASE->getBase()->IgnoreParenImpCasts();
7396 RefExpr = Base;
7397 IsArrayExpr = OMPArraySection;
7398 }
7399 }
7400 ELoc = RefExpr->getExprLoc();
7401 ERange = RefExpr->getSourceRange();
7402 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007403 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7404 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7405 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7406 (S.getCurrentThisType().isNull() || !ME ||
7407 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7408 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007409 if (IsArrayExpr != NoArrayExpr)
7410 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7411 << ERange;
7412 else {
7413 S.Diag(ELoc,
7414 AllowArraySection
7415 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7416 : diag::err_omp_expected_var_name_member_expr)
7417 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7418 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007419 return std::make_pair(nullptr, false);
7420 }
7421 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7422}
7423
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007424OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7425 SourceLocation StartLoc,
7426 SourceLocation LParenLoc,
7427 SourceLocation EndLoc) {
7428 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007429 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007430 for (auto &RefExpr : VarList) {
7431 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007432 SourceLocation ELoc;
7433 SourceRange ERange;
7434 Expr *SimpleRefExpr = RefExpr;
7435 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007436 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007437 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007438 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007439 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007440 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007441 ValueDecl *D = Res.first;
7442 if (!D)
7443 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007444
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007445 QualType Type = D->getType();
7446 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007447
7448 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7449 // A variable that appears in a private clause must not have an incomplete
7450 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007451 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007452 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007453 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007454
Alexey Bataev758e55e2013-09-06 18:03:48 +00007455 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7456 // in a Construct]
7457 // Variables with the predetermined data-sharing attributes may not be
7458 // listed in data-sharing attributes clauses, except for the cases
7459 // listed below. For these exceptions only, listing a predetermined
7460 // variable in a data-sharing attribute clause is allowed and overrides
7461 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007462 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007463 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007464 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7465 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007466 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007467 continue;
7468 }
7469
Kelvin Libf594a52016-12-17 05:48:59 +00007470 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007471 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007472 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007473 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007474 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7475 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007476 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007477 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007478 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007479 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007480 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007481 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007482 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007483 continue;
7484 }
7485
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007486 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7487 // A list item cannot appear in both a map clause and a data-sharing
7488 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007489 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007490 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007491 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007492 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007493 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007494 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007495 CurrDir == OMPD_target_parallel_for_simd ||
7496 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007497 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007498 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007499 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007500 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7501 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7502 ConflictKind = WhereFoundClauseKind;
7503 return true;
7504 })) {
7505 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007506 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007507 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007508 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007509 ReportOriginalDSA(*this, DSAStack, D, DVar);
7510 continue;
7511 }
7512 }
7513
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007514 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7515 // A variable of class type (or array thereof) that appears in a private
7516 // clause requires an accessible, unambiguous default constructor for the
7517 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007518 // Generate helper private variable and initialize it with the default
7519 // value. The address of the original variable is replaced by the address of
7520 // the new private variable in CodeGen. This new variable is not added to
7521 // IdResolver, so the code in the OpenMP region uses original variable for
7522 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007523 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007524 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7525 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007526 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007527 if (VDPrivate->isInvalidDecl())
7528 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007529 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007530 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007531
Alexey Bataev90c228f2016-02-08 09:29:13 +00007532 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007533 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007534 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007535 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007536 Vars.push_back((VD || CurContext->isDependentContext())
7537 ? RefExpr->IgnoreParens()
7538 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007539 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007540 }
7541
Alexey Bataeved09d242014-05-28 05:53:51 +00007542 if (Vars.empty())
7543 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007544
Alexey Bataev03b340a2014-10-21 03:16:40 +00007545 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7546 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007547}
7548
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007549namespace {
7550class DiagsUninitializedSeveretyRAII {
7551private:
7552 DiagnosticsEngine &Diags;
7553 SourceLocation SavedLoc;
7554 bool IsIgnored;
7555
7556public:
7557 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7558 bool IsIgnored)
7559 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7560 if (!IsIgnored) {
7561 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7562 /*Map*/ diag::Severity::Ignored, Loc);
7563 }
7564 }
7565 ~DiagsUninitializedSeveretyRAII() {
7566 if (!IsIgnored)
7567 Diags.popMappings(SavedLoc);
7568 }
7569};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007570}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007571
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007572OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7573 SourceLocation StartLoc,
7574 SourceLocation LParenLoc,
7575 SourceLocation EndLoc) {
7576 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007577 SmallVector<Expr *, 8> PrivateCopies;
7578 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007579 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007580 bool IsImplicitClause =
7581 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7582 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7583
Alexey Bataeved09d242014-05-28 05:53:51 +00007584 for (auto &RefExpr : VarList) {
7585 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007586 SourceLocation ELoc;
7587 SourceRange ERange;
7588 Expr *SimpleRefExpr = RefExpr;
7589 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007590 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007591 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007592 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007593 PrivateCopies.push_back(nullptr);
7594 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007595 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007596 ValueDecl *D = Res.first;
7597 if (!D)
7598 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007599
Alexey Bataev60da77e2016-02-29 05:54:20 +00007600 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007601 QualType Type = D->getType();
7602 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007603
7604 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7605 // A variable that appears in a private clause must not have an incomplete
7606 // type or a reference type.
7607 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007608 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007609 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007610 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007611
7612 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7613 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007614 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007615 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007616 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007617
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007618 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007619 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007620 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007621 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007622 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007623 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007624 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7625 // A list item that specifies a given variable may not appear in more
7626 // than one clause on the same directive, except that a variable may be
7627 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007628 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007629 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007630 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007631 << getOpenMPClauseName(DVar.CKind)
7632 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007633 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007634 continue;
7635 }
7636
7637 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7638 // in a Construct]
7639 // Variables with the predetermined data-sharing attributes may not be
7640 // listed in data-sharing attributes clauses, except for the cases
7641 // listed below. For these exceptions only, listing a predetermined
7642 // variable in a data-sharing attribute clause is allowed and overrides
7643 // the variable's predetermined data-sharing attributes.
7644 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7645 // in a Construct, C/C++, p.2]
7646 // Variables with const-qualified type having no mutable member may be
7647 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007648 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007649 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7650 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007651 << getOpenMPClauseName(DVar.CKind)
7652 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007653 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007654 continue;
7655 }
7656
Alexey Bataevf29276e2014-06-18 04:14:57 +00007657 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007658 // OpenMP [2.9.3.4, Restrictions, p.2]
7659 // A list item that is private within a parallel region must not appear
7660 // in a firstprivate clause on a worksharing construct if any of the
7661 // worksharing regions arising from the worksharing construct ever bind
7662 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007663 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007664 !isOpenMPParallelDirective(CurrDir) &&
7665 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007666 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007667 if (DVar.CKind != OMPC_shared &&
7668 (isOpenMPParallelDirective(DVar.DKind) ||
7669 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007670 Diag(ELoc, diag::err_omp_required_access)
7671 << getOpenMPClauseName(OMPC_firstprivate)
7672 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007673 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007674 continue;
7675 }
7676 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007677 // OpenMP [2.9.3.4, Restrictions, p.3]
7678 // A list item that appears in a reduction clause of a parallel construct
7679 // must not appear in a firstprivate clause on a worksharing or task
7680 // construct if any of the worksharing or task regions arising from the
7681 // worksharing or task construct ever bind to any of the parallel regions
7682 // arising from the parallel construct.
7683 // OpenMP [2.9.3.4, Restrictions, p.4]
7684 // A list item that appears in a reduction clause in worksharing
7685 // construct must not appear in a firstprivate clause in a task construct
7686 // encountered during execution of any of the worksharing regions arising
7687 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007688 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007689 DVar = DSAStack->hasInnermostDSA(
7690 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7691 [](OpenMPDirectiveKind K) -> bool {
7692 return isOpenMPParallelDirective(K) ||
7693 isOpenMPWorksharingDirective(K);
7694 },
7695 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007696 if (DVar.CKind == OMPC_reduction &&
7697 (isOpenMPParallelDirective(DVar.DKind) ||
7698 isOpenMPWorksharingDirective(DVar.DKind))) {
7699 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7700 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007701 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007702 continue;
7703 }
7704 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007705
7706 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7707 // A list item that is private within a teams region must not appear in a
7708 // firstprivate clause on a distribute construct if any of the distribute
7709 // regions arising from the distribute construct ever bind to any of the
7710 // teams regions arising from the teams construct.
7711 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7712 // A list item that appears in a reduction clause of a teams construct
7713 // must not appear in a firstprivate clause on a distribute construct if
7714 // any of the distribute regions arising from the distribute construct
7715 // ever bind to any of the teams regions arising from the teams construct.
7716 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7717 // A list item may appear in a firstprivate or lastprivate clause but not
7718 // both.
7719 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007720 DVar = DSAStack->hasInnermostDSA(
7721 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7722 [](OpenMPDirectiveKind K) -> bool {
7723 return isOpenMPTeamsDirective(K);
7724 },
7725 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007726 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7727 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007728 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007729 continue;
7730 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007731 DVar = DSAStack->hasInnermostDSA(
7732 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7733 [](OpenMPDirectiveKind K) -> bool {
7734 return isOpenMPTeamsDirective(K);
7735 },
7736 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007737 if (DVar.CKind == OMPC_reduction &&
7738 isOpenMPTeamsDirective(DVar.DKind)) {
7739 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007740 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007741 continue;
7742 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007743 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007744 if (DVar.CKind == OMPC_lastprivate) {
7745 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007746 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007747 continue;
7748 }
7749 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007750 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7751 // A list item cannot appear in both a map clause and a data-sharing
7752 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007753 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007754 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007755 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007756 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007757 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007758 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007759 CurrDir == OMPD_target_parallel_for_simd ||
7760 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007761 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007762 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007763 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007764 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7765 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7766 ConflictKind = WhereFoundClauseKind;
7767 return true;
7768 })) {
7769 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007770 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007771 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007772 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7773 ReportOriginalDSA(*this, DSAStack, D, DVar);
7774 continue;
7775 }
7776 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007777 }
7778
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007779 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007780 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007781 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007782 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7783 << getOpenMPClauseName(OMPC_firstprivate) << Type
7784 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7785 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007786 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007787 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007788 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007789 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007790 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007791 continue;
7792 }
7793
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007794 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007795 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7796 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007797 // Generate helper private variable and initialize it with the value of the
7798 // original variable. The address of the original variable is replaced by
7799 // the address of the new private variable in the CodeGen. This new variable
7800 // is not added to IdResolver, so the code in the OpenMP region uses
7801 // original variable for proper diagnostics and variable capturing.
7802 Expr *VDInitRefExpr = nullptr;
7803 // For arrays generate initializer for single element and replace it by the
7804 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007805 if (Type->isArrayType()) {
7806 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007807 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007808 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007809 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007810 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007811 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007812 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007813 InitializedEntity Entity =
7814 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007815 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7816
7817 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7818 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7819 if (Result.isInvalid())
7820 VDPrivate->setInvalidDecl();
7821 else
7822 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007823 // Remove temp variable declaration.
7824 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007825 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007826 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7827 ".firstprivate.temp");
7828 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7829 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007830 AddInitializerToDecl(VDPrivate,
7831 DefaultLvalueConversion(VDInitRefExpr).get(),
7832 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007833 }
7834 if (VDPrivate->isInvalidDecl()) {
7835 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007836 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007837 diag::note_omp_task_predetermined_firstprivate_here);
7838 }
7839 continue;
7840 }
7841 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007842 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007843 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7844 RefExpr->getExprLoc());
7845 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007846 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007847 if (TopDVar.CKind == OMPC_lastprivate)
7848 Ref = TopDVar.PrivateCopy;
7849 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007850 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007851 if (!IsOpenMPCapturedDecl(D))
7852 ExprCaptures.push_back(Ref->getDecl());
7853 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007854 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007855 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007856 Vars.push_back((VD || CurContext->isDependentContext())
7857 ? RefExpr->IgnoreParens()
7858 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007859 PrivateCopies.push_back(VDPrivateRefExpr);
7860 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007861 }
7862
Alexey Bataeved09d242014-05-28 05:53:51 +00007863 if (Vars.empty())
7864 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007865
7866 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007867 Vars, PrivateCopies, Inits,
7868 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007869}
7870
Alexander Musman1bb328c2014-06-04 13:06:39 +00007871OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7872 SourceLocation StartLoc,
7873 SourceLocation LParenLoc,
7874 SourceLocation EndLoc) {
7875 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007876 SmallVector<Expr *, 8> SrcExprs;
7877 SmallVector<Expr *, 8> DstExprs;
7878 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007879 SmallVector<Decl *, 4> ExprCaptures;
7880 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007881 for (auto &RefExpr : VarList) {
7882 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007883 SourceLocation ELoc;
7884 SourceRange ERange;
7885 Expr *SimpleRefExpr = RefExpr;
7886 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007887 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007888 // It will be analyzed later.
7889 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007890 SrcExprs.push_back(nullptr);
7891 DstExprs.push_back(nullptr);
7892 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007893 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007894 ValueDecl *D = Res.first;
7895 if (!D)
7896 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007897
Alexey Bataev74caaf22016-02-20 04:09:36 +00007898 QualType Type = D->getType();
7899 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007900
7901 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7902 // A variable that appears in a lastprivate clause must not have an
7903 // incomplete type or a reference type.
7904 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007905 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007906 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007907 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007908
7909 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7910 // in a Construct]
7911 // Variables with the predetermined data-sharing attributes may not be
7912 // listed in data-sharing attributes clauses, except for the cases
7913 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007914 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007915 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7916 DVar.CKind != OMPC_firstprivate &&
7917 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7918 Diag(ELoc, diag::err_omp_wrong_dsa)
7919 << getOpenMPClauseName(DVar.CKind)
7920 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007921 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007922 continue;
7923 }
7924
Alexey Bataevf29276e2014-06-18 04:14:57 +00007925 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7926 // OpenMP [2.14.3.5, Restrictions, p.2]
7927 // A list item that is private within a parallel region, or that appears in
7928 // the reduction clause of a parallel construct, must not appear in a
7929 // lastprivate clause on a worksharing construct if any of the corresponding
7930 // worksharing regions ever binds to any of the corresponding parallel
7931 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007932 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007933 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007934 !isOpenMPParallelDirective(CurrDir) &&
7935 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007936 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007937 if (DVar.CKind != OMPC_shared) {
7938 Diag(ELoc, diag::err_omp_required_access)
7939 << getOpenMPClauseName(OMPC_lastprivate)
7940 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007941 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007942 continue;
7943 }
7944 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007945
7946 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7947 // A list item may appear in a firstprivate or lastprivate clause but not
7948 // both.
7949 if (CurrDir == OMPD_distribute) {
7950 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7951 if (DVar.CKind == OMPC_firstprivate) {
7952 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7953 ReportOriginalDSA(*this, DSAStack, D, DVar);
7954 continue;
7955 }
7956 }
7957
Alexander Musman1bb328c2014-06-04 13:06:39 +00007958 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007959 // A variable of class type (or array thereof) that appears in a
7960 // lastprivate clause requires an accessible, unambiguous default
7961 // constructor for the class type, unless the list item is also specified
7962 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007963 // A variable of class type (or array thereof) that appears in a
7964 // lastprivate clause requires an accessible, unambiguous copy assignment
7965 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007966 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007967 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007968 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007969 D->hasAttrs() ? &D->getAttrs() : nullptr);
7970 auto *PseudoSrcExpr =
7971 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007972 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007973 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007974 D->hasAttrs() ? &D->getAttrs() : nullptr);
7975 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007976 // For arrays generate assignment operation for single element and replace
7977 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007978 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007979 PseudoDstExpr, PseudoSrcExpr);
7980 if (AssignmentOp.isInvalid())
7981 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007982 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007983 /*DiscardedValue=*/true);
7984 if (AssignmentOp.isInvalid())
7985 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007986
Alexey Bataev74caaf22016-02-20 04:09:36 +00007987 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007988 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007989 if (TopDVar.CKind == OMPC_firstprivate)
7990 Ref = TopDVar.PrivateCopy;
7991 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007992 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007993 if (!IsOpenMPCapturedDecl(D))
7994 ExprCaptures.push_back(Ref->getDecl());
7995 }
7996 if (TopDVar.CKind == OMPC_firstprivate ||
7997 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007998 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007999 ExprResult RefRes = DefaultLvalueConversion(Ref);
8000 if (!RefRes.isUsable())
8001 continue;
8002 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008003 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8004 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008005 if (!PostUpdateRes.isUsable())
8006 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008007 ExprPostUpdates.push_back(
8008 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008009 }
8010 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008011 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008012 Vars.push_back((VD || CurContext->isDependentContext())
8013 ? RefExpr->IgnoreParens()
8014 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008015 SrcExprs.push_back(PseudoSrcExpr);
8016 DstExprs.push_back(PseudoDstExpr);
8017 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008018 }
8019
8020 if (Vars.empty())
8021 return nullptr;
8022
8023 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008024 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008025 buildPreInits(Context, ExprCaptures),
8026 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008027}
8028
Alexey Bataev758e55e2013-09-06 18:03:48 +00008029OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8030 SourceLocation StartLoc,
8031 SourceLocation LParenLoc,
8032 SourceLocation EndLoc) {
8033 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008034 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008035 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008036 SourceLocation ELoc;
8037 SourceRange ERange;
8038 Expr *SimpleRefExpr = RefExpr;
8039 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008040 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008041 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008042 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008043 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008044 ValueDecl *D = Res.first;
8045 if (!D)
8046 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008047
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008048 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008049 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8050 // in a Construct]
8051 // Variables with the predetermined data-sharing attributes may not be
8052 // listed in data-sharing attributes clauses, except for the cases
8053 // listed below. For these exceptions only, listing a predetermined
8054 // variable in a data-sharing attribute clause is allowed and overrides
8055 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008056 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008057 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8058 DVar.RefExpr) {
8059 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8060 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008061 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008062 continue;
8063 }
8064
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008065 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008066 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008067 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008068 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008069 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8070 ? RefExpr->IgnoreParens()
8071 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008072 }
8073
Alexey Bataeved09d242014-05-28 05:53:51 +00008074 if (Vars.empty())
8075 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008076
8077 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8078}
8079
Alexey Bataevc5e02582014-06-16 07:08:35 +00008080namespace {
8081class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8082 DSAStackTy *Stack;
8083
8084public:
8085 bool VisitDeclRefExpr(DeclRefExpr *E) {
8086 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008087 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008088 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8089 return false;
8090 if (DVar.CKind != OMPC_unknown)
8091 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008092 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8093 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8094 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008095 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008096 return true;
8097 return false;
8098 }
8099 return false;
8100 }
8101 bool VisitStmt(Stmt *S) {
8102 for (auto Child : S->children()) {
8103 if (Child && Visit(Child))
8104 return true;
8105 }
8106 return false;
8107 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008108 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008109};
Alexey Bataev23b69422014-06-18 07:08:49 +00008110} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008111
Alexey Bataev60da77e2016-02-29 05:54:20 +00008112namespace {
8113// Transform MemberExpression for specified FieldDecl of current class to
8114// DeclRefExpr to specified OMPCapturedExprDecl.
8115class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8116 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8117 ValueDecl *Field;
8118 DeclRefExpr *CapturedExpr;
8119
8120public:
8121 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8122 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8123
8124 ExprResult TransformMemberExpr(MemberExpr *E) {
8125 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8126 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008127 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008128 return CapturedExpr;
8129 }
8130 return BaseTransform::TransformMemberExpr(E);
8131 }
8132 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8133};
8134} // namespace
8135
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008136template <typename T>
8137static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8138 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8139 for (auto &Set : Lookups) {
8140 for (auto *D : Set) {
8141 if (auto Res = Gen(cast<ValueDecl>(D)))
8142 return Res;
8143 }
8144 }
8145 return T();
8146}
8147
8148static ExprResult
8149buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8150 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8151 const DeclarationNameInfo &ReductionId, QualType Ty,
8152 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8153 if (ReductionIdScopeSpec.isInvalid())
8154 return ExprError();
8155 SmallVector<UnresolvedSet<8>, 4> Lookups;
8156 if (S) {
8157 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8158 Lookup.suppressDiagnostics();
8159 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8160 auto *D = Lookup.getRepresentativeDecl();
8161 do {
8162 S = S->getParent();
8163 } while (S && !S->isDeclScope(D));
8164 if (S)
8165 S = S->getParent();
8166 Lookups.push_back(UnresolvedSet<8>());
8167 Lookups.back().append(Lookup.begin(), Lookup.end());
8168 Lookup.clear();
8169 }
8170 } else if (auto *ULE =
8171 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8172 Lookups.push_back(UnresolvedSet<8>());
8173 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008174 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008175 if (D == PrevD)
8176 Lookups.push_back(UnresolvedSet<8>());
8177 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8178 Lookups.back().addDecl(DRD);
8179 PrevD = D;
8180 }
8181 }
8182 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8183 Ty->containsUnexpandedParameterPack() ||
8184 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8185 return !D->isInvalidDecl() &&
8186 (D->getType()->isDependentType() ||
8187 D->getType()->isInstantiationDependentType() ||
8188 D->getType()->containsUnexpandedParameterPack());
8189 })) {
8190 UnresolvedSet<8> ResSet;
8191 for (auto &Set : Lookups) {
8192 ResSet.append(Set.begin(), Set.end());
8193 // The last item marks the end of all declarations at the specified scope.
8194 ResSet.addDecl(Set[Set.size() - 1]);
8195 }
8196 return UnresolvedLookupExpr::Create(
8197 SemaRef.Context, /*NamingClass=*/nullptr,
8198 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8199 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8200 }
8201 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8202 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8203 if (!D->isInvalidDecl() &&
8204 SemaRef.Context.hasSameType(D->getType(), Ty))
8205 return D;
8206 return nullptr;
8207 }))
8208 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8209 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8210 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8211 if (!D->isInvalidDecl() &&
8212 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8213 !Ty.isMoreQualifiedThan(D->getType()))
8214 return D;
8215 return nullptr;
8216 })) {
8217 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8218 /*DetectVirtual=*/false);
8219 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8220 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8221 VD->getType().getUnqualifiedType()))) {
8222 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8223 /*DiagID=*/0) !=
8224 Sema::AR_inaccessible) {
8225 SemaRef.BuildBasePathArray(Paths, BasePath);
8226 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8227 }
8228 }
8229 }
8230 }
8231 if (ReductionIdScopeSpec.isSet()) {
8232 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8233 return ExprError();
8234 }
8235 return ExprEmpty();
8236}
8237
Alexey Bataevc5e02582014-06-16 07:08:35 +00008238OMPClause *Sema::ActOnOpenMPReductionClause(
8239 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8240 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008241 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8242 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008243 auto DN = ReductionId.getName();
8244 auto OOK = DN.getCXXOverloadedOperator();
8245 BinaryOperatorKind BOK = BO_Comma;
8246
8247 // OpenMP [2.14.3.6, reduction clause]
8248 // C
8249 // reduction-identifier is either an identifier or one of the following
8250 // operators: +, -, *, &, |, ^, && and ||
8251 // C++
8252 // reduction-identifier is either an id-expression or one of the following
8253 // operators: +, -, *, &, |, ^, && and ||
8254 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8255 switch (OOK) {
8256 case OO_Plus:
8257 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008258 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008259 break;
8260 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008261 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008262 break;
8263 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008264 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008265 break;
8266 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008267 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008268 break;
8269 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008270 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008271 break;
8272 case OO_AmpAmp:
8273 BOK = BO_LAnd;
8274 break;
8275 case OO_PipePipe:
8276 BOK = BO_LOr;
8277 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008278 case OO_New:
8279 case OO_Delete:
8280 case OO_Array_New:
8281 case OO_Array_Delete:
8282 case OO_Slash:
8283 case OO_Percent:
8284 case OO_Tilde:
8285 case OO_Exclaim:
8286 case OO_Equal:
8287 case OO_Less:
8288 case OO_Greater:
8289 case OO_LessEqual:
8290 case OO_GreaterEqual:
8291 case OO_PlusEqual:
8292 case OO_MinusEqual:
8293 case OO_StarEqual:
8294 case OO_SlashEqual:
8295 case OO_PercentEqual:
8296 case OO_CaretEqual:
8297 case OO_AmpEqual:
8298 case OO_PipeEqual:
8299 case OO_LessLess:
8300 case OO_GreaterGreater:
8301 case OO_LessLessEqual:
8302 case OO_GreaterGreaterEqual:
8303 case OO_EqualEqual:
8304 case OO_ExclaimEqual:
8305 case OO_PlusPlus:
8306 case OO_MinusMinus:
8307 case OO_Comma:
8308 case OO_ArrowStar:
8309 case OO_Arrow:
8310 case OO_Call:
8311 case OO_Subscript:
8312 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008313 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008314 case NUM_OVERLOADED_OPERATORS:
8315 llvm_unreachable("Unexpected reduction identifier");
8316 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008317 if (auto II = DN.getAsIdentifierInfo()) {
8318 if (II->isStr("max"))
8319 BOK = BO_GT;
8320 else if (II->isStr("min"))
8321 BOK = BO_LT;
8322 }
8323 break;
8324 }
8325 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008326 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008327 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008328 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008329
8330 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008331 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008332 SmallVector<Expr *, 8> LHSs;
8333 SmallVector<Expr *, 8> RHSs;
8334 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008335 SmallVector<Decl *, 4> ExprCaptures;
8336 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008337 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8338 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008339 for (auto RefExpr : VarList) {
8340 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008341 // OpenMP [2.1, C/C++]
8342 // A list item is a variable or array section, subject to the restrictions
8343 // specified in Section 2.4 on page 42 and in each of the sections
8344 // describing clauses and directives for which a list appears.
8345 // OpenMP [2.14.3.3, Restrictions, p.1]
8346 // A variable that is part of another variable (as an array or
8347 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008348 if (!FirstIter && IR != ER)
8349 ++IR;
8350 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008351 SourceLocation ELoc;
8352 SourceRange ERange;
8353 Expr *SimpleRefExpr = RefExpr;
8354 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8355 /*AllowArraySection=*/true);
8356 if (Res.second) {
8357 // It will be analyzed later.
8358 Vars.push_back(RefExpr);
8359 Privates.push_back(nullptr);
8360 LHSs.push_back(nullptr);
8361 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008362 // Try to find 'declare reduction' corresponding construct before using
8363 // builtin/overloaded operators.
8364 QualType Type = Context.DependentTy;
8365 CXXCastPath BasePath;
8366 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8367 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8368 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8369 if (CurContext->isDependentContext() &&
8370 (DeclareReductionRef.isUnset() ||
8371 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8372 ReductionOps.push_back(DeclareReductionRef.get());
8373 else
8374 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008375 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008376 ValueDecl *D = Res.first;
8377 if (!D)
8378 continue;
8379
Alexey Bataeva1764212015-09-30 09:22:36 +00008380 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008381 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8382 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8383 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008384 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008385 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008386 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8387 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8388 Type = ATy->getElementType();
8389 else
8390 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008391 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008392 } else
8393 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8394 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008395
Alexey Bataevc5e02582014-06-16 07:08:35 +00008396 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8397 // A variable that appears in a private clause must not have an incomplete
8398 // type or a reference type.
8399 if (RequireCompleteType(ELoc, Type,
8400 diag::err_omp_reduction_incomplete_type))
8401 continue;
8402 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008403 // A list item that appears in a reduction clause must not be
8404 // const-qualified.
8405 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008406 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008407 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008408 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008409 bool IsDecl = !VD ||
8410 VD->isThisDeclarationADefinition(Context) ==
8411 VarDecl::DeclarationOnly;
8412 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008413 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008414 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008415 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008416 continue;
8417 }
8418 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8419 // If a list-item is a reference type then it must bind to the same object
8420 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008421 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008422 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008423 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008424 DSARefChecker Check(DSAStack);
8425 if (Check.Visit(VDDef->getInit())) {
8426 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8427 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8428 continue;
8429 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008430 }
8431 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008432
Alexey Bataevc5e02582014-06-16 07:08:35 +00008433 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8434 // in a Construct]
8435 // Variables with the predetermined data-sharing attributes may not be
8436 // listed in data-sharing attributes clauses, except for the cases
8437 // listed below. For these exceptions only, listing a predetermined
8438 // variable in a data-sharing attribute clause is allowed and overrides
8439 // the variable's predetermined data-sharing attributes.
8440 // OpenMP [2.14.3.6, Restrictions, p.3]
8441 // Any number of reduction clauses can be specified on the directive,
8442 // but a list item can appear only once in the reduction clauses for that
8443 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008444 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008445 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008446 if (DVar.CKind == OMPC_reduction) {
8447 Diag(ELoc, diag::err_omp_once_referenced)
8448 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008449 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008450 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008451 } else if (DVar.CKind != OMPC_unknown) {
8452 Diag(ELoc, diag::err_omp_wrong_dsa)
8453 << getOpenMPClauseName(DVar.CKind)
8454 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008455 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008456 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008457 }
8458
8459 // OpenMP [2.14.3.6, Restrictions, p.1]
8460 // A list item that appears in a reduction clause of a worksharing
8461 // construct must be shared in the parallel regions to which any of the
8462 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008463 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8464 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008465 !isOpenMPParallelDirective(CurrDir) &&
8466 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008467 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008468 if (DVar.CKind != OMPC_shared) {
8469 Diag(ELoc, diag::err_omp_required_access)
8470 << getOpenMPClauseName(OMPC_reduction)
8471 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008472 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008473 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008474 }
8475 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008476
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008477 // Try to find 'declare reduction' corresponding construct before using
8478 // builtin/overloaded operators.
8479 CXXCastPath BasePath;
8480 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8481 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8482 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8483 if (DeclareReductionRef.isInvalid())
8484 continue;
8485 if (CurContext->isDependentContext() &&
8486 (DeclareReductionRef.isUnset() ||
8487 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8488 Vars.push_back(RefExpr);
8489 Privates.push_back(nullptr);
8490 LHSs.push_back(nullptr);
8491 RHSs.push_back(nullptr);
8492 ReductionOps.push_back(DeclareReductionRef.get());
8493 continue;
8494 }
8495 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8496 // Not allowed reduction identifier is found.
8497 Diag(ReductionId.getLocStart(),
8498 diag::err_omp_unknown_reduction_identifier)
8499 << Type << ReductionIdRange;
8500 continue;
8501 }
8502
8503 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8504 // The type of a list item that appears in a reduction clause must be valid
8505 // for the reduction-identifier. For a max or min reduction in C, the type
8506 // of the list item must be an allowed arithmetic data type: char, int,
8507 // float, double, or _Bool, possibly modified with long, short, signed, or
8508 // unsigned. For a max or min reduction in C++, the type of the list item
8509 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8510 // double, or bool, possibly modified with long, short, signed, or unsigned.
8511 if (DeclareReductionRef.isUnset()) {
8512 if ((BOK == BO_GT || BOK == BO_LT) &&
8513 !(Type->isScalarType() ||
8514 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8515 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8516 << getLangOpts().CPlusPlus;
8517 if (!ASE && !OASE) {
8518 bool IsDecl = !VD ||
8519 VD->isThisDeclarationADefinition(Context) ==
8520 VarDecl::DeclarationOnly;
8521 Diag(D->getLocation(),
8522 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8523 << D;
8524 }
8525 continue;
8526 }
8527 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8528 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8529 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8530 if (!ASE && !OASE) {
8531 bool IsDecl = !VD ||
8532 VD->isThisDeclarationADefinition(Context) ==
8533 VarDecl::DeclarationOnly;
8534 Diag(D->getLocation(),
8535 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8536 << D;
8537 }
8538 continue;
8539 }
8540 }
8541
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008542 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008543 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008544 D->hasAttrs() ? &D->getAttrs() : nullptr);
8545 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8546 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008547 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008548 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008549 (!ASE &&
8550 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008551 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008552 // Create pseudo array type for private copy. The size for this array will
8553 // be generated during codegen.
8554 // For array subscripts or single variables Private Ty is the same as Type
8555 // (type of the variable or single array element).
8556 PrivateTy = Context.getVariableArrayType(
8557 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8558 Context.getSizeType(), VK_RValue),
8559 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008560 } else if (!ASE && !OASE &&
8561 Context.getAsArrayType(D->getType().getNonReferenceType()))
8562 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008563 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008564 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8565 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008566 // Add initializer for private variable.
8567 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008568 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8569 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8570 if (DeclareReductionRef.isUsable()) {
8571 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8572 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8573 if (DRD->getInitializer()) {
8574 Init = DRDRef;
8575 RHSVD->setInit(DRDRef);
8576 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008577 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008578 } else {
8579 switch (BOK) {
8580 case BO_Add:
8581 case BO_Xor:
8582 case BO_Or:
8583 case BO_LOr:
8584 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8585 if (Type->isScalarType() || Type->isAnyComplexType())
8586 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8587 break;
8588 case BO_Mul:
8589 case BO_LAnd:
8590 if (Type->isScalarType() || Type->isAnyComplexType()) {
8591 // '*' and '&&' reduction ops - initializer is '1'.
8592 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008593 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008594 break;
8595 case BO_And: {
8596 // '&' reduction op - initializer is '~0'.
8597 QualType OrigType = Type;
8598 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8599 Type = ComplexTy->getElementType();
8600 if (Type->isRealFloatingType()) {
8601 llvm::APFloat InitValue =
8602 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8603 /*isIEEE=*/true);
8604 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8605 Type, ELoc);
8606 } else if (Type->isScalarType()) {
8607 auto Size = Context.getTypeSize(Type);
8608 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8609 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8610 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8611 }
8612 if (Init && OrigType->isAnyComplexType()) {
8613 // Init = 0xFFFF + 0xFFFFi;
8614 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8615 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8616 }
8617 Type = OrigType;
8618 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008619 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008620 case BO_LT:
8621 case BO_GT: {
8622 // 'min' reduction op - initializer is 'Largest representable number in
8623 // the reduction list item type'.
8624 // 'max' reduction op - initializer is 'Least representable number in
8625 // the reduction list item type'.
8626 if (Type->isIntegerType() || Type->isPointerType()) {
8627 bool IsSigned = Type->hasSignedIntegerRepresentation();
8628 auto Size = Context.getTypeSize(Type);
8629 QualType IntTy =
8630 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8631 llvm::APInt InitValue =
8632 (BOK != BO_LT)
8633 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8634 : llvm::APInt::getMinValue(Size)
8635 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8636 : llvm::APInt::getMaxValue(Size);
8637 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8638 if (Type->isPointerType()) {
8639 // Cast to pointer type.
8640 auto CastExpr = BuildCStyleCastExpr(
8641 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8642 SourceLocation(), Init);
8643 if (CastExpr.isInvalid())
8644 continue;
8645 Init = CastExpr.get();
8646 }
8647 } else if (Type->isRealFloatingType()) {
8648 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8649 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8650 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8651 Type, ELoc);
8652 }
8653 break;
8654 }
8655 case BO_PtrMemD:
8656 case BO_PtrMemI:
8657 case BO_MulAssign:
8658 case BO_Div:
8659 case BO_Rem:
8660 case BO_Sub:
8661 case BO_Shl:
8662 case BO_Shr:
8663 case BO_LE:
8664 case BO_GE:
8665 case BO_EQ:
8666 case BO_NE:
8667 case BO_AndAssign:
8668 case BO_XorAssign:
8669 case BO_OrAssign:
8670 case BO_Assign:
8671 case BO_AddAssign:
8672 case BO_SubAssign:
8673 case BO_DivAssign:
8674 case BO_RemAssign:
8675 case BO_ShlAssign:
8676 case BO_ShrAssign:
8677 case BO_Comma:
8678 llvm_unreachable("Unexpected reduction operation");
8679 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008680 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008681 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008682 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8683 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008684 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008685 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008686 if (RHSVD->isInvalidDecl())
8687 continue;
8688 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008689 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8690 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008691 bool IsDecl =
8692 !VD ||
8693 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8694 Diag(D->getLocation(),
8695 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8696 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008697 continue;
8698 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008699 // Store initializer for single element in private copy. Will be used during
8700 // codegen.
8701 PrivateVD->setInit(RHSVD->getInit());
8702 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008703 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008704 ExprResult ReductionOp;
8705 if (DeclareReductionRef.isUsable()) {
8706 QualType RedTy = DeclareReductionRef.get()->getType();
8707 QualType PtrRedTy = Context.getPointerType(RedTy);
8708 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8709 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8710 if (!BasePath.empty()) {
8711 LHS = DefaultLvalueConversion(LHS.get());
8712 RHS = DefaultLvalueConversion(RHS.get());
8713 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8714 CK_UncheckedDerivedToBase, LHS.get(),
8715 &BasePath, LHS.get()->getValueKind());
8716 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8717 CK_UncheckedDerivedToBase, RHS.get(),
8718 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008719 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008720 FunctionProtoType::ExtProtoInfo EPI;
8721 QualType Params[] = {PtrRedTy, PtrRedTy};
8722 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8723 auto *OVE = new (Context) OpaqueValueExpr(
8724 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8725 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8726 Expr *Args[] = {LHS.get(), RHS.get()};
8727 ReductionOp = new (Context)
8728 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8729 } else {
8730 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8731 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8732 if (ReductionOp.isUsable()) {
8733 if (BOK != BO_LT && BOK != BO_GT) {
8734 ReductionOp =
8735 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8736 BO_Assign, LHSDRE, ReductionOp.get());
8737 } else {
8738 auto *ConditionalOp = new (Context) ConditionalOperator(
8739 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8740 RHSDRE, Type, VK_LValue, OK_Ordinary);
8741 ReductionOp =
8742 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8743 BO_Assign, LHSDRE, ConditionalOp);
8744 }
8745 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8746 }
8747 if (ReductionOp.isInvalid())
8748 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008749 }
8750
Alexey Bataev60da77e2016-02-29 05:54:20 +00008751 DeclRefExpr *Ref = nullptr;
8752 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008753 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008754 if (ASE || OASE) {
8755 TransformExprToCaptures RebuildToCapture(*this, D);
8756 VarsExpr =
8757 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8758 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008759 } else {
8760 VarsExpr = Ref =
8761 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008762 }
8763 if (!IsOpenMPCapturedDecl(D)) {
8764 ExprCaptures.push_back(Ref->getDecl());
8765 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8766 ExprResult RefRes = DefaultLvalueConversion(Ref);
8767 if (!RefRes.isUsable())
8768 continue;
8769 ExprResult PostUpdateRes =
8770 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8771 SimpleRefExpr, RefRes.get());
8772 if (!PostUpdateRes.isUsable())
8773 continue;
8774 ExprPostUpdates.push_back(
8775 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008776 }
8777 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008778 }
8779 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8780 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008781 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008782 LHSs.push_back(LHSDRE);
8783 RHSs.push_back(RHSDRE);
8784 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008785 }
8786
8787 if (Vars.empty())
8788 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008789
Alexey Bataevc5e02582014-06-16 07:08:35 +00008790 return OMPReductionClause::Create(
8791 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008792 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008793 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8794 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008795}
8796
Alexey Bataevecba70f2016-04-12 11:02:11 +00008797bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8798 SourceLocation LinLoc) {
8799 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8800 LinKind == OMPC_LINEAR_unknown) {
8801 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8802 return true;
8803 }
8804 return false;
8805}
8806
8807bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8808 OpenMPLinearClauseKind LinKind,
8809 QualType Type) {
8810 auto *VD = dyn_cast_or_null<VarDecl>(D);
8811 // A variable must not have an incomplete type or a reference type.
8812 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8813 return true;
8814 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8815 !Type->isReferenceType()) {
8816 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8817 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8818 return true;
8819 }
8820 Type = Type.getNonReferenceType();
8821
8822 // A list item must not be const-qualified.
8823 if (Type.isConstant(Context)) {
8824 Diag(ELoc, diag::err_omp_const_variable)
8825 << getOpenMPClauseName(OMPC_linear);
8826 if (D) {
8827 bool IsDecl =
8828 !VD ||
8829 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8830 Diag(D->getLocation(),
8831 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8832 << D;
8833 }
8834 return true;
8835 }
8836
8837 // A list item must be of integral or pointer type.
8838 Type = Type.getUnqualifiedType().getCanonicalType();
8839 const auto *Ty = Type.getTypePtrOrNull();
8840 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8841 !Ty->isPointerType())) {
8842 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8843 if (D) {
8844 bool IsDecl =
8845 !VD ||
8846 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8847 Diag(D->getLocation(),
8848 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8849 << D;
8850 }
8851 return true;
8852 }
8853 return false;
8854}
8855
Alexey Bataev182227b2015-08-20 10:54:39 +00008856OMPClause *Sema::ActOnOpenMPLinearClause(
8857 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8858 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8859 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008860 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008861 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008862 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008863 SmallVector<Decl *, 4> ExprCaptures;
8864 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008865 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008866 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008867 for (auto &RefExpr : VarList) {
8868 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008869 SourceLocation ELoc;
8870 SourceRange ERange;
8871 Expr *SimpleRefExpr = RefExpr;
8872 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8873 /*AllowArraySection=*/false);
8874 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008875 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008876 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008877 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008878 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008879 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008880 ValueDecl *D = Res.first;
8881 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008882 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008883
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008884 QualType Type = D->getType();
8885 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008886
8887 // OpenMP [2.14.3.7, linear clause]
8888 // A list-item cannot appear in more than one linear clause.
8889 // A list-item that appears in a linear clause cannot appear in any
8890 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008891 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008892 if (DVar.RefExpr) {
8893 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8894 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008895 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008896 continue;
8897 }
8898
Alexey Bataevecba70f2016-04-12 11:02:11 +00008899 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008900 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008901 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008902
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008903 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008904 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8905 D->hasAttrs() ? &D->getAttrs() : nullptr);
8906 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008907 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008908 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008909 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008910 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008911 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008912 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8913 if (!IsOpenMPCapturedDecl(D)) {
8914 ExprCaptures.push_back(Ref->getDecl());
8915 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8916 ExprResult RefRes = DefaultLvalueConversion(Ref);
8917 if (!RefRes.isUsable())
8918 continue;
8919 ExprResult PostUpdateRes =
8920 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8921 SimpleRefExpr, RefRes.get());
8922 if (!PostUpdateRes.isUsable())
8923 continue;
8924 ExprPostUpdates.push_back(
8925 IgnoredValueConversions(PostUpdateRes.get()).get());
8926 }
8927 }
8928 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008929 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008930 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008931 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008932 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008933 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008934 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8935 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8936
8937 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008938 Vars.push_back((VD || CurContext->isDependentContext())
8939 ? RefExpr->IgnoreParens()
8940 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008941 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008942 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008943 }
8944
8945 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008946 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008947
8948 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008949 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008950 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8951 !Step->isInstantiationDependent() &&
8952 !Step->containsUnexpandedParameterPack()) {
8953 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008954 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008955 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008956 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008957 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008958
Alexander Musman3276a272015-03-21 10:12:56 +00008959 // Build var to save the step value.
8960 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008961 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008962 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008963 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008964 ExprResult CalcStep =
8965 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008966 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008967
Alexander Musman8dba6642014-04-22 13:09:42 +00008968 // Warn about zero linear step (it would be probably better specified as
8969 // making corresponding variables 'const').
8970 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008971 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8972 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008973 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8974 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008975 if (!IsConstant && CalcStep.isUsable()) {
8976 // Calculate the step beforehand instead of doing this on each iteration.
8977 // (This is not used if the number of iterations may be kfold-ed).
8978 CalcStepExpr = CalcStep.get();
8979 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008980 }
8981
Alexey Bataev182227b2015-08-20 10:54:39 +00008982 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8983 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008984 StepExpr, CalcStepExpr,
8985 buildPreInits(Context, ExprCaptures),
8986 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008987}
8988
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008989static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8990 Expr *NumIterations, Sema &SemaRef,
8991 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008992 // Walk the vars and build update/final expressions for the CodeGen.
8993 SmallVector<Expr *, 8> Updates;
8994 SmallVector<Expr *, 8> Finals;
8995 Expr *Step = Clause.getStep();
8996 Expr *CalcStep = Clause.getCalcStep();
8997 // OpenMP [2.14.3.7, linear clause]
8998 // If linear-step is not specified it is assumed to be 1.
8999 if (Step == nullptr)
9000 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009001 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009002 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009003 }
Alexander Musman3276a272015-03-21 10:12:56 +00009004 bool HasErrors = false;
9005 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009006 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009007 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009008 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009009 SourceLocation ELoc;
9010 SourceRange ERange;
9011 Expr *SimpleRefExpr = RefExpr;
9012 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9013 /*AllowArraySection=*/false);
9014 ValueDecl *D = Res.first;
9015 if (Res.second || !D) {
9016 Updates.push_back(nullptr);
9017 Finals.push_back(nullptr);
9018 HasErrors = true;
9019 continue;
9020 }
9021 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9022 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9023 ->getMemberDecl();
9024 }
9025 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009026 Expr *InitExpr = *CurInit;
9027
9028 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009029 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009030 Expr *CapturedRef;
9031 if (LinKind == OMPC_LINEAR_uval)
9032 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9033 else
9034 CapturedRef =
9035 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9036 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9037 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009038
9039 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009040 ExprResult Update;
9041 if (!Info.first) {
9042 Update =
9043 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9044 InitExpr, IV, Step, /* Subtract */ false);
9045 } else
9046 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009047 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9048 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009049
9050 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009051 ExprResult Final;
9052 if (!Info.first) {
9053 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9054 InitExpr, NumIterations, Step,
9055 /* Subtract */ false);
9056 } else
9057 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009058 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9059 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009060
Alexander Musman3276a272015-03-21 10:12:56 +00009061 if (!Update.isUsable() || !Final.isUsable()) {
9062 Updates.push_back(nullptr);
9063 Finals.push_back(nullptr);
9064 HasErrors = true;
9065 } else {
9066 Updates.push_back(Update.get());
9067 Finals.push_back(Final.get());
9068 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009069 ++CurInit;
9070 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009071 }
9072 Clause.setUpdates(Updates);
9073 Clause.setFinals(Finals);
9074 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009075}
9076
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009077OMPClause *Sema::ActOnOpenMPAlignedClause(
9078 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9079 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9080
9081 SmallVector<Expr *, 8> Vars;
9082 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009083 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9084 SourceLocation ELoc;
9085 SourceRange ERange;
9086 Expr *SimpleRefExpr = RefExpr;
9087 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9088 /*AllowArraySection=*/false);
9089 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009090 // It will be analyzed later.
9091 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009092 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009093 ValueDecl *D = Res.first;
9094 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009095 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009096
Alexey Bataev1efd1662016-03-29 10:59:56 +00009097 QualType QType = D->getType();
9098 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009099
9100 // OpenMP [2.8.1, simd construct, Restrictions]
9101 // The type of list items appearing in the aligned clause must be
9102 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009103 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009104 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009105 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009106 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009107 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009108 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009109 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009110 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009111 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009112 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009113 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009114 continue;
9115 }
9116
9117 // OpenMP [2.8.1, simd construct, Restrictions]
9118 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009119 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009120 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009121 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9122 << getOpenMPClauseName(OMPC_aligned);
9123 continue;
9124 }
9125
Alexey Bataev1efd1662016-03-29 10:59:56 +00009126 DeclRefExpr *Ref = nullptr;
9127 if (!VD && IsOpenMPCapturedDecl(D))
9128 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9129 Vars.push_back(DefaultFunctionArrayConversion(
9130 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9131 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009132 }
9133
9134 // OpenMP [2.8.1, simd construct, Description]
9135 // The parameter of the aligned clause, alignment, must be a constant
9136 // positive integer expression.
9137 // If no optional parameter is specified, implementation-defined default
9138 // alignments for SIMD instructions on the target platforms are assumed.
9139 if (Alignment != nullptr) {
9140 ExprResult AlignResult =
9141 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9142 if (AlignResult.isInvalid())
9143 return nullptr;
9144 Alignment = AlignResult.get();
9145 }
9146 if (Vars.empty())
9147 return nullptr;
9148
9149 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9150 EndLoc, Vars, Alignment);
9151}
9152
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009153OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9154 SourceLocation StartLoc,
9155 SourceLocation LParenLoc,
9156 SourceLocation EndLoc) {
9157 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009158 SmallVector<Expr *, 8> SrcExprs;
9159 SmallVector<Expr *, 8> DstExprs;
9160 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009161 for (auto &RefExpr : VarList) {
9162 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9163 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009164 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009165 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009166 SrcExprs.push_back(nullptr);
9167 DstExprs.push_back(nullptr);
9168 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009169 continue;
9170 }
9171
Alexey Bataeved09d242014-05-28 05:53:51 +00009172 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009173 // OpenMP [2.1, C/C++]
9174 // A list item is a variable name.
9175 // OpenMP [2.14.4.1, Restrictions, p.1]
9176 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009177 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009178 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009179 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9180 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009181 continue;
9182 }
9183
9184 Decl *D = DE->getDecl();
9185 VarDecl *VD = cast<VarDecl>(D);
9186
9187 QualType Type = VD->getType();
9188 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9189 // It will be analyzed later.
9190 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009191 SrcExprs.push_back(nullptr);
9192 DstExprs.push_back(nullptr);
9193 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009194 continue;
9195 }
9196
9197 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9198 // A list item that appears in a copyin clause must be threadprivate.
9199 if (!DSAStack->isThreadPrivate(VD)) {
9200 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009201 << getOpenMPClauseName(OMPC_copyin)
9202 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009203 continue;
9204 }
9205
9206 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9207 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009208 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009209 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009210 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009211 auto *SrcVD =
9212 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9213 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009214 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009215 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9216 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009217 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9218 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009219 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009220 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009221 // For arrays generate assignment operation for single element and replace
9222 // it by the original array element in CodeGen.
9223 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9224 PseudoDstExpr, PseudoSrcExpr);
9225 if (AssignmentOp.isInvalid())
9226 continue;
9227 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9228 /*DiscardedValue=*/true);
9229 if (AssignmentOp.isInvalid())
9230 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009231
9232 DSAStack->addDSA(VD, DE, OMPC_copyin);
9233 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009234 SrcExprs.push_back(PseudoSrcExpr);
9235 DstExprs.push_back(PseudoDstExpr);
9236 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009237 }
9238
Alexey Bataeved09d242014-05-28 05:53:51 +00009239 if (Vars.empty())
9240 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009241
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009242 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9243 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009244}
9245
Alexey Bataevbae9a792014-06-27 10:37:06 +00009246OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9247 SourceLocation StartLoc,
9248 SourceLocation LParenLoc,
9249 SourceLocation EndLoc) {
9250 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009251 SmallVector<Expr *, 8> SrcExprs;
9252 SmallVector<Expr *, 8> DstExprs;
9253 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009254 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009255 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9256 SourceLocation ELoc;
9257 SourceRange ERange;
9258 Expr *SimpleRefExpr = RefExpr;
9259 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9260 /*AllowArraySection=*/false);
9261 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009262 // It will be analyzed later.
9263 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009264 SrcExprs.push_back(nullptr);
9265 DstExprs.push_back(nullptr);
9266 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009267 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009268 ValueDecl *D = Res.first;
9269 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009270 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009271
Alexey Bataeve122da12016-03-17 10:50:17 +00009272 QualType Type = D->getType();
9273 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009274
9275 // OpenMP [2.14.4.2, Restrictions, p.2]
9276 // A list item that appears in a copyprivate clause may not appear in a
9277 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009278 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9279 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009280 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9281 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009282 Diag(ELoc, diag::err_omp_wrong_dsa)
9283 << getOpenMPClauseName(DVar.CKind)
9284 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009285 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009286 continue;
9287 }
9288
9289 // OpenMP [2.11.4.2, Restrictions, p.1]
9290 // All list items that appear in a copyprivate clause must be either
9291 // threadprivate or private in the enclosing context.
9292 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009293 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009294 if (DVar.CKind == OMPC_shared) {
9295 Diag(ELoc, diag::err_omp_required_access)
9296 << getOpenMPClauseName(OMPC_copyprivate)
9297 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009298 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009299 continue;
9300 }
9301 }
9302 }
9303
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009304 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009305 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009306 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009307 << getOpenMPClauseName(OMPC_copyprivate) << Type
9308 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009309 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009310 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009311 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009312 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009313 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009314 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009315 continue;
9316 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009317
Alexey Bataevbae9a792014-06-27 10:37:06 +00009318 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9319 // A variable of class type (or array thereof) that appears in a
9320 // copyin clause requires an accessible, unambiguous copy assignment
9321 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009322 Type = Context.getBaseElementType(Type.getNonReferenceType())
9323 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009324 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009325 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9326 D->hasAttrs() ? &D->getAttrs() : nullptr);
9327 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009328 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009329 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9330 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009331 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009332 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009333 PseudoDstExpr, PseudoSrcExpr);
9334 if (AssignmentOp.isInvalid())
9335 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009336 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009337 /*DiscardedValue=*/true);
9338 if (AssignmentOp.isInvalid())
9339 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009340
9341 // No need to mark vars as copyprivate, they are already threadprivate or
9342 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009343 assert(VD || IsOpenMPCapturedDecl(D));
9344 Vars.push_back(
9345 VD ? RefExpr->IgnoreParens()
9346 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009347 SrcExprs.push_back(PseudoSrcExpr);
9348 DstExprs.push_back(PseudoDstExpr);
9349 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009350 }
9351
9352 if (Vars.empty())
9353 return nullptr;
9354
Alexey Bataeva63048e2015-03-23 06:18:07 +00009355 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9356 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009357}
9358
Alexey Bataev6125da92014-07-21 11:26:11 +00009359OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9360 SourceLocation StartLoc,
9361 SourceLocation LParenLoc,
9362 SourceLocation EndLoc) {
9363 if (VarList.empty())
9364 return nullptr;
9365
9366 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9367}
Alexey Bataevdea47612014-07-23 07:46:59 +00009368
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009369OMPClause *
9370Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9371 SourceLocation DepLoc, SourceLocation ColonLoc,
9372 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9373 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009374 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009375 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009376 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009377 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009378 return nullptr;
9379 }
9380 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009381 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9382 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009383 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009384 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009385 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9386 /*Last=*/OMPC_DEPEND_unknown, Except)
9387 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009388 return nullptr;
9389 }
9390 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009391 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009392 llvm::APSInt DepCounter(/*BitWidth=*/32);
9393 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9394 if (DepKind == OMPC_DEPEND_sink) {
9395 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9396 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9397 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009398 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009399 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009400 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9401 DSAStack->getParentOrderedRegionParam()) {
9402 for (auto &RefExpr : VarList) {
9403 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009404 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009405 // It will be analyzed later.
9406 Vars.push_back(RefExpr);
9407 continue;
9408 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009409
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009410 SourceLocation ELoc = RefExpr->getExprLoc();
9411 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9412 if (DepKind == OMPC_DEPEND_sink) {
9413 if (DepCounter >= TotalDepCount) {
9414 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9415 continue;
9416 }
9417 ++DepCounter;
9418 // OpenMP [2.13.9, Summary]
9419 // depend(dependence-type : vec), where dependence-type is:
9420 // 'sink' and where vec is the iteration vector, which has the form:
9421 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9422 // where n is the value specified by the ordered clause in the loop
9423 // directive, xi denotes the loop iteration variable of the i-th nested
9424 // loop associated with the loop directive, and di is a constant
9425 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009426 if (CurContext->isDependentContext()) {
9427 // It will be analyzed later.
9428 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009429 continue;
9430 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009431 SimpleExpr = SimpleExpr->IgnoreImplicit();
9432 OverloadedOperatorKind OOK = OO_None;
9433 SourceLocation OOLoc;
9434 Expr *LHS = SimpleExpr;
9435 Expr *RHS = nullptr;
9436 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9437 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9438 OOLoc = BO->getOperatorLoc();
9439 LHS = BO->getLHS()->IgnoreParenImpCasts();
9440 RHS = BO->getRHS()->IgnoreParenImpCasts();
9441 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9442 OOK = OCE->getOperator();
9443 OOLoc = OCE->getOperatorLoc();
9444 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9445 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9446 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9447 OOK = MCE->getMethodDecl()
9448 ->getNameInfo()
9449 .getName()
9450 .getCXXOverloadedOperator();
9451 OOLoc = MCE->getCallee()->getExprLoc();
9452 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9453 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9454 }
9455 SourceLocation ELoc;
9456 SourceRange ERange;
9457 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9458 /*AllowArraySection=*/false);
9459 if (Res.second) {
9460 // It will be analyzed later.
9461 Vars.push_back(RefExpr);
9462 }
9463 ValueDecl *D = Res.first;
9464 if (!D)
9465 continue;
9466
9467 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9468 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9469 continue;
9470 }
9471 if (RHS) {
9472 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9473 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9474 if (RHSRes.isInvalid())
9475 continue;
9476 }
9477 if (!CurContext->isDependentContext() &&
9478 DSAStack->getParentOrderedRegionParam() &&
9479 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9480 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9481 << DSAStack->getParentLoopControlVariable(
9482 DepCounter.getZExtValue());
9483 continue;
9484 }
9485 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009486 } else {
9487 // OpenMP [2.11.1.1, Restrictions, p.3]
9488 // A variable that is part of another variable (such as a field of a
9489 // structure) but is not an array element or an array section cannot
9490 // appear in a depend clause.
9491 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9492 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9493 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9494 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9495 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009496 (ASE &&
9497 !ASE->getBase()
9498 ->getType()
9499 .getNonReferenceType()
9500 ->isPointerType() &&
9501 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009502 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9503 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009504 continue;
9505 }
9506 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009507 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9508 }
9509
9510 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9511 TotalDepCount > VarList.size() &&
9512 DSAStack->getParentOrderedRegionParam()) {
9513 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9514 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9515 }
9516 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9517 Vars.empty())
9518 return nullptr;
9519 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009520 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9521 DepKind, DepLoc, ColonLoc, Vars);
9522 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9523 DSAStack->addDoacrossDependClause(C, OpsOffs);
9524 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009525}
Michael Wonge710d542015-08-07 16:16:36 +00009526
9527OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9528 SourceLocation LParenLoc,
9529 SourceLocation EndLoc) {
9530 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009531
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009532 // OpenMP [2.9.1, Restrictions]
9533 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009534 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9535 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009536 return nullptr;
9537
Michael Wonge710d542015-08-07 16:16:36 +00009538 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9539}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009540
9541static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9542 DSAStackTy *Stack, CXXRecordDecl *RD) {
9543 if (!RD || RD->isInvalidDecl())
9544 return true;
9545
9546 auto QTy = SemaRef.Context.getRecordType(RD);
9547 if (RD->isDynamicClass()) {
9548 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9549 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9550 return false;
9551 }
9552 auto *DC = RD;
9553 bool IsCorrect = true;
9554 for (auto *I : DC->decls()) {
9555 if (I) {
9556 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9557 if (MD->isStatic()) {
9558 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9559 SemaRef.Diag(MD->getLocation(),
9560 diag::note_omp_static_member_in_target);
9561 IsCorrect = false;
9562 }
9563 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9564 if (VD->isStaticDataMember()) {
9565 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9566 SemaRef.Diag(VD->getLocation(),
9567 diag::note_omp_static_member_in_target);
9568 IsCorrect = false;
9569 }
9570 }
9571 }
9572 }
9573
9574 for (auto &I : RD->bases()) {
9575 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9576 I.getType()->getAsCXXRecordDecl()))
9577 IsCorrect = false;
9578 }
9579 return IsCorrect;
9580}
9581
9582static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9583 DSAStackTy *Stack, QualType QTy) {
9584 NamedDecl *ND;
9585 if (QTy->isIncompleteType(&ND)) {
9586 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9587 return false;
9588 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009589 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009590 return false;
9591 }
9592 return true;
9593}
9594
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009595/// \brief Return true if it can be proven that the provided array expression
9596/// (array section or array subscript) does NOT specify the whole size of the
9597/// array whose base type is \a BaseQTy.
9598static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9599 const Expr *E,
9600 QualType BaseQTy) {
9601 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9602
9603 // If this is an array subscript, it refers to the whole size if the size of
9604 // the dimension is constant and equals 1. Also, an array section assumes the
9605 // format of an array subscript if no colon is used.
9606 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9607 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9608 return ATy->getSize().getSExtValue() != 1;
9609 // Size can't be evaluated statically.
9610 return false;
9611 }
9612
9613 assert(OASE && "Expecting array section if not an array subscript.");
9614 auto *LowerBound = OASE->getLowerBound();
9615 auto *Length = OASE->getLength();
9616
9617 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009618 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009619 if (LowerBound) {
9620 llvm::APSInt ConstLowerBound;
9621 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9622 return false; // Can't get the integer value as a constant.
9623 if (ConstLowerBound.getSExtValue())
9624 return true;
9625 }
9626
9627 // If we don't have a length we covering the whole dimension.
9628 if (!Length)
9629 return false;
9630
9631 // If the base is a pointer, we don't have a way to get the size of the
9632 // pointee.
9633 if (BaseQTy->isPointerType())
9634 return false;
9635
9636 // We can only check if the length is the same as the size of the dimension
9637 // if we have a constant array.
9638 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9639 if (!CATy)
9640 return false;
9641
9642 llvm::APSInt ConstLength;
9643 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9644 return false; // Can't get the integer value as a constant.
9645
9646 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9647}
9648
9649// Return true if it can be proven that the provided array expression (array
9650// section or array subscript) does NOT specify a single element of the array
9651// whose base type is \a BaseQTy.
9652static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009653 const Expr *E,
9654 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009655 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9656
9657 // An array subscript always refer to a single element. Also, an array section
9658 // assumes the format of an array subscript if no colon is used.
9659 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9660 return false;
9661
9662 assert(OASE && "Expecting array section if not an array subscript.");
9663 auto *Length = OASE->getLength();
9664
9665 // If we don't have a length we have to check if the array has unitary size
9666 // for this dimension. Also, we should always expect a length if the base type
9667 // is pointer.
9668 if (!Length) {
9669 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9670 return ATy->getSize().getSExtValue() != 1;
9671 // We cannot assume anything.
9672 return false;
9673 }
9674
9675 // Check if the length evaluates to 1.
9676 llvm::APSInt ConstLength;
9677 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9678 return false; // Can't get the integer value as a constant.
9679
9680 return ConstLength.getSExtValue() != 1;
9681}
9682
Samuel Antao661c0902016-05-26 17:39:58 +00009683// Return the expression of the base of the mappable expression or null if it
9684// cannot be determined and do all the necessary checks to see if the expression
9685// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009686// components of the expression.
9687static Expr *CheckMapClauseExpressionBase(
9688 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009689 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9690 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009691 SourceLocation ELoc = E->getExprLoc();
9692 SourceRange ERange = E->getSourceRange();
9693
9694 // The base of elements of list in a map clause have to be either:
9695 // - a reference to variable or field.
9696 // - a member expression.
9697 // - an array expression.
9698 //
9699 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9700 // reference to 'r'.
9701 //
9702 // If we have:
9703 //
9704 // struct SS {
9705 // Bla S;
9706 // foo() {
9707 // #pragma omp target map (S.Arr[:12]);
9708 // }
9709 // }
9710 //
9711 // We want to retrieve the member expression 'this->S';
9712
9713 Expr *RelevantExpr = nullptr;
9714
Samuel Antao5de996e2016-01-22 20:21:36 +00009715 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9716 // If a list item is an array section, it must specify contiguous storage.
9717 //
9718 // For this restriction it is sufficient that we make sure only references
9719 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009720 // exist except in the rightmost expression (unless they cover the whole
9721 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009722 //
9723 // r.ArrS[3:5].Arr[6:7]
9724 //
9725 // r.ArrS[3:5].x
9726 //
9727 // but these would be valid:
9728 // r.ArrS[3].Arr[6:7]
9729 //
9730 // r.ArrS[3].x
9731
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009732 bool AllowUnitySizeArraySection = true;
9733 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009734
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009735 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009736 E = E->IgnoreParenImpCasts();
9737
9738 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9739 if (!isa<VarDecl>(CurE->getDecl()))
9740 break;
9741
9742 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009743
9744 // If we got a reference to a declaration, we should not expect any array
9745 // section before that.
9746 AllowUnitySizeArraySection = false;
9747 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009748
9749 // Record the component.
9750 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9751 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009752 continue;
9753 }
9754
9755 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9756 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9757
9758 if (isa<CXXThisExpr>(BaseE))
9759 // We found a base expression: this->Val.
9760 RelevantExpr = CurE;
9761 else
9762 E = BaseE;
9763
9764 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9765 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9766 << CurE->getSourceRange();
9767 break;
9768 }
9769
9770 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9771
9772 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9773 // A bit-field cannot appear in a map clause.
9774 //
9775 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009776 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9777 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009778 break;
9779 }
9780
9781 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9782 // If the type of a list item is a reference to a type T then the type
9783 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009784 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009785
9786 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9787 // A list item cannot be a variable that is a member of a structure with
9788 // a union type.
9789 //
9790 if (auto *RT = CurType->getAs<RecordType>())
9791 if (RT->isUnionType()) {
9792 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9793 << CurE->getSourceRange();
9794 break;
9795 }
9796
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009797 // If we got a member expression, we should not expect any array section
9798 // before that:
9799 //
9800 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9801 // If a list item is an element of a structure, only the rightmost symbol
9802 // of the variable reference can be an array section.
9803 //
9804 AllowUnitySizeArraySection = false;
9805 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009806
9807 // Record the component.
9808 CurComponents.push_back(
9809 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009810 continue;
9811 }
9812
9813 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9814 E = CurE->getBase()->IgnoreParenImpCasts();
9815
9816 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9817 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9818 << 0 << CurE->getSourceRange();
9819 break;
9820 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009821
9822 // If we got an array subscript that express the whole dimension we
9823 // can have any array expressions before. If it only expressing part of
9824 // the dimension, we can only have unitary-size array expressions.
9825 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9826 E->getType()))
9827 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009828
9829 // Record the component - we don't have any declaration associated.
9830 CurComponents.push_back(
9831 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009832 continue;
9833 }
9834
9835 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009836 E = CurE->getBase()->IgnoreParenImpCasts();
9837
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009838 auto CurType =
9839 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9840
Samuel Antao5de996e2016-01-22 20:21:36 +00009841 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9842 // If the type of a list item is a reference to a type T then the type
9843 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009844 if (CurType->isReferenceType())
9845 CurType = CurType->getPointeeType();
9846
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009847 bool IsPointer = CurType->isAnyPointerType();
9848
9849 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009850 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9851 << 0 << CurE->getSourceRange();
9852 break;
9853 }
9854
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009855 bool NotWhole =
9856 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9857 bool NotUnity =
9858 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9859
Samuel Antaodab51bb2016-07-18 23:22:11 +00009860 if (AllowWholeSizeArraySection) {
9861 // Any array section is currently allowed. Allowing a whole size array
9862 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009863 //
9864 // If this array section refers to the whole dimension we can still
9865 // accept other array sections before this one, except if the base is a
9866 // pointer. Otherwise, only unitary sections are accepted.
9867 if (NotWhole || IsPointer)
9868 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009869 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009870 // A unity or whole array section is not allowed and that is not
9871 // compatible with the properties of the current array section.
9872 SemaRef.Diag(
9873 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9874 << CurE->getSourceRange();
9875 break;
9876 }
Samuel Antao90927002016-04-26 14:54:23 +00009877
9878 // Record the component - we don't have any declaration associated.
9879 CurComponents.push_back(
9880 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009881 continue;
9882 }
9883
9884 // If nothing else worked, this is not a valid map clause expression.
9885 SemaRef.Diag(ELoc,
9886 diag::err_omp_expected_named_var_member_or_array_expression)
9887 << ERange;
9888 break;
9889 }
9890
9891 return RelevantExpr;
9892}
9893
9894// Return true if expression E associated with value VD has conflicts with other
9895// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009896static bool CheckMapConflicts(
9897 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9898 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009899 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9900 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009901 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009902 SourceLocation ELoc = E->getExprLoc();
9903 SourceRange ERange = E->getSourceRange();
9904
9905 // In order to easily check the conflicts we need to match each component of
9906 // the expression under test with the components of the expressions that are
9907 // already in the stack.
9908
Samuel Antao5de996e2016-01-22 20:21:36 +00009909 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009910 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009911 "Map clause expression with unexpected base!");
9912
9913 // Variables to help detecting enclosing problems in data environment nests.
9914 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009915 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009916
Samuel Antao90927002016-04-26 14:54:23 +00009917 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9918 VD, CurrentRegionOnly,
9919 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009920 StackComponents,
9921 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009922
Samuel Antao5de996e2016-01-22 20:21:36 +00009923 assert(!StackComponents.empty() &&
9924 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009925 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009926 "Map clause expression with unexpected base!");
9927
Samuel Antao90927002016-04-26 14:54:23 +00009928 // The whole expression in the stack.
9929 auto *RE = StackComponents.front().getAssociatedExpression();
9930
Samuel Antao5de996e2016-01-22 20:21:36 +00009931 // Expressions must start from the same base. Here we detect at which
9932 // point both expressions diverge from each other and see if we can
9933 // detect if the memory referred to both expressions is contiguous and
9934 // do not overlap.
9935 auto CI = CurComponents.rbegin();
9936 auto CE = CurComponents.rend();
9937 auto SI = StackComponents.rbegin();
9938 auto SE = StackComponents.rend();
9939 for (; CI != CE && SI != SE; ++CI, ++SI) {
9940
9941 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9942 // At most one list item can be an array item derived from a given
9943 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009944 if (CurrentRegionOnly &&
9945 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9946 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9947 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9948 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9949 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009950 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009951 << CI->getAssociatedExpression()->getSourceRange();
9952 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9953 diag::note_used_here)
9954 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009955 return true;
9956 }
9957
9958 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009959 if (CI->getAssociatedExpression()->getStmtClass() !=
9960 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009961 break;
9962
9963 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009964 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009965 break;
9966 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009967 // Check if the extra components of the expressions in the enclosing
9968 // data environment are redundant for the current base declaration.
9969 // If they are, the maps completely overlap, which is legal.
9970 for (; SI != SE; ++SI) {
9971 QualType Type;
9972 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009973 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009974 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009975 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9976 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009977 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9978 Type =
9979 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9980 }
9981 if (Type.isNull() || Type->isAnyPointerType() ||
9982 CheckArrayExpressionDoesNotReferToWholeSize(
9983 SemaRef, SI->getAssociatedExpression(), Type))
9984 break;
9985 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009986
9987 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9988 // List items of map clauses in the same construct must not share
9989 // original storage.
9990 //
9991 // If the expressions are exactly the same or one is a subset of the
9992 // other, it means they are sharing storage.
9993 if (CI == CE && SI == SE) {
9994 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009995 if (CKind == OMPC_map)
9996 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9997 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009998 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009999 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10000 << ERange;
10001 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010002 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10003 << RE->getSourceRange();
10004 return true;
10005 } else {
10006 // If we find the same expression in the enclosing data environment,
10007 // that is legal.
10008 IsEnclosedByDataEnvironmentExpr = true;
10009 return false;
10010 }
10011 }
10012
Samuel Antao90927002016-04-26 14:54:23 +000010013 QualType DerivedType =
10014 std::prev(CI)->getAssociatedDeclaration()->getType();
10015 SourceLocation DerivedLoc =
10016 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010017
10018 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10019 // If the type of a list item is a reference to a type T then the type
10020 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010021 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010022
10023 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10024 // A variable for which the type is pointer and an array section
10025 // derived from that variable must not appear as list items of map
10026 // clauses of the same construct.
10027 //
10028 // Also, cover one of the cases in:
10029 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10030 // If any part of the original storage of a list item has corresponding
10031 // storage in the device data environment, all of the original storage
10032 // must have corresponding storage in the device data environment.
10033 //
10034 if (DerivedType->isAnyPointerType()) {
10035 if (CI == CE || SI == SE) {
10036 SemaRef.Diag(
10037 DerivedLoc,
10038 diag::err_omp_pointer_mapped_along_with_derived_section)
10039 << DerivedLoc;
10040 } else {
10041 assert(CI != CE && SI != SE);
10042 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10043 << DerivedLoc;
10044 }
10045 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10046 << RE->getSourceRange();
10047 return true;
10048 }
10049
10050 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10051 // List items of map clauses in the same construct must not share
10052 // original storage.
10053 //
10054 // An expression is a subset of the other.
10055 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010056 if (CKind == OMPC_map)
10057 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10058 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010059 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010060 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10061 << ERange;
10062 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010063 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10064 << RE->getSourceRange();
10065 return true;
10066 }
10067
10068 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010069 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010070 if (!CurrentRegionOnly && SI != SE)
10071 EnclosingExpr = RE;
10072
10073 // The current expression is a subset of the expression in the data
10074 // environment.
10075 IsEnclosedByDataEnvironmentExpr |=
10076 (!CurrentRegionOnly && CI != CE && SI == SE);
10077
10078 return false;
10079 });
10080
10081 if (CurrentRegionOnly)
10082 return FoundError;
10083
10084 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10085 // If any part of the original storage of a list item has corresponding
10086 // storage in the device data environment, all of the original storage must
10087 // have corresponding storage in the device data environment.
10088 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10089 // If a list item is an element of a structure, and a different element of
10090 // the structure has a corresponding list item in the device data environment
10091 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010092 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010093 // data environment prior to the task encountering the construct.
10094 //
10095 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10096 SemaRef.Diag(ELoc,
10097 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10098 << ERange;
10099 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10100 << EnclosingExpr->getSourceRange();
10101 return true;
10102 }
10103
10104 return FoundError;
10105}
10106
Samuel Antao661c0902016-05-26 17:39:58 +000010107namespace {
10108// Utility struct that gathers all the related lists associated with a mappable
10109// expression.
10110struct MappableVarListInfo final {
10111 // The list of expressions.
10112 ArrayRef<Expr *> VarList;
10113 // The list of processed expressions.
10114 SmallVector<Expr *, 16> ProcessedVarList;
10115 // The mappble components for each expression.
10116 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10117 // The base declaration of the variable.
10118 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10119
10120 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10121 // We have a list of components and base declarations for each entry in the
10122 // variable list.
10123 VarComponents.reserve(VarList.size());
10124 VarBaseDeclarations.reserve(VarList.size());
10125 }
10126};
10127}
10128
10129// Check the validity of the provided variable list for the provided clause kind
10130// \a CKind. In the check process the valid expressions, and mappable expression
10131// components and variables are extracted and used to fill \a Vars,
10132// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10133// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10134static void
10135checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10136 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10137 SourceLocation StartLoc,
10138 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10139 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010140 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10141 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010142 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010143
Samuel Antao90927002016-04-26 14:54:23 +000010144 // Keep track of the mappable components and base declarations in this clause.
10145 // Each entry in the list is going to have a list of components associated. We
10146 // record each set of the components so that we can build the clause later on.
10147 // In the end we should have the same amount of declarations and component
10148 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010149
Samuel Antao661c0902016-05-26 17:39:58 +000010150 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010151 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010152 SourceLocation ELoc = RE->getExprLoc();
10153
Kelvin Li0bff7af2015-11-23 05:32:03 +000010154 auto *VE = RE->IgnoreParenLValueCasts();
10155
10156 if (VE->isValueDependent() || VE->isTypeDependent() ||
10157 VE->isInstantiationDependent() ||
10158 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010159 // We can only analyze this information once the missing information is
10160 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010161 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010162 continue;
10163 }
10164
10165 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010166
Samuel Antao5de996e2016-01-22 20:21:36 +000010167 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010168 SemaRef.Diag(ELoc,
10169 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010170 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010171 continue;
10172 }
10173
Samuel Antao90927002016-04-26 14:54:23 +000010174 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10175 ValueDecl *CurDeclaration = nullptr;
10176
10177 // Obtain the array or member expression bases if required. Also, fill the
10178 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010179 auto *BE =
10180 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010181 if (!BE)
10182 continue;
10183
Samuel Antao90927002016-04-26 14:54:23 +000010184 assert(!CurComponents.empty() &&
10185 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010186
Samuel Antao90927002016-04-26 14:54:23 +000010187 // For the following checks, we rely on the base declaration which is
10188 // expected to be associated with the last component. The declaration is
10189 // expected to be a variable or a field (if 'this' is being mapped).
10190 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10191 assert(CurDeclaration && "Null decl on map clause.");
10192 assert(
10193 CurDeclaration->isCanonicalDecl() &&
10194 "Expecting components to have associated only canonical declarations.");
10195
10196 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10197 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010198
10199 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010200 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010201
10202 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010203 // threadprivate variables cannot appear in a map clause.
10204 // OpenMP 4.5 [2.10.5, target update Construct]
10205 // threadprivate variables cannot appear in a from clause.
10206 if (VD && DSAS->isThreadPrivate(VD)) {
10207 auto DVar = DSAS->getTopDSA(VD, false);
10208 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10209 << getOpenMPClauseName(CKind);
10210 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010211 continue;
10212 }
10213
Samuel Antao5de996e2016-01-22 20:21:36 +000010214 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10215 // A list item cannot appear in both a map clause and a data-sharing
10216 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010217
Samuel Antao5de996e2016-01-22 20:21:36 +000010218 // Check conflicts with other map clause expressions. We check the conflicts
10219 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010220 // environment, because the restrictions are different. We only have to
10221 // check conflicts across regions for the map clauses.
10222 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10223 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010224 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010225 if (CKind == OMPC_map &&
10226 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10227 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010228 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010229
Samuel Antao661c0902016-05-26 17:39:58 +000010230 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010231 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10232 // If the type of a list item is a reference to a type T then the type will
10233 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010234 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010235
Samuel Antao661c0902016-05-26 17:39:58 +000010236 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10237 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010238 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010239 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010240 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10241 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010242 continue;
10243
Samuel Antao661c0902016-05-26 17:39:58 +000010244 if (CKind == OMPC_map) {
10245 // target enter data
10246 // OpenMP [2.10.2, Restrictions, p. 99]
10247 // A map-type must be specified in all map clauses and must be either
10248 // to or alloc.
10249 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10250 if (DKind == OMPD_target_enter_data &&
10251 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10252 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10253 << (IsMapTypeImplicit ? 1 : 0)
10254 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10255 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010256 continue;
10257 }
Samuel Antao661c0902016-05-26 17:39:58 +000010258
10259 // target exit_data
10260 // OpenMP [2.10.3, Restrictions, p. 102]
10261 // A map-type must be specified in all map clauses and must be either
10262 // from, release, or delete.
10263 if (DKind == OMPD_target_exit_data &&
10264 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10265 MapType == OMPC_MAP_delete)) {
10266 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10267 << (IsMapTypeImplicit ? 1 : 0)
10268 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10269 << getOpenMPDirectiveName(DKind);
10270 continue;
10271 }
10272
10273 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10274 // A list item cannot appear in both a map clause and a data-sharing
10275 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010276 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010277 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010278 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010279 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10280 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010281 auto DVar = DSAS->getTopDSA(VD, false);
10282 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010283 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010284 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010285 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010286 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10287 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10288 continue;
10289 }
10290 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010291 }
10292
Samuel Antao90927002016-04-26 14:54:23 +000010293 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010294 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010295
10296 // Store the components in the stack so that they can be used to check
10297 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010298 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10299 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010300
10301 // Save the components and declaration to create the clause. For purposes of
10302 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010303 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010304 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10305 MVLI.VarComponents.back().append(CurComponents.begin(),
10306 CurComponents.end());
10307 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10308 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010309 }
Samuel Antao661c0902016-05-26 17:39:58 +000010310}
10311
10312OMPClause *
10313Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10314 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10315 SourceLocation MapLoc, SourceLocation ColonLoc,
10316 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10317 SourceLocation LParenLoc, SourceLocation EndLoc) {
10318 MappableVarListInfo MVLI(VarList);
10319 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10320 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010321
Samuel Antao5de996e2016-01-22 20:21:36 +000010322 // We need to produce a map clause even if we don't have variables so that
10323 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010324 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10325 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10326 MVLI.VarComponents, MapTypeModifier, MapType,
10327 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010328}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010329
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010330QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10331 TypeResult ParsedType) {
10332 assert(ParsedType.isUsable());
10333
10334 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10335 if (ReductionType.isNull())
10336 return QualType();
10337
10338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10339 // A type name in a declare reduction directive cannot be a function type, an
10340 // array type, a reference type, or a type qualified with const, volatile or
10341 // restrict.
10342 if (ReductionType.hasQualifiers()) {
10343 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10344 return QualType();
10345 }
10346
10347 if (ReductionType->isFunctionType()) {
10348 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10349 return QualType();
10350 }
10351 if (ReductionType->isReferenceType()) {
10352 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10353 return QualType();
10354 }
10355 if (ReductionType->isArrayType()) {
10356 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10357 return QualType();
10358 }
10359 return ReductionType;
10360}
10361
10362Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10363 Scope *S, DeclContext *DC, DeclarationName Name,
10364 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10365 AccessSpecifier AS, Decl *PrevDeclInScope) {
10366 SmallVector<Decl *, 8> Decls;
10367 Decls.reserve(ReductionTypes.size());
10368
10369 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10370 ForRedeclaration);
10371 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10372 // A reduction-identifier may not be re-declared in the current scope for the
10373 // same type or for a type that is compatible according to the base language
10374 // rules.
10375 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10376 OMPDeclareReductionDecl *PrevDRD = nullptr;
10377 bool InCompoundScope = true;
10378 if (S != nullptr) {
10379 // Find previous declaration with the same name not referenced in other
10380 // declarations.
10381 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10382 InCompoundScope =
10383 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10384 LookupName(Lookup, S);
10385 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10386 /*AllowInlineNamespace=*/false);
10387 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10388 auto Filter = Lookup.makeFilter();
10389 while (Filter.hasNext()) {
10390 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10391 if (InCompoundScope) {
10392 auto I = UsedAsPrevious.find(PrevDecl);
10393 if (I == UsedAsPrevious.end())
10394 UsedAsPrevious[PrevDecl] = false;
10395 if (auto *D = PrevDecl->getPrevDeclInScope())
10396 UsedAsPrevious[D] = true;
10397 }
10398 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10399 PrevDecl->getLocation();
10400 }
10401 Filter.done();
10402 if (InCompoundScope) {
10403 for (auto &PrevData : UsedAsPrevious) {
10404 if (!PrevData.second) {
10405 PrevDRD = PrevData.first;
10406 break;
10407 }
10408 }
10409 }
10410 } else if (PrevDeclInScope != nullptr) {
10411 auto *PrevDRDInScope = PrevDRD =
10412 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10413 do {
10414 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10415 PrevDRDInScope->getLocation();
10416 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10417 } while (PrevDRDInScope != nullptr);
10418 }
10419 for (auto &TyData : ReductionTypes) {
10420 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10421 bool Invalid = false;
10422 if (I != PreviousRedeclTypes.end()) {
10423 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10424 << TyData.first;
10425 Diag(I->second, diag::note_previous_definition);
10426 Invalid = true;
10427 }
10428 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10429 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10430 Name, TyData.first, PrevDRD);
10431 DC->addDecl(DRD);
10432 DRD->setAccess(AS);
10433 Decls.push_back(DRD);
10434 if (Invalid)
10435 DRD->setInvalidDecl();
10436 else
10437 PrevDRD = DRD;
10438 }
10439
10440 return DeclGroupPtrTy::make(
10441 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10442}
10443
10444void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10445 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10446
10447 // Enter new function scope.
10448 PushFunctionScope();
10449 getCurFunction()->setHasBranchProtectedScope();
10450 getCurFunction()->setHasOMPDeclareReductionCombiner();
10451
10452 if (S != nullptr)
10453 PushDeclContext(S, DRD);
10454 else
10455 CurContext = DRD;
10456
10457 PushExpressionEvaluationContext(PotentiallyEvaluated);
10458
10459 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010460 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10461 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10462 // uses semantics of argument handles by value, but it should be passed by
10463 // reference. C lang does not support references, so pass all parameters as
10464 // pointers.
10465 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010466 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010467 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010468 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10469 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10470 // uses semantics of argument handles by value, but it should be passed by
10471 // reference. C lang does not support references, so pass all parameters as
10472 // pointers.
10473 // Create 'T omp_out;' variable.
10474 auto *OmpOutParm =
10475 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10476 if (S != nullptr) {
10477 PushOnScopeChains(OmpInParm, S);
10478 PushOnScopeChains(OmpOutParm, S);
10479 } else {
10480 DRD->addDecl(OmpInParm);
10481 DRD->addDecl(OmpOutParm);
10482 }
10483}
10484
10485void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10486 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10487 DiscardCleanupsInEvaluationContext();
10488 PopExpressionEvaluationContext();
10489
10490 PopDeclContext();
10491 PopFunctionScopeInfo();
10492
10493 if (Combiner != nullptr)
10494 DRD->setCombiner(Combiner);
10495 else
10496 DRD->setInvalidDecl();
10497}
10498
10499void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10500 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10501
10502 // Enter new function scope.
10503 PushFunctionScope();
10504 getCurFunction()->setHasBranchProtectedScope();
10505
10506 if (S != nullptr)
10507 PushDeclContext(S, DRD);
10508 else
10509 CurContext = DRD;
10510
10511 PushExpressionEvaluationContext(PotentiallyEvaluated);
10512
10513 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010514 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10515 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10516 // uses semantics of argument handles by value, but it should be passed by
10517 // reference. C lang does not support references, so pass all parameters as
10518 // pointers.
10519 // Create 'T omp_priv;' variable.
10520 auto *OmpPrivParm =
10521 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010522 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10523 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10524 // uses semantics of argument handles by value, but it should be passed by
10525 // reference. C lang does not support references, so pass all parameters as
10526 // pointers.
10527 // Create 'T omp_orig;' variable.
10528 auto *OmpOrigParm =
10529 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010530 if (S != nullptr) {
10531 PushOnScopeChains(OmpPrivParm, S);
10532 PushOnScopeChains(OmpOrigParm, S);
10533 } else {
10534 DRD->addDecl(OmpPrivParm);
10535 DRD->addDecl(OmpOrigParm);
10536 }
10537}
10538
10539void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10540 Expr *Initializer) {
10541 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10542 DiscardCleanupsInEvaluationContext();
10543 PopExpressionEvaluationContext();
10544
10545 PopDeclContext();
10546 PopFunctionScopeInfo();
10547
10548 if (Initializer != nullptr)
10549 DRD->setInitializer(Initializer);
10550 else
10551 DRD->setInvalidDecl();
10552}
10553
10554Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10555 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10556 for (auto *D : DeclReductions.get()) {
10557 if (IsValid) {
10558 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10559 if (S != nullptr)
10560 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10561 } else
10562 D->setInvalidDecl();
10563 }
10564 return DeclReductions;
10565}
10566
David Majnemer9d168222016-08-05 17:44:54 +000010567OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010568 SourceLocation StartLoc,
10569 SourceLocation LParenLoc,
10570 SourceLocation EndLoc) {
10571 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010572
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010573 // OpenMP [teams Constrcut, Restrictions]
10574 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010575 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10576 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010577 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010578
10579 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10580}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010581
10582OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10583 SourceLocation StartLoc,
10584 SourceLocation LParenLoc,
10585 SourceLocation EndLoc) {
10586 Expr *ValExpr = ThreadLimit;
10587
10588 // OpenMP [teams Constrcut, Restrictions]
10589 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010590 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10591 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010592 return nullptr;
10593
David Majnemer9d168222016-08-05 17:44:54 +000010594 return new (Context)
10595 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010596}
Alexey Bataeva0569352015-12-01 10:17:31 +000010597
10598OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10599 SourceLocation StartLoc,
10600 SourceLocation LParenLoc,
10601 SourceLocation EndLoc) {
10602 Expr *ValExpr = Priority;
10603
10604 // OpenMP [2.9.1, task Constrcut]
10605 // The priority-value is a non-negative numerical scalar expression.
10606 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10607 /*StrictlyPositive=*/false))
10608 return nullptr;
10609
10610 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10611}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010612
10613OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10614 SourceLocation StartLoc,
10615 SourceLocation LParenLoc,
10616 SourceLocation EndLoc) {
10617 Expr *ValExpr = Grainsize;
10618
10619 // OpenMP [2.9.2, taskloop Constrcut]
10620 // The parameter of the grainsize clause must be a positive integer
10621 // expression.
10622 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10623 /*StrictlyPositive=*/true))
10624 return nullptr;
10625
10626 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10627}
Alexey Bataev382967a2015-12-08 12:06:20 +000010628
10629OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10630 SourceLocation StartLoc,
10631 SourceLocation LParenLoc,
10632 SourceLocation EndLoc) {
10633 Expr *ValExpr = NumTasks;
10634
10635 // OpenMP [2.9.2, taskloop Constrcut]
10636 // The parameter of the num_tasks clause must be a positive integer
10637 // expression.
10638 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10639 /*StrictlyPositive=*/true))
10640 return nullptr;
10641
10642 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10643}
10644
Alexey Bataev28c75412015-12-15 08:19:24 +000010645OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10646 SourceLocation LParenLoc,
10647 SourceLocation EndLoc) {
10648 // OpenMP [2.13.2, critical construct, Description]
10649 // ... where hint-expression is an integer constant expression that evaluates
10650 // to a valid lock hint.
10651 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10652 if (HintExpr.isInvalid())
10653 return nullptr;
10654 return new (Context)
10655 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10656}
10657
Carlo Bertollib4adf552016-01-15 18:50:31 +000010658OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10659 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10660 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10661 SourceLocation EndLoc) {
10662 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10663 std::string Values;
10664 Values += "'";
10665 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10666 Values += "'";
10667 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10668 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10669 return nullptr;
10670 }
10671 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010672 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010673 if (ChunkSize) {
10674 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10675 !ChunkSize->isInstantiationDependent() &&
10676 !ChunkSize->containsUnexpandedParameterPack()) {
10677 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10678 ExprResult Val =
10679 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10680 if (Val.isInvalid())
10681 return nullptr;
10682
10683 ValExpr = Val.get();
10684
10685 // OpenMP [2.7.1, Restrictions]
10686 // chunk_size must be a loop invariant integer expression with a positive
10687 // value.
10688 llvm::APSInt Result;
10689 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10690 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10691 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10692 << "dist_schedule" << ChunkSize->getSourceRange();
10693 return nullptr;
10694 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010695 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10696 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010697 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10698 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10699 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010700 }
10701 }
10702 }
10703
10704 return new (Context)
10705 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010706 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010707}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010708
10709OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10710 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10711 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10712 SourceLocation KindLoc, SourceLocation EndLoc) {
10713 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010714 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010715 std::string Value;
10716 SourceLocation Loc;
10717 Value += "'";
10718 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10719 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010720 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010721 Loc = MLoc;
10722 } else {
10723 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010724 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010725 Loc = KindLoc;
10726 }
10727 Value += "'";
10728 Diag(Loc, diag::err_omp_unexpected_clause_value)
10729 << Value << getOpenMPClauseName(OMPC_defaultmap);
10730 return nullptr;
10731 }
10732
10733 return new (Context)
10734 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10735}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010736
10737bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10738 DeclContext *CurLexicalContext = getCurLexicalContext();
10739 if (!CurLexicalContext->isFileContext() &&
10740 !CurLexicalContext->isExternCContext() &&
10741 !CurLexicalContext->isExternCXXContext()) {
10742 Diag(Loc, diag::err_omp_region_not_file_context);
10743 return false;
10744 }
10745 if (IsInOpenMPDeclareTargetContext) {
10746 Diag(Loc, diag::err_omp_enclosed_declare_target);
10747 return false;
10748 }
10749
10750 IsInOpenMPDeclareTargetContext = true;
10751 return true;
10752}
10753
10754void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10755 assert(IsInOpenMPDeclareTargetContext &&
10756 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10757
10758 IsInOpenMPDeclareTargetContext = false;
10759}
10760
David Majnemer9d168222016-08-05 17:44:54 +000010761void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10762 CXXScopeSpec &ScopeSpec,
10763 const DeclarationNameInfo &Id,
10764 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10765 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010766 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10767 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10768
10769 if (Lookup.isAmbiguous())
10770 return;
10771 Lookup.suppressDiagnostics();
10772
10773 if (!Lookup.isSingleResult()) {
10774 if (TypoCorrection Corrected =
10775 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10776 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10777 CTK_ErrorRecovery)) {
10778 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10779 << Id.getName());
10780 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10781 return;
10782 }
10783
10784 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10785 return;
10786 }
10787
10788 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10789 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10790 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10791 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10792
10793 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10794 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10795 ND->addAttr(A);
10796 if (ASTMutationListener *ML = Context.getASTMutationListener())
10797 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10798 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10799 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10800 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10801 << Id.getName();
10802 }
10803 } else
10804 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10805}
10806
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010807static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10808 Sema &SemaRef, Decl *D) {
10809 if (!D)
10810 return;
10811 Decl *LD = nullptr;
10812 if (isa<TagDecl>(D)) {
10813 LD = cast<TagDecl>(D)->getDefinition();
10814 } else if (isa<VarDecl>(D)) {
10815 LD = cast<VarDecl>(D)->getDefinition();
10816
10817 // If this is an implicit variable that is legal and we do not need to do
10818 // anything.
10819 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010820 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10821 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10822 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010823 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010824 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010825 return;
10826 }
10827
10828 } else if (isa<FunctionDecl>(D)) {
10829 const FunctionDecl *FD = nullptr;
10830 if (cast<FunctionDecl>(D)->hasBody(FD))
10831 LD = const_cast<FunctionDecl *>(FD);
10832
10833 // If the definition is associated with the current declaration in the
10834 // target region (it can be e.g. a lambda) that is legal and we do not need
10835 // to do anything else.
10836 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010837 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10838 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10839 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010840 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010841 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010842 return;
10843 }
10844 }
10845 if (!LD)
10846 LD = D;
10847 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10848 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10849 // Outlined declaration is not declared target.
10850 if (LD->isOutOfLine()) {
10851 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10852 SemaRef.Diag(SL, diag::note_used_here) << SR;
10853 } else {
10854 DeclContext *DC = LD->getDeclContext();
10855 while (DC) {
10856 if (isa<FunctionDecl>(DC) &&
10857 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10858 break;
10859 DC = DC->getParent();
10860 }
10861 if (DC)
10862 return;
10863
10864 // Is not declared in target context.
10865 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10866 SemaRef.Diag(SL, diag::note_used_here) << SR;
10867 }
10868 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010869 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10870 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10871 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010872 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010873 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010874 }
10875}
10876
10877static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10878 Sema &SemaRef, DSAStackTy *Stack,
10879 ValueDecl *VD) {
10880 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10881 return true;
10882 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10883 return false;
10884 return true;
10885}
10886
10887void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10888 if (!D || D->isInvalidDecl())
10889 return;
10890 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10891 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10892 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10893 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10894 if (DSAStack->isThreadPrivate(VD)) {
10895 Diag(SL, diag::err_omp_threadprivate_in_target);
10896 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10897 return;
10898 }
10899 }
10900 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10901 // Problem if any with var declared with incomplete type will be reported
10902 // as normal, so no need to check it here.
10903 if ((E || !VD->getType()->isIncompleteType()) &&
10904 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10905 // Mark decl as declared target to prevent further diagnostic.
10906 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010907 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10908 Context, OMPDeclareTargetDeclAttr::MT_To);
10909 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010910 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010911 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010912 }
10913 return;
10914 }
10915 }
10916 if (!E) {
10917 // Checking declaration inside declare target region.
10918 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10919 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010920 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10921 Context, OMPDeclareTargetDeclAttr::MT_To);
10922 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010923 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010924 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010925 }
10926 return;
10927 }
10928 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10929}
Samuel Antao661c0902016-05-26 17:39:58 +000010930
10931OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10932 SourceLocation StartLoc,
10933 SourceLocation LParenLoc,
10934 SourceLocation EndLoc) {
10935 MappableVarListInfo MVLI(VarList);
10936 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10937 if (MVLI.ProcessedVarList.empty())
10938 return nullptr;
10939
10940 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10941 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10942 MVLI.VarComponents);
10943}
Samuel Antaoec172c62016-05-26 17:49:04 +000010944
10945OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10946 SourceLocation StartLoc,
10947 SourceLocation LParenLoc,
10948 SourceLocation EndLoc) {
10949 MappableVarListInfo MVLI(VarList);
10950 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10951 if (MVLI.ProcessedVarList.empty())
10952 return nullptr;
10953
10954 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10955 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10956 MVLI.VarComponents);
10957}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010958
10959OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10960 SourceLocation StartLoc,
10961 SourceLocation LParenLoc,
10962 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010963 MappableVarListInfo MVLI(VarList);
10964 SmallVector<Expr *, 8> PrivateCopies;
10965 SmallVector<Expr *, 8> Inits;
10966
Carlo Bertolli2404b172016-07-13 15:37:16 +000010967 for (auto &RefExpr : VarList) {
10968 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10969 SourceLocation ELoc;
10970 SourceRange ERange;
10971 Expr *SimpleRefExpr = RefExpr;
10972 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10973 if (Res.second) {
10974 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010975 MVLI.ProcessedVarList.push_back(RefExpr);
10976 PrivateCopies.push_back(nullptr);
10977 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010978 }
10979 ValueDecl *D = Res.first;
10980 if (!D)
10981 continue;
10982
10983 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010984 Type = Type.getNonReferenceType().getUnqualifiedType();
10985
10986 auto *VD = dyn_cast<VarDecl>(D);
10987
10988 // Item should be a pointer or reference to pointer.
10989 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010990 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10991 << 0 << RefExpr->getSourceRange();
10992 continue;
10993 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010994
10995 // Build the private variable and the expression that refers to it.
10996 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10997 D->hasAttrs() ? &D->getAttrs() : nullptr);
10998 if (VDPrivate->isInvalidDecl())
10999 continue;
11000
11001 CurContext->addDecl(VDPrivate);
11002 auto VDPrivateRefExpr = buildDeclRefExpr(
11003 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11004
11005 // Add temporary variable to initialize the private copy of the pointer.
11006 auto *VDInit =
11007 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11008 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11009 RefExpr->getExprLoc());
11010 AddInitializerToDecl(VDPrivate,
11011 DefaultLvalueConversion(VDInitRefExpr).get(),
11012 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
11013
11014 // If required, build a capture to implement the privatization initialized
11015 // with the current list item value.
11016 DeclRefExpr *Ref = nullptr;
11017 if (!VD)
11018 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11019 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11020 PrivateCopies.push_back(VDPrivateRefExpr);
11021 Inits.push_back(VDInitRefExpr);
11022
11023 // We need to add a data sharing attribute for this variable to make sure it
11024 // is correctly captured. A variable that shows up in a use_device_ptr has
11025 // similar properties of a first private variable.
11026 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11027
11028 // Create a mappable component for the list item. List items in this clause
11029 // only need a component.
11030 MVLI.VarBaseDeclarations.push_back(D);
11031 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11032 MVLI.VarComponents.back().push_back(
11033 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011034 }
11035
Samuel Antaocc10b852016-07-28 14:23:26 +000011036 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011037 return nullptr;
11038
Samuel Antaocc10b852016-07-28 14:23:26 +000011039 return OMPUseDevicePtrClause::Create(
11040 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11041 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011042}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011043
11044OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11045 SourceLocation StartLoc,
11046 SourceLocation LParenLoc,
11047 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011048 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011049 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011050 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011051 SourceLocation ELoc;
11052 SourceRange ERange;
11053 Expr *SimpleRefExpr = RefExpr;
11054 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11055 if (Res.second) {
11056 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011057 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011058 }
11059 ValueDecl *D = Res.first;
11060 if (!D)
11061 continue;
11062
11063 QualType Type = D->getType();
11064 // item should be a pointer or array or reference to pointer or array
11065 if (!Type.getNonReferenceType()->isPointerType() &&
11066 !Type.getNonReferenceType()->isArrayType()) {
11067 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11068 << 0 << RefExpr->getSourceRange();
11069 continue;
11070 }
Samuel Antao6890b092016-07-28 14:25:09 +000011071
11072 // Check if the declaration in the clause does not show up in any data
11073 // sharing attribute.
11074 auto DVar = DSAStack->getTopDSA(D, false);
11075 if (isOpenMPPrivate(DVar.CKind)) {
11076 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11077 << getOpenMPClauseName(DVar.CKind)
11078 << getOpenMPClauseName(OMPC_is_device_ptr)
11079 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11080 ReportOriginalDSA(*this, DSAStack, D, DVar);
11081 continue;
11082 }
11083
11084 Expr *ConflictExpr;
11085 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011086 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011087 [&ConflictExpr](
11088 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11089 OpenMPClauseKind) -> bool {
11090 ConflictExpr = R.front().getAssociatedExpression();
11091 return true;
11092 })) {
11093 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11094 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11095 << ConflictExpr->getSourceRange();
11096 continue;
11097 }
11098
11099 // Store the components in the stack so that they can be used to check
11100 // against other clauses later on.
11101 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11102 DSAStack->addMappableExpressionComponents(
11103 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11104
11105 // Record the expression we've just processed.
11106 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11107
11108 // Create a mappable component for the list item. List items in this clause
11109 // only need a component. We use a null declaration to signal fields in
11110 // 'this'.
11111 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11112 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11113 "Unexpected device pointer expression!");
11114 MVLI.VarBaseDeclarations.push_back(
11115 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11116 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11117 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011118 }
11119
Samuel Antao6890b092016-07-28 14:25:09 +000011120 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011121 return nullptr;
11122
Samuel Antao6890b092016-07-28 14:25:09 +000011123 return OMPIsDevicePtrClause::Create(
11124 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11125 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011126}