blob: 35fdc25867bbd4a513b0aa3071d8debb622b2ff4 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001092 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Kelvin Libf594a52016-12-17 05:48:59 +00001597 case OMPD_teams:
1598 case OMPD_target_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
Arpith Chacko Jacob68019572017-01-18 15:14:52 +00001611 case OMPD_target_parallel: {
1612 Sema::CapturedParamNameType ParamsTarget[] = {
1613 std::make_pair(StringRef(), QualType()) // __context with shared vars
1614 };
1615 // Start a captured region for 'target' with no implicit parameters.
1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1617 ParamsTarget);
1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1619 QualType KmpInt32PtrTy =
1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1621 Sema::CapturedParamNameType ParamsParallel[] = {
1622 std::make_pair(".global_tid.", KmpInt32PtrTy),
1623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1624 std::make_pair(StringRef(), QualType()) // __context with shared vars
1625 };
1626 // Start a captured region for 'parallel'.
1627 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1628 ParamsParallel);
1629 break;
1630 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001631 case OMPD_simd:
1632 case OMPD_for:
1633 case OMPD_for_simd:
1634 case OMPD_sections:
1635 case OMPD_section:
1636 case OMPD_single:
1637 case OMPD_master:
1638 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001639 case OMPD_taskgroup:
1640 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001641 case OMPD_ordered:
1642 case OMPD_atomic:
1643 case OMPD_target_data:
1644 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001645 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001646 case OMPD_target_parallel_for_simd:
1647 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001648 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1650 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001653 break;
1654 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001655 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001656 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001657 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1658 FunctionProtoType::ExtProtoInfo EPI;
1659 EPI.Variadic = true;
1660 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001661 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001662 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001663 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1664 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1665 std::make_pair(".copy_fn.",
1666 Context.getPointerType(CopyFnType).withConst()),
1667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001668 std::make_pair(StringRef(), QualType()) // __context with shared vars
1669 };
1670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1671 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001672 // Mark this captured region as inlined, because we don't use outlined
1673 // function directly.
1674 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1675 AlwaysInlineAttr::CreateImplicit(
1676 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001677 break;
1678 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001679 case OMPD_taskloop:
1680 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001681 QualType KmpInt32Ty =
1682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1683 QualType KmpUInt64Ty =
1684 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1685 QualType KmpInt64Ty =
1686 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1687 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1688 FunctionProtoType::ExtProtoInfo EPI;
1689 EPI.Variadic = true;
1690 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001691 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001692 std::make_pair(".global_tid.", KmpInt32Ty),
1693 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1694 std::make_pair(".privates.",
1695 Context.VoidPtrTy.withConst().withRestrict()),
1696 std::make_pair(
1697 ".copy_fn.",
1698 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1699 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1700 std::make_pair(".lb.", KmpUInt64Ty),
1701 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1702 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001703 std::make_pair(StringRef(), QualType()) // __context with shared vars
1704 };
1705 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1706 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001707 // Mark this captured region as inlined, because we don't use outlined
1708 // function directly.
1709 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1710 AlwaysInlineAttr::CreateImplicit(
1711 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001712 break;
1713 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001714 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001715 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001716 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001717 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001718 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001719 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001720 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001721 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001722 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001723 case OMPD_target_teams_distribute_parallel_for_simd:
1724 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001725 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1726 QualType KmpInt32PtrTy =
1727 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1728 Sema::CapturedParamNameType Params[] = {
1729 std::make_pair(".global_tid.", KmpInt32PtrTy),
1730 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1731 std::make_pair(".previous.lb.", Context.getSizeType()),
1732 std::make_pair(".previous.ub.", Context.getSizeType()),
1733 std::make_pair(StringRef(), QualType()) // __context with shared vars
1734 };
1735 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1736 Params);
1737 break;
1738 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001739 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001740 case OMPD_taskyield:
1741 case OMPD_barrier:
1742 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001743 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001744 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001745 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001746 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001747 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001748 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001749 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001750 case OMPD_declare_target:
1751 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001752 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001753 llvm_unreachable("OpenMP Directive is not allowed");
1754 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001755 llvm_unreachable("Unknown OpenMP directive");
1756 }
1757}
1758
Arpith Chacko Jacob68019572017-01-18 15:14:52 +00001759int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1760 return getOpenMPCaptureRegions(DKind).size();
1761}
1762
Alexey Bataev3392d762016-02-16 11:18:12 +00001763static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001764 Expr *CaptureExpr, bool WithInit,
1765 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001766 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001767 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001768 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001769 QualType Ty = Init->getType();
1770 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1771 if (S.getLangOpts().CPlusPlus)
1772 Ty = C.getLValueReferenceType(Ty);
1773 else {
1774 Ty = C.getPointerType(Ty);
1775 ExprResult Res =
1776 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1777 if (!Res.isUsable())
1778 return nullptr;
1779 Init = Res.get();
1780 }
Alexey Bataev61205072016-03-02 04:57:40 +00001781 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001782 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001783 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1784 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001785 if (!WithInit)
1786 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001787 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001788 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001789 return CED;
1790}
1791
Alexey Bataev61205072016-03-02 04:57:40 +00001792static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1793 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001794 OMPCapturedExprDecl *CD;
1795 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1796 CD = cast<OMPCapturedExprDecl>(VD);
1797 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001798 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1799 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001800 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001801 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001802}
1803
Alexey Bataev5a3af132016-03-29 08:58:54 +00001804static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1805 if (!Ref) {
1806 auto *CD =
1807 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1808 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1809 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1810 CaptureExpr->getExprLoc());
1811 }
1812 ExprResult Res = Ref;
1813 if (!S.getLangOpts().CPlusPlus &&
1814 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1815 Ref->getType()->isPointerType())
1816 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1817 if (!Res.isUsable())
1818 return ExprError();
1819 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001820}
1821
Arpith Chacko Jacob68019572017-01-18 15:14:52 +00001822namespace {
1823// OpenMP directives parsed in this section are represented as a
1824// CapturedStatement with an associated statement. If a syntax error
1825// is detected during the parsing of the associated statement, the
1826// compiler must abort processing and close the CapturedStatement.
1827//
1828// Combined directives such as 'target parallel' have more than one
1829// nested CapturedStatements. This RAII ensures that we unwind out
1830// of all the nested CapturedStatements when an error is found.
1831class CaptureRegionUnwinderRAII {
1832private:
1833 Sema &S;
1834 bool &ErrorFound;
1835 OpenMPDirectiveKind DKind;
1836
1837public:
1838 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1839 OpenMPDirectiveKind DKind)
1840 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1841 ~CaptureRegionUnwinderRAII() {
1842 if (ErrorFound) {
1843 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1844 while (--ThisCaptureLevel >= 0)
1845 S.ActOnCapturedRegionError();
1846 }
1847 }
1848};
1849} // namespace
1850
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001851StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1852 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob68019572017-01-18 15:14:52 +00001853 bool ErrorFound = false;
1854 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1855 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001856 if (!S.isUsable()) {
Arpith Chacko Jacob68019572017-01-18 15:14:52 +00001857 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001858 return StmtError();
1859 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001860
1861 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001862 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001863 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001864 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001865 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001866 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001867 Clause->getClauseKind() == OMPC_copyprivate ||
1868 (getLangOpts().OpenMPUseTLS &&
1869 getASTContext().getTargetInfo().isTLSSupported() &&
1870 Clause->getClauseKind() == OMPC_copyin)) {
1871 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001872 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001873 for (auto *VarRef : Clause->children()) {
1874 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001875 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001876 }
1877 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001878 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001879 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001880 // Mark all variables in private list clauses as used in inner region.
1881 // Required for proper codegen of combined directives.
1882 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001883 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001884 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1885 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001886 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1887 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001888 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001889 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1890 if (auto *E = C->getPostUpdateExpr())
1891 MarkDeclarationsReferencedInExpr(E);
1892 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001893 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001894 if (Clause->getClauseKind() == OMPC_schedule)
1895 SC = cast<OMPScheduleClause>(Clause);
1896 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001897 OC = cast<OMPOrderedClause>(Clause);
1898 else if (Clause->getClauseKind() == OMPC_linear)
1899 LCs.push_back(cast<OMPLinearClause>(Clause));
1900 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001901 // OpenMP, 2.7.1 Loop Construct, Restrictions
1902 // The nonmonotonic modifier cannot be specified if an ordered clause is
1903 // specified.
1904 if (SC &&
1905 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1906 SC->getSecondScheduleModifier() ==
1907 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1908 OC) {
1909 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1910 ? SC->getFirstScheduleModifierLoc()
1911 : SC->getSecondScheduleModifierLoc(),
1912 diag::err_omp_schedule_nonmonotonic_ordered)
1913 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1914 ErrorFound = true;
1915 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001916 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1917 for (auto *C : LCs) {
1918 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1919 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1920 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001921 ErrorFound = true;
1922 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001923 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1924 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1925 OC->getNumForLoops()) {
1926 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1927 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1928 ErrorFound = true;
1929 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001930 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001931 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001932 }
Arpith Chacko Jacob68019572017-01-18 15:14:52 +00001933 StmtResult SR = S;
1934 int ThisCaptureLevel =
1935 getOpenMPCaptureLevels(DSAStack->getCurrentDirective());
1936 while (--ThisCaptureLevel >= 0)
1937 SR = ActOnCapturedRegionEnd(SR.get());
1938 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001939}
1940
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001941static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1942 OpenMPDirectiveKind CurrentRegion,
1943 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001944 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001945 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001946 if (Stack->getCurScope()) {
1947 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001948 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001949 bool NestingProhibited = false;
1950 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001951 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001952 enum {
1953 NoRecommend,
1954 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001955 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001956 ShouldBeInTargetRegion,
1957 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001958 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001959 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001960 // OpenMP [2.16, Nesting of Regions]
1961 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001962 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001963 // An ordered construct with the simd clause is the only OpenMP
1964 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001965 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001966 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1967 // message.
1968 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1969 ? diag::err_omp_prohibited_region_simd
1970 : diag::warn_omp_nesting_simd);
1971 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001972 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001973 if (ParentRegion == OMPD_atomic) {
1974 // OpenMP [2.16, Nesting of Regions]
1975 // OpenMP constructs may not be nested inside an atomic region.
1976 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1977 return true;
1978 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001979 if (CurrentRegion == OMPD_section) {
1980 // OpenMP [2.7.2, sections Construct, Restrictions]
1981 // Orphaned section directives are prohibited. That is, the section
1982 // directives must appear within the sections construct and must not be
1983 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001984 if (ParentRegion != OMPD_sections &&
1985 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001986 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1987 << (ParentRegion != OMPD_unknown)
1988 << getOpenMPDirectiveName(ParentRegion);
1989 return true;
1990 }
1991 return false;
1992 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001993 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001994 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001995 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00001996 if (ParentRegion == OMPD_unknown &&
1997 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001998 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001999 if (CurrentRegion == OMPD_cancellation_point ||
2000 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002001 // OpenMP [2.16, Nesting of Regions]
2002 // A cancellation point construct for which construct-type-clause is
2003 // taskgroup must be nested inside a task construct. A cancellation
2004 // point construct for which construct-type-clause is not taskgroup must
2005 // be closely nested inside an OpenMP construct that matches the type
2006 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002007 // A cancel construct for which construct-type-clause is taskgroup must be
2008 // nested inside a task construct. A cancel construct for which
2009 // construct-type-clause is not taskgroup must be closely nested inside an
2010 // OpenMP construct that matches the type specified in
2011 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002012 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002013 !((CancelRegion == OMPD_parallel &&
2014 (ParentRegion == OMPD_parallel ||
2015 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002016 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002017 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2018 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002019 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2020 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002021 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2022 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002023 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002024 // OpenMP [2.16, Nesting of Regions]
2025 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002026 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002027 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002028 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002029 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2030 // OpenMP [2.16, Nesting of Regions]
2031 // A critical region may not be nested (closely or otherwise) inside a
2032 // critical region with the same name. Note that this restriction is not
2033 // sufficient to prevent deadlock.
2034 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002035 bool DeadLock = Stack->hasDirective(
2036 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2037 const DeclarationNameInfo &DNI,
2038 SourceLocation Loc) -> bool {
2039 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2040 PreviousCriticalLoc = Loc;
2041 return true;
2042 } else
2043 return false;
2044 },
2045 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002046 if (DeadLock) {
2047 SemaRef.Diag(StartLoc,
2048 diag::err_omp_prohibited_region_critical_same_name)
2049 << CurrentName.getName();
2050 if (PreviousCriticalLoc.isValid())
2051 SemaRef.Diag(PreviousCriticalLoc,
2052 diag::note_omp_previous_critical_region);
2053 return true;
2054 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002055 } else if (CurrentRegion == OMPD_barrier) {
2056 // OpenMP [2.16, Nesting of Regions]
2057 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002058 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002059 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2060 isOpenMPTaskingDirective(ParentRegion) ||
2061 ParentRegion == OMPD_master ||
2062 ParentRegion == OMPD_critical ||
2063 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002064 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002065 !isOpenMPParallelDirective(CurrentRegion) &&
2066 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002067 // OpenMP [2.16, Nesting of Regions]
2068 // A worksharing region may not be closely nested inside a worksharing,
2069 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002070 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2071 isOpenMPTaskingDirective(ParentRegion) ||
2072 ParentRegion == OMPD_master ||
2073 ParentRegion == OMPD_critical ||
2074 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002075 Recommend = ShouldBeInParallelRegion;
2076 } else if (CurrentRegion == OMPD_ordered) {
2077 // OpenMP [2.16, Nesting of Regions]
2078 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002079 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002080 // An ordered region must be closely nested inside a loop region (or
2081 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002082 // OpenMP [2.8.1,simd Construct, Restrictions]
2083 // An ordered construct with the simd clause is the only OpenMP construct
2084 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002085 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002086 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002087 !(isOpenMPSimdDirective(ParentRegion) ||
2088 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002089 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002090 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002091 // OpenMP [2.16, Nesting of Regions]
2092 // If specified, a teams construct must be contained within a target
2093 // construct.
2094 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002095 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002096 Recommend = ShouldBeInTargetRegion;
2097 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2098 }
Kelvin Libf594a52016-12-17 05:48:59 +00002099 if (!NestingProhibited &&
2100 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2101 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2102 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002103 // OpenMP [2.16, Nesting of Regions]
2104 // distribute, parallel, parallel sections, parallel workshare, and the
2105 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2106 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002107 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2108 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002109 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002110 }
David Majnemer9d168222016-08-05 17:44:54 +00002111 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002112 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002113 // OpenMP 4.5 [2.17 Nesting of Regions]
2114 // The region associated with the distribute construct must be strictly
2115 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002116 NestingProhibited =
2117 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002118 Recommend = ShouldBeInTeamsRegion;
2119 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002120 if (!NestingProhibited &&
2121 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2122 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2123 // OpenMP 4.5 [2.17 Nesting of Regions]
2124 // If a target, target update, target data, target enter data, or
2125 // target exit data construct is encountered during execution of a
2126 // target region, the behavior is unspecified.
2127 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002128 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2129 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002130 if (isOpenMPTargetExecutionDirective(K)) {
2131 OffendingRegion = K;
2132 return true;
2133 } else
2134 return false;
2135 },
2136 false /* don't skip top directive */);
2137 CloseNesting = false;
2138 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002139 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002140 if (OrphanSeen) {
2141 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2142 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2143 } else {
2144 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2145 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2146 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2147 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002148 return true;
2149 }
2150 }
2151 return false;
2152}
2153
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002154static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2155 ArrayRef<OMPClause *> Clauses,
2156 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2157 bool ErrorFound = false;
2158 unsigned NamedModifiersNumber = 0;
2159 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2160 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002161 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002162 for (const auto *C : Clauses) {
2163 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2164 // At most one if clause without a directive-name-modifier can appear on
2165 // the directive.
2166 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2167 if (FoundNameModifiers[CurNM]) {
2168 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2169 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2170 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2171 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002172 } else if (CurNM != OMPD_unknown) {
2173 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002174 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002175 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002176 FoundNameModifiers[CurNM] = IC;
2177 if (CurNM == OMPD_unknown)
2178 continue;
2179 // Check if the specified name modifier is allowed for the current
2180 // directive.
2181 // At most one if clause with the particular directive-name-modifier can
2182 // appear on the directive.
2183 bool MatchFound = false;
2184 for (auto NM : AllowedNameModifiers) {
2185 if (CurNM == NM) {
2186 MatchFound = true;
2187 break;
2188 }
2189 }
2190 if (!MatchFound) {
2191 S.Diag(IC->getNameModifierLoc(),
2192 diag::err_omp_wrong_if_directive_name_modifier)
2193 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2194 ErrorFound = true;
2195 }
2196 }
2197 }
2198 // If any if clause on the directive includes a directive-name-modifier then
2199 // all if clauses on the directive must include a directive-name-modifier.
2200 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2201 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2202 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2203 diag::err_omp_no_more_if_clause);
2204 } else {
2205 std::string Values;
2206 std::string Sep(", ");
2207 unsigned AllowedCnt = 0;
2208 unsigned TotalAllowedNum =
2209 AllowedNameModifiers.size() - NamedModifiersNumber;
2210 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2211 ++Cnt) {
2212 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2213 if (!FoundNameModifiers[NM]) {
2214 Values += "'";
2215 Values += getOpenMPDirectiveName(NM);
2216 Values += "'";
2217 if (AllowedCnt + 2 == TotalAllowedNum)
2218 Values += " or ";
2219 else if (AllowedCnt + 1 != TotalAllowedNum)
2220 Values += Sep;
2221 ++AllowedCnt;
2222 }
2223 }
2224 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2225 diag::err_omp_unnamed_if_clause)
2226 << (TotalAllowedNum > 1) << Values;
2227 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002228 for (auto Loc : NameModifierLoc) {
2229 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2230 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002231 ErrorFound = true;
2232 }
2233 return ErrorFound;
2234}
2235
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002236StmtResult Sema::ActOnOpenMPExecutableDirective(
2237 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2238 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2239 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002240 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002241 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2242 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002243 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002244
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002245 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002246 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002247 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002248 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002249 if (AStmt) {
2250 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2251
2252 // Check default data sharing attributes for referenced variables.
2253 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2254 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2255 if (DSAChecker.isErrorFound())
2256 return StmtError();
2257 // Generate list of implicitly defined firstprivate variables.
2258 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002259
2260 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2261 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2262 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2263 SourceLocation(), SourceLocation())) {
2264 ClausesWithImplicit.push_back(Implicit);
2265 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2266 DSAChecker.getImplicitFirstprivate().size();
2267 } else
2268 ErrorFound = true;
2269 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002270 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002271
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002272 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002273 switch (Kind) {
2274 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002275 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2276 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002277 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002278 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002279 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002280 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2281 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002282 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002283 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002284 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2285 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002286 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002287 case OMPD_for_simd:
2288 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2289 EndLoc, VarsWithInheritedDSA);
2290 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002291 case OMPD_sections:
2292 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2293 EndLoc);
2294 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002295 case OMPD_section:
2296 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002297 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002298 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2299 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002300 case OMPD_single:
2301 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2302 EndLoc);
2303 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002304 case OMPD_master:
2305 assert(ClausesWithImplicit.empty() &&
2306 "No clauses are allowed for 'omp master' directive");
2307 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2308 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002309 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002310 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2311 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002312 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002313 case OMPD_parallel_for:
2314 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2315 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002316 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002317 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002318 case OMPD_parallel_for_simd:
2319 Res = ActOnOpenMPParallelForSimdDirective(
2320 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002321 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002322 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002323 case OMPD_parallel_sections:
2324 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2325 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002326 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002327 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002328 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002329 Res =
2330 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002331 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002332 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002333 case OMPD_taskyield:
2334 assert(ClausesWithImplicit.empty() &&
2335 "No clauses are allowed for 'omp taskyield' directive");
2336 assert(AStmt == nullptr &&
2337 "No associated statement allowed for 'omp taskyield' directive");
2338 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2339 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002340 case OMPD_barrier:
2341 assert(ClausesWithImplicit.empty() &&
2342 "No clauses are allowed for 'omp barrier' directive");
2343 assert(AStmt == nullptr &&
2344 "No associated statement allowed for 'omp barrier' directive");
2345 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2346 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002347 case OMPD_taskwait:
2348 assert(ClausesWithImplicit.empty() &&
2349 "No clauses are allowed for 'omp taskwait' directive");
2350 assert(AStmt == nullptr &&
2351 "No associated statement allowed for 'omp taskwait' directive");
2352 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2353 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002354 case OMPD_taskgroup:
2355 assert(ClausesWithImplicit.empty() &&
2356 "No clauses are allowed for 'omp taskgroup' directive");
2357 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2358 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002359 case OMPD_flush:
2360 assert(AStmt == nullptr &&
2361 "No associated statement allowed for 'omp flush' directive");
2362 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2363 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002364 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002365 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2366 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002367 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002368 case OMPD_atomic:
2369 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2370 EndLoc);
2371 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002372 case OMPD_teams:
2373 Res =
2374 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2375 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002376 case OMPD_target:
2377 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2378 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002379 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002380 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002381 case OMPD_target_parallel:
2382 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2383 StartLoc, EndLoc);
2384 AllowedNameModifiers.push_back(OMPD_target);
2385 AllowedNameModifiers.push_back(OMPD_parallel);
2386 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002387 case OMPD_target_parallel_for:
2388 Res = ActOnOpenMPTargetParallelForDirective(
2389 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2390 AllowedNameModifiers.push_back(OMPD_target);
2391 AllowedNameModifiers.push_back(OMPD_parallel);
2392 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002393 case OMPD_cancellation_point:
2394 assert(ClausesWithImplicit.empty() &&
2395 "No clauses are allowed for 'omp cancellation point' directive");
2396 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2397 "cancellation point' directive");
2398 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2399 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002400 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002401 assert(AStmt == nullptr &&
2402 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002403 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2404 CancelRegion);
2405 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002406 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002407 case OMPD_target_data:
2408 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2409 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002410 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002411 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002412 case OMPD_target_enter_data:
2413 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2414 EndLoc);
2415 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2416 break;
Samuel Antao72590762016-01-19 20:04:50 +00002417 case OMPD_target_exit_data:
2418 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2419 EndLoc);
2420 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2421 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002422 case OMPD_taskloop:
2423 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2424 EndLoc, VarsWithInheritedDSA);
2425 AllowedNameModifiers.push_back(OMPD_taskloop);
2426 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002427 case OMPD_taskloop_simd:
2428 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2429 EndLoc, VarsWithInheritedDSA);
2430 AllowedNameModifiers.push_back(OMPD_taskloop);
2431 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002432 case OMPD_distribute:
2433 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2434 EndLoc, VarsWithInheritedDSA);
2435 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002436 case OMPD_target_update:
2437 assert(!AStmt && "Statement is not allowed for target update");
2438 Res =
2439 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2440 AllowedNameModifiers.push_back(OMPD_target_update);
2441 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002442 case OMPD_distribute_parallel_for:
2443 Res = ActOnOpenMPDistributeParallelForDirective(
2444 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2445 AllowedNameModifiers.push_back(OMPD_parallel);
2446 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002447 case OMPD_distribute_parallel_for_simd:
2448 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2449 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2450 AllowedNameModifiers.push_back(OMPD_parallel);
2451 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002452 case OMPD_distribute_simd:
2453 Res = ActOnOpenMPDistributeSimdDirective(
2454 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2455 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002456 case OMPD_target_parallel_for_simd:
2457 Res = ActOnOpenMPTargetParallelForSimdDirective(
2458 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2459 AllowedNameModifiers.push_back(OMPD_target);
2460 AllowedNameModifiers.push_back(OMPD_parallel);
2461 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002462 case OMPD_target_simd:
2463 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2464 EndLoc, VarsWithInheritedDSA);
2465 AllowedNameModifiers.push_back(OMPD_target);
2466 break;
Kelvin Li02532872016-08-05 14:37:37 +00002467 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002468 Res = ActOnOpenMPTeamsDistributeDirective(
2469 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002470 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002471 case OMPD_teams_distribute_simd:
2472 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2473 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2474 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002475 case OMPD_teams_distribute_parallel_for_simd:
2476 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2477 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2478 AllowedNameModifiers.push_back(OMPD_parallel);
2479 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002480 case OMPD_teams_distribute_parallel_for:
2481 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2482 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2483 AllowedNameModifiers.push_back(OMPD_parallel);
2484 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002485 case OMPD_target_teams:
2486 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2487 EndLoc);
2488 AllowedNameModifiers.push_back(OMPD_target);
2489 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002490 case OMPD_target_teams_distribute:
2491 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2492 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2493 AllowedNameModifiers.push_back(OMPD_target);
2494 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002495 case OMPD_target_teams_distribute_parallel_for:
2496 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2497 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2498 AllowedNameModifiers.push_back(OMPD_target);
2499 AllowedNameModifiers.push_back(OMPD_parallel);
2500 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002501 case OMPD_target_teams_distribute_parallel_for_simd:
2502 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2503 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2504 AllowedNameModifiers.push_back(OMPD_target);
2505 AllowedNameModifiers.push_back(OMPD_parallel);
2506 break;
Kelvin Lida681182017-01-10 18:08:18 +00002507 case OMPD_target_teams_distribute_simd:
2508 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2509 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2510 AllowedNameModifiers.push_back(OMPD_target);
2511 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002512 case OMPD_declare_target:
2513 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002514 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002515 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002516 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002517 llvm_unreachable("OpenMP Directive is not allowed");
2518 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002519 llvm_unreachable("Unknown OpenMP directive");
2520 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002521
Alexey Bataev4acb8592014-07-07 13:01:15 +00002522 for (auto P : VarsWithInheritedDSA) {
2523 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2524 << P.first << P.second->getSourceRange();
2525 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002526 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2527
2528 if (!AllowedNameModifiers.empty())
2529 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2530 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002531
Alexey Bataeved09d242014-05-28 05:53:51 +00002532 if (ErrorFound)
2533 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002534 return Res;
2535}
2536
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002537Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2538 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002539 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002540 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2541 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002542 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002543 assert(Linears.size() == LinModifiers.size());
2544 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002545 if (!DG || DG.get().isNull())
2546 return DeclGroupPtrTy();
2547
2548 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002549 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002550 return DG;
2551 }
2552 auto *ADecl = DG.get().getSingleDecl();
2553 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2554 ADecl = FTD->getTemplatedDecl();
2555
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002556 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2557 if (!FD) {
2558 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002559 return DeclGroupPtrTy();
2560 }
2561
Alexey Bataev2af33e32016-04-07 12:45:37 +00002562 // OpenMP [2.8.2, declare simd construct, Description]
2563 // The parameter of the simdlen clause must be a constant positive integer
2564 // expression.
2565 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002566 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002567 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002568 // OpenMP [2.8.2, declare simd construct, Description]
2569 // The special this pointer can be used as if was one of the arguments to the
2570 // function in any of the linear, aligned, or uniform clauses.
2571 // The uniform clause declares one or more arguments to have an invariant
2572 // value for all concurrent invocations of the function in the execution of a
2573 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002574 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2575 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002576 for (auto *E : Uniforms) {
2577 E = E->IgnoreParenImpCasts();
2578 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2579 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2580 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2581 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002582 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2583 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002584 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002585 }
2586 if (isa<CXXThisExpr>(E)) {
2587 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002588 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002589 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002590 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2591 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002592 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002593 // OpenMP [2.8.2, declare simd construct, Description]
2594 // The aligned clause declares that the object to which each list item points
2595 // is aligned to the number of bytes expressed in the optional parameter of
2596 // the aligned clause.
2597 // The special this pointer can be used as if was one of the arguments to the
2598 // function in any of the linear, aligned, or uniform clauses.
2599 // The type of list items appearing in the aligned clause must be array,
2600 // pointer, reference to array, or reference to pointer.
2601 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2602 Expr *AlignedThis = nullptr;
2603 for (auto *E : Aligneds) {
2604 E = E->IgnoreParenImpCasts();
2605 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2606 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2607 auto *CanonPVD = PVD->getCanonicalDecl();
2608 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2609 FD->getParamDecl(PVD->getFunctionScopeIndex())
2610 ->getCanonicalDecl() == CanonPVD) {
2611 // OpenMP [2.8.1, simd construct, Restrictions]
2612 // A list-item cannot appear in more than one aligned clause.
2613 if (AlignedArgs.count(CanonPVD) > 0) {
2614 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2615 << 1 << E->getSourceRange();
2616 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2617 diag::note_omp_explicit_dsa)
2618 << getOpenMPClauseName(OMPC_aligned);
2619 continue;
2620 }
2621 AlignedArgs[CanonPVD] = E;
2622 QualType QTy = PVD->getType()
2623 .getNonReferenceType()
2624 .getUnqualifiedType()
2625 .getCanonicalType();
2626 const Type *Ty = QTy.getTypePtrOrNull();
2627 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2628 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2629 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2630 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2631 }
2632 continue;
2633 }
2634 }
2635 if (isa<CXXThisExpr>(E)) {
2636 if (AlignedThis) {
2637 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2638 << 2 << E->getSourceRange();
2639 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2640 << getOpenMPClauseName(OMPC_aligned);
2641 }
2642 AlignedThis = E;
2643 continue;
2644 }
2645 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2646 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2647 }
2648 // The optional parameter of the aligned clause, alignment, must be a constant
2649 // positive integer expression. If no optional parameter is specified,
2650 // implementation-defined default alignments for SIMD instructions on the
2651 // target platforms are assumed.
2652 SmallVector<Expr *, 4> NewAligns;
2653 for (auto *E : Alignments) {
2654 ExprResult Align;
2655 if (E)
2656 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2657 NewAligns.push_back(Align.get());
2658 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002659 // OpenMP [2.8.2, declare simd construct, Description]
2660 // The linear clause declares one or more list items to be private to a SIMD
2661 // lane and to have a linear relationship with respect to the iteration space
2662 // of a loop.
2663 // The special this pointer can be used as if was one of the arguments to the
2664 // function in any of the linear, aligned, or uniform clauses.
2665 // When a linear-step expression is specified in a linear clause it must be
2666 // either a constant integer expression or an integer-typed parameter that is
2667 // specified in a uniform clause on the directive.
2668 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2669 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2670 auto MI = LinModifiers.begin();
2671 for (auto *E : Linears) {
2672 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2673 ++MI;
2674 E = E->IgnoreParenImpCasts();
2675 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2676 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2677 auto *CanonPVD = PVD->getCanonicalDecl();
2678 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2679 FD->getParamDecl(PVD->getFunctionScopeIndex())
2680 ->getCanonicalDecl() == CanonPVD) {
2681 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2682 // A list-item cannot appear in more than one linear clause.
2683 if (LinearArgs.count(CanonPVD) > 0) {
2684 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2685 << getOpenMPClauseName(OMPC_linear)
2686 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2687 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2688 diag::note_omp_explicit_dsa)
2689 << getOpenMPClauseName(OMPC_linear);
2690 continue;
2691 }
2692 // Each argument can appear in at most one uniform or linear clause.
2693 if (UniformedArgs.count(CanonPVD) > 0) {
2694 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2695 << getOpenMPClauseName(OMPC_linear)
2696 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2697 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2698 diag::note_omp_explicit_dsa)
2699 << getOpenMPClauseName(OMPC_uniform);
2700 continue;
2701 }
2702 LinearArgs[CanonPVD] = E;
2703 if (E->isValueDependent() || E->isTypeDependent() ||
2704 E->isInstantiationDependent() ||
2705 E->containsUnexpandedParameterPack())
2706 continue;
2707 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2708 PVD->getOriginalType());
2709 continue;
2710 }
2711 }
2712 if (isa<CXXThisExpr>(E)) {
2713 if (UniformedLinearThis) {
2714 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2715 << getOpenMPClauseName(OMPC_linear)
2716 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2717 << E->getSourceRange();
2718 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2719 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2720 : OMPC_linear);
2721 continue;
2722 }
2723 UniformedLinearThis = E;
2724 if (E->isValueDependent() || E->isTypeDependent() ||
2725 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2726 continue;
2727 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2728 E->getType());
2729 continue;
2730 }
2731 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2732 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2733 }
2734 Expr *Step = nullptr;
2735 Expr *NewStep = nullptr;
2736 SmallVector<Expr *, 4> NewSteps;
2737 for (auto *E : Steps) {
2738 // Skip the same step expression, it was checked already.
2739 if (Step == E || !E) {
2740 NewSteps.push_back(E ? NewStep : nullptr);
2741 continue;
2742 }
2743 Step = E;
2744 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2745 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2746 auto *CanonPVD = PVD->getCanonicalDecl();
2747 if (UniformedArgs.count(CanonPVD) == 0) {
2748 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2749 << Step->getSourceRange();
2750 } else if (E->isValueDependent() || E->isTypeDependent() ||
2751 E->isInstantiationDependent() ||
2752 E->containsUnexpandedParameterPack() ||
2753 CanonPVD->getType()->hasIntegerRepresentation())
2754 NewSteps.push_back(Step);
2755 else {
2756 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2757 << Step->getSourceRange();
2758 }
2759 continue;
2760 }
2761 NewStep = Step;
2762 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2763 !Step->isInstantiationDependent() &&
2764 !Step->containsUnexpandedParameterPack()) {
2765 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2766 .get();
2767 if (NewStep)
2768 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2769 }
2770 NewSteps.push_back(NewStep);
2771 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002772 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2773 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002774 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002775 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2776 const_cast<Expr **>(Linears.data()), Linears.size(),
2777 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2778 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002779 ADecl->addAttr(NewAttr);
2780 return ConvertDeclToDeclGroup(ADecl);
2781}
2782
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002783StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2784 Stmt *AStmt,
2785 SourceLocation StartLoc,
2786 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002787 if (!AStmt)
2788 return StmtError();
2789
Alexey Bataev9959db52014-05-06 10:08:46 +00002790 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2791 // 1.2.2 OpenMP Language Terminology
2792 // Structured block - An executable statement with a single entry at the
2793 // top and a single exit at the bottom.
2794 // The point of exit cannot be a branch out of the structured block.
2795 // longjmp() and throw() must not violate the entry/exit criteria.
2796 CS->getCapturedDecl()->setNothrow();
2797
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002798 getCurFunction()->setHasBranchProtectedScope();
2799
Alexey Bataev25e5b442015-09-15 12:52:43 +00002800 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2801 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002802}
2803
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002804namespace {
2805/// \brief Helper class for checking canonical form of the OpenMP loops and
2806/// extracting iteration space of each loop in the loop nest, that will be used
2807/// for IR generation.
2808class OpenMPIterationSpaceChecker {
2809 /// \brief Reference to Sema.
2810 Sema &SemaRef;
2811 /// \brief A location for diagnostics (when there is no some better location).
2812 SourceLocation DefaultLoc;
2813 /// \brief A location for diagnostics (when increment is not compatible).
2814 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002815 /// \brief A source location for referring to loop init later.
2816 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002817 /// \brief A source location for referring to condition later.
2818 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002819 /// \brief A source location for referring to increment later.
2820 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002821 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002822 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002823 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002824 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002825 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002826 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002827 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002828 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002829 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002830 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002831 /// \brief This flag is true when condition is one of:
2832 /// Var < UB
2833 /// Var <= UB
2834 /// UB > Var
2835 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002836 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002837 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002838 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002839 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002840 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002841
2842public:
2843 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002844 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002845 /// \brief Check init-expr for canonical loop form and save loop counter
2846 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002847 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002848 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2849 /// for less/greater and for strict/non-strict comparison.
2850 bool CheckCond(Expr *S);
2851 /// \brief Check incr-expr for canonical loop form and return true if it
2852 /// does not conform, otherwise save loop step (#Step).
2853 bool CheckInc(Expr *S);
2854 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002855 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002856 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002857 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002858 /// \brief Source range of the loop init.
2859 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2860 /// \brief Source range of the loop condition.
2861 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2862 /// \brief Source range of the loop increment.
2863 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2864 /// \brief True if the step should be subtracted.
2865 bool ShouldSubtractStep() const { return SubtractStep; }
2866 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002867 Expr *
2868 BuildNumIterations(Scope *S, const bool LimitedType,
2869 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002870 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002871 Expr *BuildPreCond(Scope *S, Expr *Cond,
2872 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002873 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002874 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2875 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002876 /// \brief Build reference expression to the private counter be used for
2877 /// codegen.
2878 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002879 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002880 Expr *BuildCounterInit() const;
2881 /// \brief Build step of the counter be used for codegen.
2882 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002883 /// \brief Return true if any expression is dependent.
2884 bool Dependent() const;
2885
2886private:
2887 /// \brief Check the right-hand side of an assignment in the increment
2888 /// expression.
2889 bool CheckIncRHS(Expr *RHS);
2890 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002891 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002892 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002893 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002894 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002895 /// \brief Helper to set loop increment.
2896 bool SetStep(Expr *NewStep, bool Subtract);
2897};
2898
2899bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002900 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002901 assert(!LB && !UB && !Step);
2902 return false;
2903 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002904 return LCDecl->getType()->isDependentType() ||
2905 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2906 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002907}
2908
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002909static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002910 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2911 E = ExprTemp->getSubExpr();
2912
2913 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2914 E = MTE->GetTemporaryExpr();
2915
2916 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2917 E = Binder->getSubExpr();
2918
2919 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2920 E = ICE->getSubExprAsWritten();
2921 return E->IgnoreParens();
2922}
2923
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002924bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2925 Expr *NewLCRefExpr,
2926 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002927 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002928 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002929 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002930 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002931 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002932 LCDecl = getCanonicalDecl(NewLCDecl);
2933 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002934 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2935 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002936 if ((Ctor->isCopyOrMoveConstructor() ||
2937 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2938 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002939 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002940 LB = NewLB;
2941 return false;
2942}
2943
2944bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002945 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002946 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002947 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2948 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002949 if (!NewUB)
2950 return true;
2951 UB = NewUB;
2952 TestIsLessOp = LessOp;
2953 TestIsStrictOp = StrictOp;
2954 ConditionSrcRange = SR;
2955 ConditionLoc = SL;
2956 return false;
2957}
2958
2959bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2960 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002961 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962 if (!NewStep)
2963 return true;
2964 if (!NewStep->isValueDependent()) {
2965 // Check that the step is integer expression.
2966 SourceLocation StepLoc = NewStep->getLocStart();
2967 ExprResult Val =
2968 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2969 if (Val.isInvalid())
2970 return true;
2971 NewStep = Val.get();
2972
2973 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2974 // If test-expr is of form var relational-op b and relational-op is < or
2975 // <= then incr-expr must cause var to increase on each iteration of the
2976 // loop. If test-expr is of form var relational-op b and relational-op is
2977 // > or >= then incr-expr must cause var to decrease on each iteration of
2978 // the loop.
2979 // If test-expr is of form b relational-op var and relational-op is < or
2980 // <= then incr-expr must cause var to decrease on each iteration of the
2981 // loop. If test-expr is of form b relational-op var and relational-op is
2982 // > or >= then incr-expr must cause var to increase on each iteration of
2983 // the loop.
2984 llvm::APSInt Result;
2985 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2986 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2987 bool IsConstNeg =
2988 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002989 bool IsConstPos =
2990 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002991 bool IsConstZero = IsConstant && !Result.getBoolValue();
2992 if (UB && (IsConstZero ||
2993 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002994 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002995 SemaRef.Diag(NewStep->getExprLoc(),
2996 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002997 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002998 SemaRef.Diag(ConditionLoc,
2999 diag::note_omp_loop_cond_requres_compatible_incr)
3000 << TestIsLessOp << ConditionSrcRange;
3001 return true;
3002 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003003 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003004 NewStep =
3005 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3006 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003007 Subtract = !Subtract;
3008 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003009 }
3010
3011 Step = NewStep;
3012 SubtractStep = Subtract;
3013 return false;
3014}
3015
Alexey Bataev9c821032015-04-30 04:23:23 +00003016bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003017 // Check init-expr for canonical loop form and save loop counter
3018 // variable - #Var and its initialization value - #LB.
3019 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3020 // var = lb
3021 // integer-type var = lb
3022 // random-access-iterator-type var = lb
3023 // pointer-type var = lb
3024 //
3025 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003026 if (EmitDiags) {
3027 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3028 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003029 return true;
3030 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003031 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3032 if (!ExprTemp->cleanupsHaveSideEffects())
3033 S = ExprTemp->getSubExpr();
3034
Alexander Musmana5f070a2014-10-01 06:03:56 +00003035 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003036 if (Expr *E = dyn_cast<Expr>(S))
3037 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003038 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003039 if (BO->getOpcode() == BO_Assign) {
3040 auto *LHS = BO->getLHS()->IgnoreParens();
3041 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3042 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3043 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3044 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3045 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3046 }
3047 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3048 if (ME->isArrow() &&
3049 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3050 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3051 }
3052 }
David Majnemer9d168222016-08-05 17:44:54 +00003053 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003054 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003055 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003056 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003057 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003058 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003059 SemaRef.Diag(S->getLocStart(),
3060 diag::ext_omp_loop_not_canonical_init)
3061 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003062 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003063 }
3064 }
3065 }
David Majnemer9d168222016-08-05 17:44:54 +00003066 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003067 if (CE->getOperator() == OO_Equal) {
3068 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003069 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003070 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3071 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3072 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3073 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3074 }
3075 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3076 if (ME->isArrow() &&
3077 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3078 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3079 }
3080 }
3081 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003082
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003083 if (Dependent() || SemaRef.CurContext->isDependentContext())
3084 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003085 if (EmitDiags) {
3086 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3087 << S->getSourceRange();
3088 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003089 return true;
3090}
3091
Alexey Bataev23b69422014-06-18 07:08:49 +00003092/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003093/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003094static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003095 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003096 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003097 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003098 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3099 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003100 if ((Ctor->isCopyOrMoveConstructor() ||
3101 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3102 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003103 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003104 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3105 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3106 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3107 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3108 return getCanonicalDecl(ME->getMemberDecl());
3109 return getCanonicalDecl(VD);
3110 }
3111 }
3112 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3113 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3114 return getCanonicalDecl(ME->getMemberDecl());
3115 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003116}
3117
3118bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3119 // Check test-expr for canonical form, save upper-bound UB, flags for
3120 // less/greater and for strict/non-strict comparison.
3121 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3122 // var relational-op b
3123 // b relational-op var
3124 //
3125 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003126 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003127 return true;
3128 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003129 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003130 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003131 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003132 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003133 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003134 return SetUB(BO->getRHS(),
3135 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3136 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3137 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003138 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003139 return SetUB(BO->getLHS(),
3140 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3141 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3142 BO->getSourceRange(), BO->getOperatorLoc());
3143 }
David Majnemer9d168222016-08-05 17:44:54 +00003144 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003145 if (CE->getNumArgs() == 2) {
3146 auto Op = CE->getOperator();
3147 switch (Op) {
3148 case OO_Greater:
3149 case OO_GreaterEqual:
3150 case OO_Less:
3151 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003152 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003153 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3154 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3155 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003156 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003157 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3158 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3159 CE->getOperatorLoc());
3160 break;
3161 default:
3162 break;
3163 }
3164 }
3165 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003166 if (Dependent() || SemaRef.CurContext->isDependentContext())
3167 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003169 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003170 return true;
3171}
3172
3173bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3174 // RHS of canonical loop form increment can be:
3175 // var + incr
3176 // incr + var
3177 // var - incr
3178 //
3179 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003180 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003181 if (BO->isAdditiveOp()) {
3182 bool IsAdd = BO->getOpcode() == BO_Add;
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(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003185 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 return SetStep(BO->getLHS(), false);
3187 }
David Majnemer9d168222016-08-05 17:44:54 +00003188 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003189 bool IsAdd = CE->getOperator() == OO_Plus;
3190 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003191 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003192 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003193 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003194 return SetStep(CE->getArg(0), false);
3195 }
3196 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003197 if (Dependent() || SemaRef.CurContext->isDependentContext())
3198 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003199 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003200 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003201 return true;
3202}
3203
3204bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3205 // Check incr-expr for canonical loop form and return true if it
3206 // does not conform.
3207 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3208 // ++var
3209 // var++
3210 // --var
3211 // var--
3212 // var += incr
3213 // var -= incr
3214 // var = var + incr
3215 // var = incr + var
3216 // var = var - incr
3217 //
3218 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003219 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003220 return true;
3221 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003222 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3223 if (!ExprTemp->cleanupsHaveSideEffects())
3224 S = ExprTemp->getSubExpr();
3225
Alexander Musmana5f070a2014-10-01 06:03:56 +00003226 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003227 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003228 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003229 if (UO->isIncrementDecrementOp() &&
3230 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003231 return SetStep(SemaRef
3232 .ActOnIntegerConstant(UO->getLocStart(),
3233 (UO->isDecrementOp() ? -1 : 1))
3234 .get(),
3235 false);
3236 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003237 switch (BO->getOpcode()) {
3238 case BO_AddAssign:
3239 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003240 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003241 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3242 break;
3243 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003244 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003245 return CheckIncRHS(BO->getRHS());
3246 break;
3247 default:
3248 break;
3249 }
David Majnemer9d168222016-08-05 17:44:54 +00003250 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003251 switch (CE->getOperator()) {
3252 case OO_PlusPlus:
3253 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003254 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003255 return SetStep(SemaRef
3256 .ActOnIntegerConstant(
3257 CE->getLocStart(),
3258 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3259 .get(),
3260 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003261 break;
3262 case OO_PlusEqual:
3263 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003264 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003265 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3266 break;
3267 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003268 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003269 return CheckIncRHS(CE->getArg(1));
3270 break;
3271 default:
3272 break;
3273 }
3274 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003275 if (Dependent() || SemaRef.CurContext->isDependentContext())
3276 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003277 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003278 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003279 return true;
3280}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003281
Alexey Bataev5a3af132016-03-29 08:58:54 +00003282static ExprResult
3283tryBuildCapture(Sema &SemaRef, Expr *Capture,
3284 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003285 if (SemaRef.CurContext->isDependentContext())
3286 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003287 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3288 return SemaRef.PerformImplicitConversion(
3289 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3290 /*AllowExplicit=*/true);
3291 auto I = Captures.find(Capture);
3292 if (I != Captures.end())
3293 return buildCapture(SemaRef, Capture, I->second);
3294 DeclRefExpr *Ref = nullptr;
3295 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3296 Captures[Capture] = Ref;
3297 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003298}
3299
Alexander Musmana5f070a2014-10-01 06:03:56 +00003300/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003301Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3302 Scope *S, const bool LimitedType,
3303 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003304 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003305 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003306 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003307 SemaRef.getLangOpts().CPlusPlus) {
3308 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003309 auto *UBExpr = TestIsLessOp ? UB : LB;
3310 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003311 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3312 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003313 if (!Upper || !Lower)
3314 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003315
3316 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3317
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003318 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003319 // BuildBinOp already emitted error, this one is to point user to upper
3320 // and lower bound, and to tell what is passed to 'operator-'.
3321 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3322 << Upper->getSourceRange() << Lower->getSourceRange();
3323 return nullptr;
3324 }
3325 }
3326
3327 if (!Diff.isUsable())
3328 return nullptr;
3329
3330 // Upper - Lower [- 1]
3331 if (TestIsStrictOp)
3332 Diff = SemaRef.BuildBinOp(
3333 S, DefaultLoc, BO_Sub, Diff.get(),
3334 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3335 if (!Diff.isUsable())
3336 return nullptr;
3337
3338 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003339 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3340 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003341 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003342 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003343 if (!Diff.isUsable())
3344 return nullptr;
3345
3346 // Parentheses (for dumping/debugging purposes only).
3347 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3348 if (!Diff.isUsable())
3349 return nullptr;
3350
3351 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003352 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003353 if (!Diff.isUsable())
3354 return nullptr;
3355
Alexander Musman174b3ca2014-10-06 11:16:29 +00003356 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003357 QualType Type = Diff.get()->getType();
3358 auto &C = SemaRef.Context;
3359 bool UseVarType = VarType->hasIntegerRepresentation() &&
3360 C.getTypeSize(Type) > C.getTypeSize(VarType);
3361 if (!Type->isIntegerType() || UseVarType) {
3362 unsigned NewSize =
3363 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3364 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3365 : Type->hasSignedIntegerRepresentation();
3366 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003367 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3368 Diff = SemaRef.PerformImplicitConversion(
3369 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3370 if (!Diff.isUsable())
3371 return nullptr;
3372 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003373 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003374 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003375 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3376 if (NewSize != C.getTypeSize(Type)) {
3377 if (NewSize < C.getTypeSize(Type)) {
3378 assert(NewSize == 64 && "incorrect loop var size");
3379 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3380 << InitSrcRange << ConditionSrcRange;
3381 }
3382 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003383 NewSize, Type->hasSignedIntegerRepresentation() ||
3384 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003385 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3386 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3387 Sema::AA_Converting, true);
3388 if (!Diff.isUsable())
3389 return nullptr;
3390 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003391 }
3392 }
3393
Alexander Musmana5f070a2014-10-01 06:03:56 +00003394 return Diff.get();
3395}
3396
Alexey Bataev5a3af132016-03-29 08:58:54 +00003397Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3398 Scope *S, Expr *Cond,
3399 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003400 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3401 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3402 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003403
Alexey Bataev5a3af132016-03-29 08:58:54 +00003404 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3405 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3406 if (!NewLB.isUsable() || !NewUB.isUsable())
3407 return nullptr;
3408
Alexey Bataev62dbb972015-04-22 11:59:37 +00003409 auto CondExpr = SemaRef.BuildBinOp(
3410 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3411 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003412 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003413 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003414 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3415 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003416 CondExpr = SemaRef.PerformImplicitConversion(
3417 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3418 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003419 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003420 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3421 // Otherwise use original loop conditon and evaluate it in runtime.
3422 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3423}
3424
Alexander Musmana5f070a2014-10-01 06:03:56 +00003425/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003426DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003427 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003428 auto *VD = dyn_cast<VarDecl>(LCDecl);
3429 if (!VD) {
3430 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3431 auto *Ref = buildDeclRefExpr(
3432 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003433 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3434 // If the loop control decl is explicitly marked as private, do not mark it
3435 // as captured again.
3436 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3437 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003438 return Ref;
3439 }
3440 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003441 DefaultLoc);
3442}
3443
3444Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003445 if (LCDecl && !LCDecl->isInvalidDecl()) {
3446 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003447 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3449 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003450 if (PrivateVar->isInvalidDecl())
3451 return nullptr;
3452 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3453 }
3454 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003455}
3456
Samuel Antao4c8035b2016-12-12 18:00:20 +00003457/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003458Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3459
3460/// \brief Build step of the counter be used for codegen.
3461Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3462
3463/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003464struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003465 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003466 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003467 /// \brief This expression calculates the number of iterations in the loop.
3468 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003469 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003470 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003471 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003472 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003473 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003474 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003475 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003476 /// \brief This is step for the #CounterVar used to generate its update:
3477 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003478 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003479 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003480 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003481 /// \brief Source range of the loop init.
3482 SourceRange InitSrcRange;
3483 /// \brief Source range of the loop condition.
3484 SourceRange CondSrcRange;
3485 /// \brief Source range of the loop increment.
3486 SourceRange IncSrcRange;
3487};
3488
Alexey Bataev23b69422014-06-18 07:08:49 +00003489} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003490
Alexey Bataev9c821032015-04-30 04:23:23 +00003491void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3492 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3493 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003494 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3495 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003496 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3497 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003498 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3499 if (auto *D = ISC.GetLoopDecl()) {
3500 auto *VD = dyn_cast<VarDecl>(D);
3501 if (!VD) {
3502 if (auto *Private = IsOpenMPCapturedDecl(D))
3503 VD = Private;
3504 else {
3505 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3506 /*WithInit=*/false);
3507 VD = cast<VarDecl>(Ref->getDecl());
3508 }
3509 }
3510 DSAStack->addLoopControlVariable(D, VD);
3511 }
3512 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003513 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003514 }
3515}
3516
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003517/// \brief Called on a for stmt to check and extract its iteration space
3518/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003519static bool CheckOpenMPIterationSpace(
3520 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3521 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003522 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003523 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003524 LoopIterationSpace &ResultIterSpace,
3525 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003526 // OpenMP [2.6, Canonical Loop Form]
3527 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003528 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003529 if (!For) {
3530 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003531 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3532 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3533 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3534 if (NestedLoopCount > 1) {
3535 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3536 SemaRef.Diag(DSA.getConstructLoc(),
3537 diag::note_omp_collapse_ordered_expr)
3538 << 2 << CollapseLoopCountExpr->getSourceRange()
3539 << OrderedLoopCountExpr->getSourceRange();
3540 else if (CollapseLoopCountExpr)
3541 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3542 diag::note_omp_collapse_ordered_expr)
3543 << 0 << CollapseLoopCountExpr->getSourceRange();
3544 else
3545 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3546 diag::note_omp_collapse_ordered_expr)
3547 << 1 << OrderedLoopCountExpr->getSourceRange();
3548 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003549 return true;
3550 }
3551 assert(For->getBody());
3552
3553 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3554
3555 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003556 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003557 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003558 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003559
3560 bool HasErrors = false;
3561
3562 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003563 if (auto *LCDecl = ISC.GetLoopDecl()) {
3564 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003565
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003566 // OpenMP [2.6, Canonical Loop Form]
3567 // Var is one of the following:
3568 // A variable of signed or unsigned integer type.
3569 // For C++, a variable of a random access iterator type.
3570 // For C, a variable of a pointer type.
3571 auto VarType = LCDecl->getType().getNonReferenceType();
3572 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3573 !VarType->isPointerType() &&
3574 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3575 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3576 << SemaRef.getLangOpts().CPlusPlus;
3577 HasErrors = true;
3578 }
3579
3580 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3581 // a Construct
3582 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3583 // parallel for construct is (are) private.
3584 // The loop iteration variable in the associated for-loop of a simd
3585 // construct with just one associated for-loop is linear with a
3586 // constant-linear-step that is the increment of the associated for-loop.
3587 // Exclude loop var from the list of variables with implicitly defined data
3588 // sharing attributes.
3589 VarsWithImplicitDSA.erase(LCDecl);
3590
3591 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3592 // in a Construct, C/C++].
3593 // The loop iteration variable in the associated for-loop of a simd
3594 // construct with just one associated for-loop may be listed in a linear
3595 // clause with a constant-linear-step that is the increment of the
3596 // associated for-loop.
3597 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3598 // parallel for construct may be listed in a private or lastprivate clause.
3599 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3600 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3601 // declared in the loop and it is predetermined as a private.
3602 auto PredeterminedCKind =
3603 isOpenMPSimdDirective(DKind)
3604 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3605 : OMPC_private;
3606 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3607 DVar.CKind != PredeterminedCKind) ||
3608 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3609 isOpenMPDistributeDirective(DKind)) &&
3610 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3611 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3612 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3613 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3614 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3615 << getOpenMPClauseName(PredeterminedCKind);
3616 if (DVar.RefExpr == nullptr)
3617 DVar.CKind = PredeterminedCKind;
3618 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3619 HasErrors = true;
3620 } else if (LoopDeclRefExpr != nullptr) {
3621 // Make the loop iteration variable private (for worksharing constructs),
3622 // linear (for simd directives with the only one associated loop) or
3623 // lastprivate (for simd directives with several collapsed or ordered
3624 // loops).
3625 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003626 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3627 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003628 /*FromParent=*/false);
3629 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3630 }
3631
3632 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3633
3634 // Check test-expr.
3635 HasErrors |= ISC.CheckCond(For->getCond());
3636
3637 // Check incr-expr.
3638 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003639 }
3640
Alexander Musmana5f070a2014-10-01 06:03:56 +00003641 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003642 return HasErrors;
3643
Alexander Musmana5f070a2014-10-01 06:03:56 +00003644 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003645 ResultIterSpace.PreCond =
3646 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003647 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003648 DSA.getCurScope(),
3649 (isOpenMPWorksharingDirective(DKind) ||
3650 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3651 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003652 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003653 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003654 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3655 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3656 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3657 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3658 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3659 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3660
Alexey Bataev62dbb972015-04-22 11:59:37 +00003661 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3662 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003663 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003664 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003665 ResultIterSpace.CounterInit == nullptr ||
3666 ResultIterSpace.CounterStep == nullptr);
3667
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003668 return HasErrors;
3669}
3670
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003671/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003672static ExprResult
3673BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3674 ExprResult Start,
3675 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003676 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003677 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3678 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003679 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003680 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003681 VarRef.get()->getType())) {
3682 NewStart = SemaRef.PerformImplicitConversion(
3683 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3684 /*AllowExplicit=*/true);
3685 if (!NewStart.isUsable())
3686 return ExprError();
3687 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003688
3689 auto Init =
3690 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3691 return Init;
3692}
3693
Alexander Musmana5f070a2014-10-01 06:03:56 +00003694/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003695static ExprResult
3696BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3697 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3698 ExprResult Step, bool Subtract,
3699 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003700 // Add parentheses (for debugging purposes only).
3701 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3702 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3703 !Step.isUsable())
3704 return ExprError();
3705
Alexey Bataev5a3af132016-03-29 08:58:54 +00003706 ExprResult NewStep = Step;
3707 if (Captures)
3708 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003709 if (NewStep.isInvalid())
3710 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003711 ExprResult Update =
3712 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003713 if (!Update.isUsable())
3714 return ExprError();
3715
Alexey Bataevc0214e02016-02-16 12:13:49 +00003716 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3717 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003718 ExprResult NewStart = Start;
3719 if (Captures)
3720 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003721 if (NewStart.isInvalid())
3722 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003723
Alexey Bataevc0214e02016-02-16 12:13:49 +00003724 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3725 ExprResult SavedUpdate = Update;
3726 ExprResult UpdateVal;
3727 if (VarRef.get()->getType()->isOverloadableType() ||
3728 NewStart.get()->getType()->isOverloadableType() ||
3729 Update.get()->getType()->isOverloadableType()) {
3730 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3731 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3732 Update =
3733 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3734 if (Update.isUsable()) {
3735 UpdateVal =
3736 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3737 VarRef.get(), SavedUpdate.get());
3738 if (UpdateVal.isUsable()) {
3739 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3740 UpdateVal.get());
3741 }
3742 }
3743 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3744 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003745
Alexey Bataevc0214e02016-02-16 12:13:49 +00003746 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3747 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3748 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3749 NewStart.get(), SavedUpdate.get());
3750 if (!Update.isUsable())
3751 return ExprError();
3752
Alexey Bataev11481f52016-02-17 10:29:05 +00003753 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3754 VarRef.get()->getType())) {
3755 Update = SemaRef.PerformImplicitConversion(
3756 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3757 if (!Update.isUsable())
3758 return ExprError();
3759 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003760
3761 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3762 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003763 return Update;
3764}
3765
3766/// \brief Convert integer expression \a E to make it have at least \a Bits
3767/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003768static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003769 if (E == nullptr)
3770 return ExprError();
3771 auto &C = SemaRef.Context;
3772 QualType OldType = E->getType();
3773 unsigned HasBits = C.getTypeSize(OldType);
3774 if (HasBits >= Bits)
3775 return ExprResult(E);
3776 // OK to convert to signed, because new type has more bits than old.
3777 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3778 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3779 true);
3780}
3781
3782/// \brief Check if the given expression \a E is a constant integer that fits
3783/// into \a Bits bits.
3784static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3785 if (E == nullptr)
3786 return false;
3787 llvm::APSInt Result;
3788 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3789 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3790 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003791}
3792
Alexey Bataev5a3af132016-03-29 08:58:54 +00003793/// Build preinits statement for the given declarations.
3794static Stmt *buildPreInits(ASTContext &Context,
3795 SmallVectorImpl<Decl *> &PreInits) {
3796 if (!PreInits.empty()) {
3797 return new (Context) DeclStmt(
3798 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3799 SourceLocation(), SourceLocation());
3800 }
3801 return nullptr;
3802}
3803
3804/// Build preinits statement for the given declarations.
3805static Stmt *buildPreInits(ASTContext &Context,
3806 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3807 if (!Captures.empty()) {
3808 SmallVector<Decl *, 16> PreInits;
3809 for (auto &Pair : Captures)
3810 PreInits.push_back(Pair.second->getDecl());
3811 return buildPreInits(Context, PreInits);
3812 }
3813 return nullptr;
3814}
3815
3816/// Build postupdate expression for the given list of postupdates expressions.
3817static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3818 Expr *PostUpdate = nullptr;
3819 if (!PostUpdates.empty()) {
3820 for (auto *E : PostUpdates) {
3821 Expr *ConvE = S.BuildCStyleCastExpr(
3822 E->getExprLoc(),
3823 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3824 E->getExprLoc(), E)
3825 .get();
3826 PostUpdate = PostUpdate
3827 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3828 PostUpdate, ConvE)
3829 .get()
3830 : ConvE;
3831 }
3832 }
3833 return PostUpdate;
3834}
3835
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003836/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003837/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3838/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003839static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003840CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3841 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3842 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003843 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003844 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003845 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003846 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003847 // Found 'collapse' clause - calculate collapse number.
3848 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003849 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003850 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003851 }
3852 if (OrderedLoopCountExpr) {
3853 // Found 'ordered' clause - calculate collapse number.
3854 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003855 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3856 if (Result.getLimitedValue() < NestedLoopCount) {
3857 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3858 diag::err_omp_wrong_ordered_loop_count)
3859 << OrderedLoopCountExpr->getSourceRange();
3860 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3861 diag::note_collapse_loop_count)
3862 << CollapseLoopCountExpr->getSourceRange();
3863 }
3864 NestedLoopCount = Result.getLimitedValue();
3865 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003866 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003867 // This is helper routine for loop directives (e.g., 'for', 'simd',
3868 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003869 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003870 SmallVector<LoopIterationSpace, 4> IterSpaces;
3871 IterSpaces.resize(NestedLoopCount);
3872 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003873 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003874 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003875 NestedLoopCount, CollapseLoopCountExpr,
3876 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003877 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003878 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003879 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003880 // OpenMP [2.8.1, simd construct, Restrictions]
3881 // All loops associated with the construct must be perfectly nested; that
3882 // is, there must be no intervening code nor any OpenMP directive between
3883 // any two loops.
3884 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003885 }
3886
Alexander Musmana5f070a2014-10-01 06:03:56 +00003887 Built.clear(/* size */ NestedLoopCount);
3888
3889 if (SemaRef.CurContext->isDependentContext())
3890 return NestedLoopCount;
3891
3892 // An example of what is generated for the following code:
3893 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003894 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003895 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003896 // for (k = 0; k < NK; ++k)
3897 // for (j = J0; j < NJ; j+=2) {
3898 // <loop body>
3899 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003900 //
3901 // We generate the code below.
3902 // Note: the loop body may be outlined in CodeGen.
3903 // Note: some counters may be C++ classes, operator- is used to find number of
3904 // iterations and operator+= to calculate counter value.
3905 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3906 // or i64 is currently supported).
3907 //
3908 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3909 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3910 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3911 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3912 // // similar updates for vars in clauses (e.g. 'linear')
3913 // <loop body (using local i and j)>
3914 // }
3915 // i = NI; // assign final values of counters
3916 // j = NJ;
3917 //
3918
3919 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3920 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003921 // Precondition tests if there is at least one iteration (all conditions are
3922 // true).
3923 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003924 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003925 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003926 32 /* Bits */, SemaRef
3927 .PerformImplicitConversion(
3928 N0->IgnoreImpCasts(), N0->getType(),
3929 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003930 .get(),
3931 SemaRef);
3932 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003933 64 /* Bits */, SemaRef
3934 .PerformImplicitConversion(
3935 N0->IgnoreImpCasts(), N0->getType(),
3936 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003937 .get(),
3938 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003939
3940 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3941 return NestedLoopCount;
3942
3943 auto &C = SemaRef.Context;
3944 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3945
3946 Scope *CurScope = DSA.getCurScope();
3947 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003948 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003949 PreCond =
3950 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3951 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003952 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003953 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003954 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003955 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3956 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003957 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003958 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003959 SemaRef
3960 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3961 Sema::AA_Converting,
3962 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003963 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003964 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003965 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003966 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003967 SemaRef
3968 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3969 Sema::AA_Converting,
3970 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003971 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003972 }
3973
3974 // Choose either the 32-bit or 64-bit version.
3975 ExprResult LastIteration = LastIteration64;
3976 if (LastIteration32.isUsable() &&
3977 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3978 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3979 FitsInto(
3980 32 /* Bits */,
3981 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3982 LastIteration64.get(), SemaRef)))
3983 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003984 QualType VType = LastIteration.get()->getType();
3985 QualType RealVType = VType;
3986 QualType StrideVType = VType;
3987 if (isOpenMPTaskLoopDirective(DKind)) {
3988 VType =
3989 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3990 StrideVType =
3991 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3992 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003993
3994 if (!LastIteration.isUsable())
3995 return 0;
3996
3997 // Save the number of iterations.
3998 ExprResult NumIterations = LastIteration;
3999 {
4000 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004001 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4002 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004003 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4004 if (!LastIteration.isUsable())
4005 return 0;
4006 }
4007
4008 // Calculate the last iteration number beforehand instead of doing this on
4009 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4010 llvm::APSInt Result;
4011 bool IsConstant =
4012 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4013 ExprResult CalcLastIteration;
4014 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004015 ExprResult SaveRef =
4016 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004017 LastIteration = SaveRef;
4018
4019 // Prepare SaveRef + 1.
4020 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004021 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004022 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4023 if (!NumIterations.isUsable())
4024 return 0;
4025 }
4026
4027 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4028
David Majnemer9d168222016-08-05 17:44:54 +00004029 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00004030 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004031 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4032 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004033 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004034 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4035 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004036 SemaRef.AddInitializerToDecl(LBDecl,
4037 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4038 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004039
4040 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004041 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4042 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004043 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004044 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004045
4046 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4047 // This will be used to implement clause 'lastprivate'.
4048 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004049 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4050 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004051 SemaRef.AddInitializerToDecl(ILDecl,
4052 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4053 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004054
4055 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004056 VarDecl *STDecl =
4057 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4058 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004059 SemaRef.AddInitializerToDecl(STDecl,
4060 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4061 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004062
4063 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004064 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004065 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4066 UB.get(), LastIteration.get());
4067 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4068 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4069 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4070 CondOp.get());
4071 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004072
4073 // If we have a combined directive that combines 'distribute', 'for' or
4074 // 'simd' we need to be able to access the bounds of the schedule of the
4075 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4076 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4077 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4078 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4079
4080 // We expect to have at least 2 more parameters than the 'parallel'
4081 // directive does - the lower and upper bounds of the previous schedule.
4082 assert(CD->getNumParams() >= 4 &&
4083 "Unexpected number of parameters in loop combined directive");
4084
4085 // Set the proper type for the bounds given what we learned from the
4086 // enclosed loops.
4087 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4088 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4089
4090 // Previous lower and upper bounds are obtained from the region
4091 // parameters.
4092 PrevLB =
4093 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4094 PrevUB =
4095 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4096 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004097 }
4098
4099 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004100 ExprResult IV;
4101 ExprResult Init;
4102 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004103 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4104 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004105 Expr *RHS =
4106 (isOpenMPWorksharingDirective(DKind) ||
4107 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4108 ? LB.get()
4109 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004110 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4111 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004112 }
4113
Alexander Musmanc6388682014-12-15 07:07:06 +00004114 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004115 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004116 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004117 (isOpenMPWorksharingDirective(DKind) ||
4118 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004119 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4120 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4121 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004122
4123 // Loop increment (IV = IV + 1)
4124 SourceLocation IncLoc;
4125 ExprResult Inc =
4126 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4127 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4128 if (!Inc.isUsable())
4129 return 0;
4130 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004131 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4132 if (!Inc.isUsable())
4133 return 0;
4134
4135 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4136 // Used for directives with static scheduling.
4137 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004138 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4139 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004140 // LB + ST
4141 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4142 if (!NextLB.isUsable())
4143 return 0;
4144 // LB = LB + ST
4145 NextLB =
4146 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4147 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4148 if (!NextLB.isUsable())
4149 return 0;
4150 // UB + ST
4151 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4152 if (!NextUB.isUsable())
4153 return 0;
4154 // UB = UB + ST
4155 NextUB =
4156 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4157 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4158 if (!NextUB.isUsable())
4159 return 0;
4160 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004161
4162 // Build updates and final values of the loop counters.
4163 bool HasErrors = false;
4164 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004165 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004166 Built.Updates.resize(NestedLoopCount);
4167 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004168 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004169 {
4170 ExprResult Div;
4171 // Go from inner nested loop to outer.
4172 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4173 LoopIterationSpace &IS = IterSpaces[Cnt];
4174 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4175 // Build: Iter = (IV / Div) % IS.NumIters
4176 // where Div is product of previous iterations' IS.NumIters.
4177 ExprResult Iter;
4178 if (Div.isUsable()) {
4179 Iter =
4180 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4181 } else {
4182 Iter = IV;
4183 assert((Cnt == (int)NestedLoopCount - 1) &&
4184 "unusable div expected on first iteration only");
4185 }
4186
4187 if (Cnt != 0 && Iter.isUsable())
4188 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4189 IS.NumIterations);
4190 if (!Iter.isUsable()) {
4191 HasErrors = true;
4192 break;
4193 }
4194
Alexey Bataev39f915b82015-05-08 10:41:21 +00004195 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004196 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4197 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4198 IS.CounterVar->getExprLoc(),
4199 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004200 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004201 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004202 if (!Init.isUsable()) {
4203 HasErrors = true;
4204 break;
4205 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004206 ExprResult Update = BuildCounterUpdate(
4207 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4208 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004209 if (!Update.isUsable()) {
4210 HasErrors = true;
4211 break;
4212 }
4213
4214 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4215 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004216 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004217 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004218 if (!Final.isUsable()) {
4219 HasErrors = true;
4220 break;
4221 }
4222
4223 // Build Div for the next iteration: Div <- Div * IS.NumIters
4224 if (Cnt != 0) {
4225 if (Div.isUnset())
4226 Div = IS.NumIterations;
4227 else
4228 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4229 IS.NumIterations);
4230
4231 // Add parentheses (for debugging purposes only).
4232 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004233 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004234 if (!Div.isUsable()) {
4235 HasErrors = true;
4236 break;
4237 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004238 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004239 }
4240 if (!Update.isUsable() || !Final.isUsable()) {
4241 HasErrors = true;
4242 break;
4243 }
4244 // Save results
4245 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004246 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004247 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004248 Built.Updates[Cnt] = Update.get();
4249 Built.Finals[Cnt] = Final.get();
4250 }
4251 }
4252
4253 if (HasErrors)
4254 return 0;
4255
4256 // Save results
4257 Built.IterationVarRef = IV.get();
4258 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004259 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004260 Built.CalcLastIteration =
4261 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004262 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004263 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004264 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004265 Built.Init = Init.get();
4266 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004267 Built.LB = LB.get();
4268 Built.UB = UB.get();
4269 Built.IL = IL.get();
4270 Built.ST = ST.get();
4271 Built.EUB = EUB.get();
4272 Built.NLB = NextLB.get();
4273 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004274 Built.PrevLB = PrevLB.get();
4275 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004276
Alexey Bataev8b427062016-05-25 12:36:08 +00004277 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4278 // Fill data for doacross depend clauses.
4279 for (auto Pair : DSA.getDoacrossDependClauses()) {
4280 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4281 Pair.first->setCounterValue(CounterVal);
4282 else {
4283 if (NestedLoopCount != Pair.second.size() ||
4284 NestedLoopCount != LoopMultipliers.size() + 1) {
4285 // Erroneous case - clause has some problems.
4286 Pair.first->setCounterValue(CounterVal);
4287 continue;
4288 }
4289 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4290 auto I = Pair.second.rbegin();
4291 auto IS = IterSpaces.rbegin();
4292 auto ILM = LoopMultipliers.rbegin();
4293 Expr *UpCounterVal = CounterVal;
4294 Expr *Multiplier = nullptr;
4295 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4296 if (I->first) {
4297 assert(IS->CounterStep);
4298 Expr *NormalizedOffset =
4299 SemaRef
4300 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4301 I->first, IS->CounterStep)
4302 .get();
4303 if (Multiplier) {
4304 NormalizedOffset =
4305 SemaRef
4306 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4307 NormalizedOffset, Multiplier)
4308 .get();
4309 }
4310 assert(I->second == OO_Plus || I->second == OO_Minus);
4311 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004312 UpCounterVal = SemaRef
4313 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4314 UpCounterVal, NormalizedOffset)
4315 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004316 }
4317 Multiplier = *ILM;
4318 ++I;
4319 ++IS;
4320 ++ILM;
4321 }
4322 Pair.first->setCounterValue(UpCounterVal);
4323 }
4324 }
4325
Alexey Bataevabfc0692014-06-25 06:52:00 +00004326 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004327}
4328
Alexey Bataev10e775f2015-07-30 11:36:16 +00004329static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004330 auto CollapseClauses =
4331 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4332 if (CollapseClauses.begin() != CollapseClauses.end())
4333 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004334 return nullptr;
4335}
4336
Alexey Bataev10e775f2015-07-30 11:36:16 +00004337static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004338 auto OrderedClauses =
4339 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4340 if (OrderedClauses.begin() != OrderedClauses.end())
4341 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004342 return nullptr;
4343}
4344
Kelvin Lic5609492016-07-15 04:39:07 +00004345static bool checkSimdlenSafelenSpecified(Sema &S,
4346 const ArrayRef<OMPClause *> Clauses) {
4347 OMPSafelenClause *Safelen = nullptr;
4348 OMPSimdlenClause *Simdlen = nullptr;
4349
4350 for (auto *Clause : Clauses) {
4351 if (Clause->getClauseKind() == OMPC_safelen)
4352 Safelen = cast<OMPSafelenClause>(Clause);
4353 else if (Clause->getClauseKind() == OMPC_simdlen)
4354 Simdlen = cast<OMPSimdlenClause>(Clause);
4355 if (Safelen && Simdlen)
4356 break;
4357 }
4358
4359 if (Simdlen && Safelen) {
4360 llvm::APSInt SimdlenRes, SafelenRes;
4361 auto SimdlenLength = Simdlen->getSimdlen();
4362 auto SafelenLength = Safelen->getSafelen();
4363 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4364 SimdlenLength->isInstantiationDependent() ||
4365 SimdlenLength->containsUnexpandedParameterPack())
4366 return false;
4367 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4368 SafelenLength->isInstantiationDependent() ||
4369 SafelenLength->containsUnexpandedParameterPack())
4370 return false;
4371 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4372 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4373 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4374 // If both simdlen and safelen clauses are specified, the value of the
4375 // simdlen parameter must be less than or equal to the value of the safelen
4376 // parameter.
4377 if (SimdlenRes > SafelenRes) {
4378 S.Diag(SimdlenLength->getExprLoc(),
4379 diag::err_omp_wrong_simdlen_safelen_values)
4380 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4381 return true;
4382 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004383 }
4384 return false;
4385}
4386
Alexey Bataev4acb8592014-07-07 13:01:15 +00004387StmtResult Sema::ActOnOpenMPSimdDirective(
4388 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4389 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004390 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004391 if (!AStmt)
4392 return StmtError();
4393
4394 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004395 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004396 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4397 // define the nested loops number.
4398 unsigned NestedLoopCount = CheckOpenMPLoop(
4399 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4400 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004401 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004402 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004403
Alexander Musmana5f070a2014-10-01 06:03:56 +00004404 assert((CurContext->isDependentContext() || B.builtAll()) &&
4405 "omp simd loop exprs were not built");
4406
Alexander Musman3276a272015-03-21 10:12:56 +00004407 if (!CurContext->isDependentContext()) {
4408 // Finalize the clauses that need pre-built expressions for CodeGen.
4409 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004410 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004411 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004412 B.NumIterations, *this, CurScope,
4413 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004414 return StmtError();
4415 }
4416 }
4417
Kelvin Lic5609492016-07-15 04:39:07 +00004418 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004419 return StmtError();
4420
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004421 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004422 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4423 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004424}
4425
Alexey Bataev4acb8592014-07-07 13:01:15 +00004426StmtResult Sema::ActOnOpenMPForDirective(
4427 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4428 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004429 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004430 if (!AStmt)
4431 return StmtError();
4432
4433 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004434 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004435 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4436 // define the nested loops number.
4437 unsigned NestedLoopCount = CheckOpenMPLoop(
4438 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4439 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004440 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004441 return StmtError();
4442
Alexander Musmana5f070a2014-10-01 06:03:56 +00004443 assert((CurContext->isDependentContext() || B.builtAll()) &&
4444 "omp for loop exprs were not built");
4445
Alexey Bataev54acd402015-08-04 11:18:19 +00004446 if (!CurContext->isDependentContext()) {
4447 // Finalize the clauses that need pre-built expressions for CodeGen.
4448 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004449 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004450 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004451 B.NumIterations, *this, CurScope,
4452 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004453 return StmtError();
4454 }
4455 }
4456
Alexey Bataevf29276e2014-06-18 04:14:57 +00004457 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004458 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004459 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004460}
4461
Alexander Musmanf82886e2014-09-18 05:12:34 +00004462StmtResult Sema::ActOnOpenMPForSimdDirective(
4463 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4464 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004465 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004466 if (!AStmt)
4467 return StmtError();
4468
4469 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004470 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004471 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4472 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004473 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004474 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4475 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4476 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004477 if (NestedLoopCount == 0)
4478 return StmtError();
4479
Alexander Musmanc6388682014-12-15 07:07:06 +00004480 assert((CurContext->isDependentContext() || B.builtAll()) &&
4481 "omp for simd loop exprs were not built");
4482
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004483 if (!CurContext->isDependentContext()) {
4484 // Finalize the clauses that need pre-built expressions for CodeGen.
4485 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004486 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004487 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004488 B.NumIterations, *this, CurScope,
4489 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004490 return StmtError();
4491 }
4492 }
4493
Kelvin Lic5609492016-07-15 04:39:07 +00004494 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004495 return StmtError();
4496
Alexander Musmanf82886e2014-09-18 05:12:34 +00004497 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004498 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4499 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004500}
4501
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004502StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4503 Stmt *AStmt,
4504 SourceLocation StartLoc,
4505 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004506 if (!AStmt)
4507 return StmtError();
4508
4509 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004510 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004511 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004512 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004513 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004514 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004515 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004516 return StmtError();
4517 // All associated statements must be '#pragma omp section' except for
4518 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004519 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004520 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4521 if (SectionStmt)
4522 Diag(SectionStmt->getLocStart(),
4523 diag::err_omp_sections_substmt_not_section);
4524 return StmtError();
4525 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004526 cast<OMPSectionDirective>(SectionStmt)
4527 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004528 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004529 } else {
4530 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4531 return StmtError();
4532 }
4533
4534 getCurFunction()->setHasBranchProtectedScope();
4535
Alexey Bataev25e5b442015-09-15 12:52:43 +00004536 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4537 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004538}
4539
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004540StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4541 SourceLocation StartLoc,
4542 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004543 if (!AStmt)
4544 return StmtError();
4545
4546 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004547
4548 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004549 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004550
Alexey Bataev25e5b442015-09-15 12:52:43 +00004551 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4552 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004553}
4554
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004555StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4556 Stmt *AStmt,
4557 SourceLocation StartLoc,
4558 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004559 if (!AStmt)
4560 return StmtError();
4561
4562 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004563
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004564 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004565
Alexey Bataev3255bf32015-01-19 05:20:46 +00004566 // OpenMP [2.7.3, single Construct, Restrictions]
4567 // The copyprivate clause must not be used with the nowait clause.
4568 OMPClause *Nowait = nullptr;
4569 OMPClause *Copyprivate = nullptr;
4570 for (auto *Clause : Clauses) {
4571 if (Clause->getClauseKind() == OMPC_nowait)
4572 Nowait = Clause;
4573 else if (Clause->getClauseKind() == OMPC_copyprivate)
4574 Copyprivate = Clause;
4575 if (Copyprivate && Nowait) {
4576 Diag(Copyprivate->getLocStart(),
4577 diag::err_omp_single_copyprivate_with_nowait);
4578 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4579 return StmtError();
4580 }
4581 }
4582
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004583 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4584}
4585
Alexander Musman80c22892014-07-17 08:54:58 +00004586StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4587 SourceLocation StartLoc,
4588 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004589 if (!AStmt)
4590 return StmtError();
4591
4592 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004593
4594 getCurFunction()->setHasBranchProtectedScope();
4595
4596 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4597}
4598
Alexey Bataev28c75412015-12-15 08:19:24 +00004599StmtResult Sema::ActOnOpenMPCriticalDirective(
4600 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4601 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004602 if (!AStmt)
4603 return StmtError();
4604
4605 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004606
Alexey Bataev28c75412015-12-15 08:19:24 +00004607 bool ErrorFound = false;
4608 llvm::APSInt Hint;
4609 SourceLocation HintLoc;
4610 bool DependentHint = false;
4611 for (auto *C : Clauses) {
4612 if (C->getClauseKind() == OMPC_hint) {
4613 if (!DirName.getName()) {
4614 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4615 ErrorFound = true;
4616 }
4617 Expr *E = cast<OMPHintClause>(C)->getHint();
4618 if (E->isTypeDependent() || E->isValueDependent() ||
4619 E->isInstantiationDependent())
4620 DependentHint = true;
4621 else {
4622 Hint = E->EvaluateKnownConstInt(Context);
4623 HintLoc = C->getLocStart();
4624 }
4625 }
4626 }
4627 if (ErrorFound)
4628 return StmtError();
4629 auto Pair = DSAStack->getCriticalWithHint(DirName);
4630 if (Pair.first && DirName.getName() && !DependentHint) {
4631 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4632 Diag(StartLoc, diag::err_omp_critical_with_hint);
4633 if (HintLoc.isValid()) {
4634 Diag(HintLoc, diag::note_omp_critical_hint_here)
4635 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4636 } else
4637 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4638 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4639 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4640 << 1
4641 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4642 /*Radix=*/10, /*Signed=*/false);
4643 } else
4644 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4645 }
4646 }
4647
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004648 getCurFunction()->setHasBranchProtectedScope();
4649
Alexey Bataev28c75412015-12-15 08:19:24 +00004650 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4651 Clauses, AStmt);
4652 if (!Pair.first && DirName.getName() && !DependentHint)
4653 DSAStack->addCriticalWithHint(Dir, Hint);
4654 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004655}
4656
Alexey Bataev4acb8592014-07-07 13:01:15 +00004657StmtResult Sema::ActOnOpenMPParallelForDirective(
4658 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4659 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004660 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004661 if (!AStmt)
4662 return StmtError();
4663
Alexey Bataev4acb8592014-07-07 13:01:15 +00004664 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4665 // 1.2.2 OpenMP Language Terminology
4666 // Structured block - An executable statement with a single entry at the
4667 // top and a single exit at the bottom.
4668 // The point of exit cannot be a branch out of the structured block.
4669 // longjmp() and throw() must not violate the entry/exit criteria.
4670 CS->getCapturedDecl()->setNothrow();
4671
Alexander Musmanc6388682014-12-15 07:07:06 +00004672 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004673 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4674 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004675 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004676 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4677 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4678 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004679 if (NestedLoopCount == 0)
4680 return StmtError();
4681
Alexander Musmana5f070a2014-10-01 06:03:56 +00004682 assert((CurContext->isDependentContext() || B.builtAll()) &&
4683 "omp parallel for loop exprs were not built");
4684
Alexey Bataev54acd402015-08-04 11:18:19 +00004685 if (!CurContext->isDependentContext()) {
4686 // Finalize the clauses that need pre-built expressions for CodeGen.
4687 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004688 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004689 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004690 B.NumIterations, *this, CurScope,
4691 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004692 return StmtError();
4693 }
4694 }
4695
Alexey Bataev4acb8592014-07-07 13:01:15 +00004696 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004697 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004698 NestedLoopCount, Clauses, AStmt, B,
4699 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004700}
4701
Alexander Musmane4e893b2014-09-23 09:33:00 +00004702StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4703 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4704 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004705 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004706 if (!AStmt)
4707 return StmtError();
4708
Alexander Musmane4e893b2014-09-23 09:33:00 +00004709 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4710 // 1.2.2 OpenMP Language Terminology
4711 // Structured block - An executable statement with a single entry at the
4712 // top and a single exit at the bottom.
4713 // The point of exit cannot be a branch out of the structured block.
4714 // longjmp() and throw() must not violate the entry/exit criteria.
4715 CS->getCapturedDecl()->setNothrow();
4716
Alexander Musmanc6388682014-12-15 07:07:06 +00004717 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004718 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4719 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004720 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004721 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4722 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4723 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004724 if (NestedLoopCount == 0)
4725 return StmtError();
4726
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004727 if (!CurContext->isDependentContext()) {
4728 // Finalize the clauses that need pre-built expressions for CodeGen.
4729 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004730 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004731 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004732 B.NumIterations, *this, CurScope,
4733 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004734 return StmtError();
4735 }
4736 }
4737
Kelvin Lic5609492016-07-15 04:39:07 +00004738 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004739 return StmtError();
4740
Alexander Musmane4e893b2014-09-23 09:33:00 +00004741 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004742 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004743 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004744}
4745
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004746StmtResult
4747Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4748 Stmt *AStmt, SourceLocation StartLoc,
4749 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004750 if (!AStmt)
4751 return StmtError();
4752
4753 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004754 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004755 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004756 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004757 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004758 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004759 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004760 return StmtError();
4761 // All associated statements must be '#pragma omp section' except for
4762 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004763 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004764 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4765 if (SectionStmt)
4766 Diag(SectionStmt->getLocStart(),
4767 diag::err_omp_parallel_sections_substmt_not_section);
4768 return StmtError();
4769 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004770 cast<OMPSectionDirective>(SectionStmt)
4771 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004772 }
4773 } else {
4774 Diag(AStmt->getLocStart(),
4775 diag::err_omp_parallel_sections_not_compound_stmt);
4776 return StmtError();
4777 }
4778
4779 getCurFunction()->setHasBranchProtectedScope();
4780
Alexey Bataev25e5b442015-09-15 12:52:43 +00004781 return OMPParallelSectionsDirective::Create(
4782 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004783}
4784
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004785StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4786 Stmt *AStmt, SourceLocation StartLoc,
4787 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004788 if (!AStmt)
4789 return StmtError();
4790
David Majnemer9d168222016-08-05 17:44:54 +00004791 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004792 // 1.2.2 OpenMP Language Terminology
4793 // Structured block - An executable statement with a single entry at the
4794 // top and a single exit at the bottom.
4795 // The point of exit cannot be a branch out of the structured block.
4796 // longjmp() and throw() must not violate the entry/exit criteria.
4797 CS->getCapturedDecl()->setNothrow();
4798
4799 getCurFunction()->setHasBranchProtectedScope();
4800
Alexey Bataev25e5b442015-09-15 12:52:43 +00004801 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4802 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004803}
4804
Alexey Bataev68446b72014-07-18 07:47:19 +00004805StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4806 SourceLocation EndLoc) {
4807 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4808}
4809
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004810StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4811 SourceLocation EndLoc) {
4812 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4813}
4814
Alexey Bataev2df347a2014-07-18 10:17:07 +00004815StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4816 SourceLocation EndLoc) {
4817 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4818}
4819
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004820StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4821 SourceLocation StartLoc,
4822 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004823 if (!AStmt)
4824 return StmtError();
4825
4826 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004827
4828 getCurFunction()->setHasBranchProtectedScope();
4829
4830 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4831}
4832
Alexey Bataev6125da92014-07-21 11:26:11 +00004833StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4834 SourceLocation StartLoc,
4835 SourceLocation EndLoc) {
4836 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4837 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4838}
4839
Alexey Bataev346265e2015-09-25 10:37:12 +00004840StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4841 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004842 SourceLocation StartLoc,
4843 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004844 OMPClause *DependFound = nullptr;
4845 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004846 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004847 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004848 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004849 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004850 for (auto *C : Clauses) {
4851 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4852 DependFound = C;
4853 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4854 if (DependSourceClause) {
4855 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4856 << getOpenMPDirectiveName(OMPD_ordered)
4857 << getOpenMPClauseName(OMPC_depend) << 2;
4858 ErrorFound = true;
4859 } else
4860 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004861 if (DependSinkClause) {
4862 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4863 << 0;
4864 ErrorFound = true;
4865 }
4866 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4867 if (DependSourceClause) {
4868 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4869 << 1;
4870 ErrorFound = true;
4871 }
4872 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004873 }
4874 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004875 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004876 else if (C->getClauseKind() == OMPC_simd)
4877 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004878 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004879 if (!ErrorFound && !SC &&
4880 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004881 // OpenMP [2.8.1,simd Construct, Restrictions]
4882 // An ordered construct with the simd clause is the only OpenMP construct
4883 // that can appear in the simd region.
4884 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004885 ErrorFound = true;
4886 } else if (DependFound && (TC || SC)) {
4887 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4888 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4889 ErrorFound = true;
4890 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4891 Diag(DependFound->getLocStart(),
4892 diag::err_omp_ordered_directive_without_param);
4893 ErrorFound = true;
4894 } else if (TC || Clauses.empty()) {
4895 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4896 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4897 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4898 << (TC != nullptr);
4899 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4900 ErrorFound = true;
4901 }
4902 }
4903 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004904 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004905
4906 if (AStmt) {
4907 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4908
4909 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004910 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004911
4912 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004913}
4914
Alexey Bataev1d160b12015-03-13 12:27:31 +00004915namespace {
4916/// \brief Helper class for checking expression in 'omp atomic [update]'
4917/// construct.
4918class OpenMPAtomicUpdateChecker {
4919 /// \brief Error results for atomic update expressions.
4920 enum ExprAnalysisErrorCode {
4921 /// \brief A statement is not an expression statement.
4922 NotAnExpression,
4923 /// \brief Expression is not builtin binary or unary operation.
4924 NotABinaryOrUnaryExpression,
4925 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4926 NotAnUnaryIncDecExpression,
4927 /// \brief An expression is not of scalar type.
4928 NotAScalarType,
4929 /// \brief A binary operation is not an assignment operation.
4930 NotAnAssignmentOp,
4931 /// \brief RHS part of the binary operation is not a binary expression.
4932 NotABinaryExpression,
4933 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4934 /// expression.
4935 NotABinaryOperator,
4936 /// \brief RHS binary operation does not have reference to the updated LHS
4937 /// part.
4938 NotAnUpdateExpression,
4939 /// \brief No errors is found.
4940 NoError
4941 };
4942 /// \brief Reference to Sema.
4943 Sema &SemaRef;
4944 /// \brief A location for note diagnostics (when error is found).
4945 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004946 /// \brief 'x' lvalue part of the source atomic expression.
4947 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004948 /// \brief 'expr' rvalue part of the source atomic expression.
4949 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004950 /// \brief Helper expression of the form
4951 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4952 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4953 Expr *UpdateExpr;
4954 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4955 /// important for non-associative operations.
4956 bool IsXLHSInRHSPart;
4957 BinaryOperatorKind Op;
4958 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004959 /// \brief true if the source expression is a postfix unary operation, false
4960 /// if it is a prefix unary operation.
4961 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004962
4963public:
4964 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004965 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004966 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004967 /// \brief Check specified statement that it is suitable for 'atomic update'
4968 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004969 /// expression. If DiagId and NoteId == 0, then only check is performed
4970 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004971 /// \param DiagId Diagnostic which should be emitted if error is found.
4972 /// \param NoteId Diagnostic note for the main error message.
4973 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004974 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004975 /// \brief Return the 'x' lvalue part of the source atomic expression.
4976 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004977 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4978 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004979 /// \brief Return the update expression used in calculation of the updated
4980 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4981 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4982 Expr *getUpdateExpr() const { return UpdateExpr; }
4983 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4984 /// false otherwise.
4985 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4986
Alexey Bataevb78ca832015-04-01 03:33:17 +00004987 /// \brief true if the source expression is a postfix unary operation, false
4988 /// if it is a prefix unary operation.
4989 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4990
Alexey Bataev1d160b12015-03-13 12:27:31 +00004991private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004992 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4993 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004994};
4995} // namespace
4996
4997bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4998 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4999 ExprAnalysisErrorCode ErrorFound = NoError;
5000 SourceLocation ErrorLoc, NoteLoc;
5001 SourceRange ErrorRange, NoteRange;
5002 // Allowed constructs are:
5003 // x = x binop expr;
5004 // x = expr binop x;
5005 if (AtomicBinOp->getOpcode() == BO_Assign) {
5006 X = AtomicBinOp->getLHS();
5007 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5008 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5009 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5010 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5011 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005012 Op = AtomicInnerBinOp->getOpcode();
5013 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005014 auto *LHS = AtomicInnerBinOp->getLHS();
5015 auto *RHS = AtomicInnerBinOp->getRHS();
5016 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5017 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5018 /*Canonical=*/true);
5019 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5020 /*Canonical=*/true);
5021 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5022 /*Canonical=*/true);
5023 if (XId == LHSId) {
5024 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005025 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005026 } else if (XId == RHSId) {
5027 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005028 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005029 } else {
5030 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5031 ErrorRange = AtomicInnerBinOp->getSourceRange();
5032 NoteLoc = X->getExprLoc();
5033 NoteRange = X->getSourceRange();
5034 ErrorFound = NotAnUpdateExpression;
5035 }
5036 } else {
5037 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5038 ErrorRange = AtomicInnerBinOp->getSourceRange();
5039 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5040 NoteRange = SourceRange(NoteLoc, NoteLoc);
5041 ErrorFound = NotABinaryOperator;
5042 }
5043 } else {
5044 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5045 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5046 ErrorFound = NotABinaryExpression;
5047 }
5048 } else {
5049 ErrorLoc = AtomicBinOp->getExprLoc();
5050 ErrorRange = AtomicBinOp->getSourceRange();
5051 NoteLoc = AtomicBinOp->getOperatorLoc();
5052 NoteRange = SourceRange(NoteLoc, NoteLoc);
5053 ErrorFound = NotAnAssignmentOp;
5054 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005055 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005056 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5057 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5058 return true;
5059 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005060 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005061 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005062}
5063
5064bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5065 unsigned NoteId) {
5066 ExprAnalysisErrorCode ErrorFound = NoError;
5067 SourceLocation ErrorLoc, NoteLoc;
5068 SourceRange ErrorRange, NoteRange;
5069 // Allowed constructs are:
5070 // x++;
5071 // x--;
5072 // ++x;
5073 // --x;
5074 // x binop= expr;
5075 // x = x binop expr;
5076 // x = expr binop x;
5077 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5078 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5079 if (AtomicBody->getType()->isScalarType() ||
5080 AtomicBody->isInstantiationDependent()) {
5081 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5082 AtomicBody->IgnoreParenImpCasts())) {
5083 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005084 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005085 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005086 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005087 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005088 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005089 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005090 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5091 AtomicBody->IgnoreParenImpCasts())) {
5092 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005093 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005094 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005095 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5096 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005097 // Check for Unary Operation
5098 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005099 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005100 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5101 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005102 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005103 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5104 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005105 } else {
5106 ErrorFound = NotAnUnaryIncDecExpression;
5107 ErrorLoc = AtomicUnaryOp->getExprLoc();
5108 ErrorRange = AtomicUnaryOp->getSourceRange();
5109 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5110 NoteRange = SourceRange(NoteLoc, NoteLoc);
5111 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005112 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005113 ErrorFound = NotABinaryOrUnaryExpression;
5114 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5115 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5116 }
5117 } else {
5118 ErrorFound = NotAScalarType;
5119 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5120 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5121 }
5122 } else {
5123 ErrorFound = NotAnExpression;
5124 NoteLoc = ErrorLoc = S->getLocStart();
5125 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5126 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005127 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005128 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5129 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5130 return true;
5131 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005132 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005133 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005134 // Build an update expression of form 'OpaqueValueExpr(x) binop
5135 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5136 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5137 auto *OVEX = new (SemaRef.getASTContext())
5138 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5139 auto *OVEExpr = new (SemaRef.getASTContext())
5140 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5141 auto Update =
5142 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5143 IsXLHSInRHSPart ? OVEExpr : OVEX);
5144 if (Update.isInvalid())
5145 return true;
5146 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5147 Sema::AA_Casting);
5148 if (Update.isInvalid())
5149 return true;
5150 UpdateExpr = Update.get();
5151 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005152 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005153}
5154
Alexey Bataev0162e452014-07-22 10:10:35 +00005155StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5156 Stmt *AStmt,
5157 SourceLocation StartLoc,
5158 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005159 if (!AStmt)
5160 return StmtError();
5161
David Majnemer9d168222016-08-05 17:44:54 +00005162 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005163 // 1.2.2 OpenMP Language Terminology
5164 // Structured block - An executable statement with a single entry at the
5165 // top and a single exit at the bottom.
5166 // The point of exit cannot be a branch out of the structured block.
5167 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005168 OpenMPClauseKind AtomicKind = OMPC_unknown;
5169 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005170 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005171 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005172 C->getClauseKind() == OMPC_update ||
5173 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005174 if (AtomicKind != OMPC_unknown) {
5175 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5176 << SourceRange(C->getLocStart(), C->getLocEnd());
5177 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5178 << getOpenMPClauseName(AtomicKind);
5179 } else {
5180 AtomicKind = C->getClauseKind();
5181 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005182 }
5183 }
5184 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005185
Alexey Bataev459dec02014-07-24 06:46:57 +00005186 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005187 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5188 Body = EWC->getSubExpr();
5189
Alexey Bataev62cec442014-11-18 10:14:22 +00005190 Expr *X = nullptr;
5191 Expr *V = nullptr;
5192 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005193 Expr *UE = nullptr;
5194 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005195 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005196 // OpenMP [2.12.6, atomic Construct]
5197 // In the next expressions:
5198 // * x and v (as applicable) are both l-value expressions with scalar type.
5199 // * During the execution of an atomic region, multiple syntactic
5200 // occurrences of x must designate the same storage location.
5201 // * Neither of v and expr (as applicable) may access the storage location
5202 // designated by x.
5203 // * Neither of x and expr (as applicable) may access the storage location
5204 // designated by v.
5205 // * expr is an expression with scalar type.
5206 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5207 // * binop, binop=, ++, and -- are not overloaded operators.
5208 // * The expression x binop expr must be numerically equivalent to x binop
5209 // (expr). This requirement is satisfied if the operators in expr have
5210 // precedence greater than binop, or by using parentheses around expr or
5211 // subexpressions of expr.
5212 // * The expression expr binop x must be numerically equivalent to (expr)
5213 // binop x. This requirement is satisfied if the operators in expr have
5214 // precedence equal to or greater than binop, or by using parentheses around
5215 // expr or subexpressions of expr.
5216 // * For forms that allow multiple occurrences of x, the number of times
5217 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005218 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005219 enum {
5220 NotAnExpression,
5221 NotAnAssignmentOp,
5222 NotAScalarType,
5223 NotAnLValue,
5224 NoError
5225 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005226 SourceLocation ErrorLoc, NoteLoc;
5227 SourceRange ErrorRange, NoteRange;
5228 // If clause is read:
5229 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005230 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5231 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005232 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5233 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5234 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5235 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5236 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5237 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5238 if (!X->isLValue() || !V->isLValue()) {
5239 auto NotLValueExpr = X->isLValue() ? V : X;
5240 ErrorFound = NotAnLValue;
5241 ErrorLoc = AtomicBinOp->getExprLoc();
5242 ErrorRange = AtomicBinOp->getSourceRange();
5243 NoteLoc = NotLValueExpr->getExprLoc();
5244 NoteRange = NotLValueExpr->getSourceRange();
5245 }
5246 } else if (!X->isInstantiationDependent() ||
5247 !V->isInstantiationDependent()) {
5248 auto NotScalarExpr =
5249 (X->isInstantiationDependent() || X->getType()->isScalarType())
5250 ? V
5251 : X;
5252 ErrorFound = NotAScalarType;
5253 ErrorLoc = AtomicBinOp->getExprLoc();
5254 ErrorRange = AtomicBinOp->getSourceRange();
5255 NoteLoc = NotScalarExpr->getExprLoc();
5256 NoteRange = NotScalarExpr->getSourceRange();
5257 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005258 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005259 ErrorFound = NotAnAssignmentOp;
5260 ErrorLoc = AtomicBody->getExprLoc();
5261 ErrorRange = AtomicBody->getSourceRange();
5262 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5263 : AtomicBody->getExprLoc();
5264 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5265 : AtomicBody->getSourceRange();
5266 }
5267 } else {
5268 ErrorFound = NotAnExpression;
5269 NoteLoc = ErrorLoc = Body->getLocStart();
5270 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005271 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005272 if (ErrorFound != NoError) {
5273 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5274 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005275 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5276 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005277 return StmtError();
5278 } else if (CurContext->isDependentContext())
5279 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005280 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005281 enum {
5282 NotAnExpression,
5283 NotAnAssignmentOp,
5284 NotAScalarType,
5285 NotAnLValue,
5286 NoError
5287 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005288 SourceLocation ErrorLoc, NoteLoc;
5289 SourceRange ErrorRange, NoteRange;
5290 // If clause is write:
5291 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005292 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5293 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005294 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5295 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005296 X = AtomicBinOp->getLHS();
5297 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005298 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5299 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5300 if (!X->isLValue()) {
5301 ErrorFound = NotAnLValue;
5302 ErrorLoc = AtomicBinOp->getExprLoc();
5303 ErrorRange = AtomicBinOp->getSourceRange();
5304 NoteLoc = X->getExprLoc();
5305 NoteRange = X->getSourceRange();
5306 }
5307 } else if (!X->isInstantiationDependent() ||
5308 !E->isInstantiationDependent()) {
5309 auto NotScalarExpr =
5310 (X->isInstantiationDependent() || X->getType()->isScalarType())
5311 ? E
5312 : X;
5313 ErrorFound = NotAScalarType;
5314 ErrorLoc = AtomicBinOp->getExprLoc();
5315 ErrorRange = AtomicBinOp->getSourceRange();
5316 NoteLoc = NotScalarExpr->getExprLoc();
5317 NoteRange = NotScalarExpr->getSourceRange();
5318 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005319 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005320 ErrorFound = NotAnAssignmentOp;
5321 ErrorLoc = AtomicBody->getExprLoc();
5322 ErrorRange = AtomicBody->getSourceRange();
5323 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5324 : AtomicBody->getExprLoc();
5325 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5326 : AtomicBody->getSourceRange();
5327 }
5328 } else {
5329 ErrorFound = NotAnExpression;
5330 NoteLoc = ErrorLoc = Body->getLocStart();
5331 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005332 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005333 if (ErrorFound != NoError) {
5334 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5335 << ErrorRange;
5336 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5337 << NoteRange;
5338 return StmtError();
5339 } else if (CurContext->isDependentContext())
5340 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005341 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005342 // If clause is update:
5343 // x++;
5344 // x--;
5345 // ++x;
5346 // --x;
5347 // x binop= expr;
5348 // x = x binop expr;
5349 // x = expr binop x;
5350 OpenMPAtomicUpdateChecker Checker(*this);
5351 if (Checker.checkStatement(
5352 Body, (AtomicKind == OMPC_update)
5353 ? diag::err_omp_atomic_update_not_expression_statement
5354 : diag::err_omp_atomic_not_expression_statement,
5355 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005356 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005357 if (!CurContext->isDependentContext()) {
5358 E = Checker.getExpr();
5359 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005360 UE = Checker.getUpdateExpr();
5361 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005362 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005363 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005364 enum {
5365 NotAnAssignmentOp,
5366 NotACompoundStatement,
5367 NotTwoSubstatements,
5368 NotASpecificExpression,
5369 NoError
5370 } ErrorFound = NoError;
5371 SourceLocation ErrorLoc, NoteLoc;
5372 SourceRange ErrorRange, NoteRange;
5373 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5374 // If clause is a capture:
5375 // v = x++;
5376 // v = x--;
5377 // v = ++x;
5378 // v = --x;
5379 // v = x binop= expr;
5380 // v = x = x binop expr;
5381 // v = x = expr binop x;
5382 auto *AtomicBinOp =
5383 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5384 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5385 V = AtomicBinOp->getLHS();
5386 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5387 OpenMPAtomicUpdateChecker Checker(*this);
5388 if (Checker.checkStatement(
5389 Body, diag::err_omp_atomic_capture_not_expression_statement,
5390 diag::note_omp_atomic_update))
5391 return StmtError();
5392 E = Checker.getExpr();
5393 X = Checker.getX();
5394 UE = Checker.getUpdateExpr();
5395 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5396 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005397 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005398 ErrorLoc = AtomicBody->getExprLoc();
5399 ErrorRange = AtomicBody->getSourceRange();
5400 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5401 : AtomicBody->getExprLoc();
5402 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5403 : AtomicBody->getSourceRange();
5404 ErrorFound = NotAnAssignmentOp;
5405 }
5406 if (ErrorFound != NoError) {
5407 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5408 << ErrorRange;
5409 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5410 return StmtError();
5411 } else if (CurContext->isDependentContext()) {
5412 UE = V = E = X = nullptr;
5413 }
5414 } else {
5415 // If clause is a capture:
5416 // { v = x; x = expr; }
5417 // { v = x; x++; }
5418 // { v = x; x--; }
5419 // { v = x; ++x; }
5420 // { v = x; --x; }
5421 // { v = x; x binop= expr; }
5422 // { v = x; x = x binop expr; }
5423 // { v = x; x = expr binop x; }
5424 // { x++; v = x; }
5425 // { x--; v = x; }
5426 // { ++x; v = x; }
5427 // { --x; v = x; }
5428 // { x binop= expr; v = x; }
5429 // { x = x binop expr; v = x; }
5430 // { x = expr binop x; v = x; }
5431 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5432 // Check that this is { expr1; expr2; }
5433 if (CS->size() == 2) {
5434 auto *First = CS->body_front();
5435 auto *Second = CS->body_back();
5436 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5437 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5438 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5439 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5440 // Need to find what subexpression is 'v' and what is 'x'.
5441 OpenMPAtomicUpdateChecker Checker(*this);
5442 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5443 BinaryOperator *BinOp = nullptr;
5444 if (IsUpdateExprFound) {
5445 BinOp = dyn_cast<BinaryOperator>(First);
5446 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5447 }
5448 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5449 // { v = x; x++; }
5450 // { v = x; x--; }
5451 // { v = x; ++x; }
5452 // { v = x; --x; }
5453 // { v = x; x binop= expr; }
5454 // { v = x; x = x binop expr; }
5455 // { v = x; x = expr binop x; }
5456 // Check that the first expression has form v = x.
5457 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5458 llvm::FoldingSetNodeID XId, PossibleXId;
5459 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5460 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5461 IsUpdateExprFound = XId == PossibleXId;
5462 if (IsUpdateExprFound) {
5463 V = BinOp->getLHS();
5464 X = Checker.getX();
5465 E = Checker.getExpr();
5466 UE = Checker.getUpdateExpr();
5467 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005468 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005469 }
5470 }
5471 if (!IsUpdateExprFound) {
5472 IsUpdateExprFound = !Checker.checkStatement(First);
5473 BinOp = nullptr;
5474 if (IsUpdateExprFound) {
5475 BinOp = dyn_cast<BinaryOperator>(Second);
5476 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5477 }
5478 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5479 // { x++; v = x; }
5480 // { x--; v = x; }
5481 // { ++x; v = x; }
5482 // { --x; v = x; }
5483 // { x binop= expr; v = x; }
5484 // { x = x binop expr; v = x; }
5485 // { x = expr binop x; v = x; }
5486 // Check that the second expression has form v = x.
5487 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5488 llvm::FoldingSetNodeID XId, PossibleXId;
5489 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5490 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5491 IsUpdateExprFound = XId == PossibleXId;
5492 if (IsUpdateExprFound) {
5493 V = BinOp->getLHS();
5494 X = Checker.getX();
5495 E = Checker.getExpr();
5496 UE = Checker.getUpdateExpr();
5497 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005498 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005499 }
5500 }
5501 }
5502 if (!IsUpdateExprFound) {
5503 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005504 auto *FirstExpr = dyn_cast<Expr>(First);
5505 auto *SecondExpr = dyn_cast<Expr>(Second);
5506 if (!FirstExpr || !SecondExpr ||
5507 !(FirstExpr->isInstantiationDependent() ||
5508 SecondExpr->isInstantiationDependent())) {
5509 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5510 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005511 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005512 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5513 : First->getLocStart();
5514 NoteRange = ErrorRange = FirstBinOp
5515 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005516 : SourceRange(ErrorLoc, ErrorLoc);
5517 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005518 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5519 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5520 ErrorFound = NotAnAssignmentOp;
5521 NoteLoc = ErrorLoc = SecondBinOp
5522 ? SecondBinOp->getOperatorLoc()
5523 : Second->getLocStart();
5524 NoteRange = ErrorRange =
5525 SecondBinOp ? SecondBinOp->getSourceRange()
5526 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005527 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005528 auto *PossibleXRHSInFirst =
5529 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5530 auto *PossibleXLHSInSecond =
5531 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5532 llvm::FoldingSetNodeID X1Id, X2Id;
5533 PossibleXRHSInFirst->Profile(X1Id, Context,
5534 /*Canonical=*/true);
5535 PossibleXLHSInSecond->Profile(X2Id, Context,
5536 /*Canonical=*/true);
5537 IsUpdateExprFound = X1Id == X2Id;
5538 if (IsUpdateExprFound) {
5539 V = FirstBinOp->getLHS();
5540 X = SecondBinOp->getLHS();
5541 E = SecondBinOp->getRHS();
5542 UE = nullptr;
5543 IsXLHSInRHSPart = false;
5544 IsPostfixUpdate = true;
5545 } else {
5546 ErrorFound = NotASpecificExpression;
5547 ErrorLoc = FirstBinOp->getExprLoc();
5548 ErrorRange = FirstBinOp->getSourceRange();
5549 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5550 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5551 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005552 }
5553 }
5554 }
5555 }
5556 } else {
5557 NoteLoc = ErrorLoc = Body->getLocStart();
5558 NoteRange = ErrorRange =
5559 SourceRange(Body->getLocStart(), Body->getLocStart());
5560 ErrorFound = NotTwoSubstatements;
5561 }
5562 } else {
5563 NoteLoc = ErrorLoc = Body->getLocStart();
5564 NoteRange = ErrorRange =
5565 SourceRange(Body->getLocStart(), Body->getLocStart());
5566 ErrorFound = NotACompoundStatement;
5567 }
5568 if (ErrorFound != NoError) {
5569 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5570 << ErrorRange;
5571 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5572 return StmtError();
5573 } else if (CurContext->isDependentContext()) {
5574 UE = V = E = X = nullptr;
5575 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005576 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005577 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005578
5579 getCurFunction()->setHasBranchProtectedScope();
5580
Alexey Bataev62cec442014-11-18 10:14:22 +00005581 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005582 X, V, E, UE, IsXLHSInRHSPart,
5583 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005584}
5585
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005586StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5587 Stmt *AStmt,
5588 SourceLocation StartLoc,
5589 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005590 if (!AStmt)
5591 return StmtError();
5592
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005593 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5594 // 1.2.2 OpenMP Language Terminology
5595 // Structured block - An executable statement with a single entry at the
5596 // top and a single exit at the bottom.
5597 // The point of exit cannot be a branch out of the structured block.
5598 // longjmp() and throw() must not violate the entry/exit criteria.
5599 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005600
Alexey Bataev13314bf2014-10-09 04:18:56 +00005601 // OpenMP [2.16, Nesting of Regions]
5602 // If specified, a teams construct must be contained within a target
5603 // construct. That target construct must contain no statements or directives
5604 // outside of the teams construct.
5605 if (DSAStack->hasInnerTeamsRegion()) {
5606 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5607 bool OMPTeamsFound = true;
5608 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5609 auto I = CS->body_begin();
5610 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005611 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005612 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5613 OMPTeamsFound = false;
5614 break;
5615 }
5616 ++I;
5617 }
5618 assert(I != CS->body_end() && "Not found statement");
5619 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005620 } else {
5621 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5622 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005623 }
5624 if (!OMPTeamsFound) {
5625 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5626 Diag(DSAStack->getInnerTeamsRegionLoc(),
5627 diag::note_omp_nested_teams_construct_here);
5628 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5629 << isa<OMPExecutableDirective>(S);
5630 return StmtError();
5631 }
5632 }
5633
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005634 getCurFunction()->setHasBranchProtectedScope();
5635
5636 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5637}
5638
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005639StmtResult
5640Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5641 Stmt *AStmt, SourceLocation StartLoc,
5642 SourceLocation EndLoc) {
5643 if (!AStmt)
5644 return StmtError();
5645
5646 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5647 // 1.2.2 OpenMP Language Terminology
5648 // Structured block - An executable statement with a single entry at the
5649 // top and a single exit at the bottom.
5650 // The point of exit cannot be a branch out of the structured block.
5651 // longjmp() and throw() must not violate the entry/exit criteria.
5652 CS->getCapturedDecl()->setNothrow();
5653
5654 getCurFunction()->setHasBranchProtectedScope();
5655
5656 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5657 AStmt);
5658}
5659
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005660StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5661 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5662 SourceLocation EndLoc,
5663 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5664 if (!AStmt)
5665 return StmtError();
5666
5667 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5668 // 1.2.2 OpenMP Language Terminology
5669 // Structured block - An executable statement with a single entry at the
5670 // top and a single exit at the bottom.
5671 // The point of exit cannot be a branch out of the structured block.
5672 // longjmp() and throw() must not violate the entry/exit criteria.
5673 CS->getCapturedDecl()->setNothrow();
5674
5675 OMPLoopDirective::HelperExprs B;
5676 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5677 // define the nested loops number.
5678 unsigned NestedLoopCount =
5679 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5680 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5681 VarsWithImplicitDSA, B);
5682 if (NestedLoopCount == 0)
5683 return StmtError();
5684
5685 assert((CurContext->isDependentContext() || B.builtAll()) &&
5686 "omp target parallel for loop exprs were not built");
5687
5688 if (!CurContext->isDependentContext()) {
5689 // Finalize the clauses that need pre-built expressions for CodeGen.
5690 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005691 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005692 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005693 B.NumIterations, *this, CurScope,
5694 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005695 return StmtError();
5696 }
5697 }
5698
5699 getCurFunction()->setHasBranchProtectedScope();
5700 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5701 NestedLoopCount, Clauses, AStmt,
5702 B, DSAStack->isCancelRegion());
5703}
5704
Samuel Antaodf67fc42016-01-19 19:15:56 +00005705/// \brief Check for existence of a map clause in the list of clauses.
5706static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5707 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5708 I != E; ++I) {
5709 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5710 return true;
5711 }
5712 }
5713
5714 return false;
5715}
5716
Michael Wong65f367f2015-07-21 13:44:28 +00005717StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5718 Stmt *AStmt,
5719 SourceLocation StartLoc,
5720 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005721 if (!AStmt)
5722 return StmtError();
5723
5724 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5725
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005726 // OpenMP [2.10.1, Restrictions, p. 97]
5727 // At least one map clause must appear on the directive.
5728 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005729 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5730 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005731 return StmtError();
5732 }
5733
Michael Wong65f367f2015-07-21 13:44:28 +00005734 getCurFunction()->setHasBranchProtectedScope();
5735
5736 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5737 AStmt);
5738}
5739
Samuel Antaodf67fc42016-01-19 19:15:56 +00005740StmtResult
5741Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5742 SourceLocation StartLoc,
5743 SourceLocation EndLoc) {
5744 // OpenMP [2.10.2, Restrictions, p. 99]
5745 // At least one map clause must appear on the directive.
5746 if (!HasMapClause(Clauses)) {
5747 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5748 << getOpenMPDirectiveName(OMPD_target_enter_data);
5749 return StmtError();
5750 }
5751
5752 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5753 Clauses);
5754}
5755
Samuel Antao72590762016-01-19 20:04:50 +00005756StmtResult
5757Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5758 SourceLocation StartLoc,
5759 SourceLocation EndLoc) {
5760 // OpenMP [2.10.3, Restrictions, p. 102]
5761 // At least one map clause must appear on the directive.
5762 if (!HasMapClause(Clauses)) {
5763 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5764 << getOpenMPDirectiveName(OMPD_target_exit_data);
5765 return StmtError();
5766 }
5767
5768 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5769}
5770
Samuel Antao686c70c2016-05-26 17:30:50 +00005771StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5772 SourceLocation StartLoc,
5773 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005774 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005775 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005776 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005777 seenMotionClause = true;
5778 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005779 if (!seenMotionClause) {
5780 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5781 return StmtError();
5782 }
5783 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5784}
5785
Alexey Bataev13314bf2014-10-09 04:18:56 +00005786StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5787 Stmt *AStmt, SourceLocation StartLoc,
5788 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005789 if (!AStmt)
5790 return StmtError();
5791
Alexey Bataev13314bf2014-10-09 04:18:56 +00005792 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5793 // 1.2.2 OpenMP Language Terminology
5794 // Structured block - An executable statement with a single entry at the
5795 // top and a single exit at the bottom.
5796 // The point of exit cannot be a branch out of the structured block.
5797 // longjmp() and throw() must not violate the entry/exit criteria.
5798 CS->getCapturedDecl()->setNothrow();
5799
5800 getCurFunction()->setHasBranchProtectedScope();
5801
5802 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5803}
5804
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005805StmtResult
5806Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5807 SourceLocation EndLoc,
5808 OpenMPDirectiveKind CancelRegion) {
5809 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5810 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5811 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5812 << getOpenMPDirectiveName(CancelRegion);
5813 return StmtError();
5814 }
5815 if (DSAStack->isParentNowaitRegion()) {
5816 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5817 return StmtError();
5818 }
5819 if (DSAStack->isParentOrderedRegion()) {
5820 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5821 return StmtError();
5822 }
5823 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5824 CancelRegion);
5825}
5826
Alexey Bataev87933c72015-09-18 08:07:34 +00005827StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5828 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005829 SourceLocation EndLoc,
5830 OpenMPDirectiveKind CancelRegion) {
5831 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5832 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5833 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5834 << getOpenMPDirectiveName(CancelRegion);
5835 return StmtError();
5836 }
5837 if (DSAStack->isParentNowaitRegion()) {
5838 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5839 return StmtError();
5840 }
5841 if (DSAStack->isParentOrderedRegion()) {
5842 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5843 return StmtError();
5844 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005845 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005846 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5847 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005848}
5849
Alexey Bataev382967a2015-12-08 12:06:20 +00005850static bool checkGrainsizeNumTasksClauses(Sema &S,
5851 ArrayRef<OMPClause *> Clauses) {
5852 OMPClause *PrevClause = nullptr;
5853 bool ErrorFound = false;
5854 for (auto *C : Clauses) {
5855 if (C->getClauseKind() == OMPC_grainsize ||
5856 C->getClauseKind() == OMPC_num_tasks) {
5857 if (!PrevClause)
5858 PrevClause = C;
5859 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5860 S.Diag(C->getLocStart(),
5861 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5862 << getOpenMPClauseName(C->getClauseKind())
5863 << getOpenMPClauseName(PrevClause->getClauseKind());
5864 S.Diag(PrevClause->getLocStart(),
5865 diag::note_omp_previous_grainsize_num_tasks)
5866 << getOpenMPClauseName(PrevClause->getClauseKind());
5867 ErrorFound = true;
5868 }
5869 }
5870 }
5871 return ErrorFound;
5872}
5873
Alexey Bataev49f6e782015-12-01 04:18:41 +00005874StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5875 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5876 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005877 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005878 if (!AStmt)
5879 return StmtError();
5880
5881 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5882 OMPLoopDirective::HelperExprs B;
5883 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5884 // define the nested loops number.
5885 unsigned NestedLoopCount =
5886 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005887 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005888 VarsWithImplicitDSA, B);
5889 if (NestedLoopCount == 0)
5890 return StmtError();
5891
5892 assert((CurContext->isDependentContext() || B.builtAll()) &&
5893 "omp for loop exprs were not built");
5894
Alexey Bataev382967a2015-12-08 12:06:20 +00005895 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5896 // The grainsize clause and num_tasks clause are mutually exclusive and may
5897 // not appear on the same taskloop directive.
5898 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5899 return StmtError();
5900
Alexey Bataev49f6e782015-12-01 04:18:41 +00005901 getCurFunction()->setHasBranchProtectedScope();
5902 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5903 NestedLoopCount, Clauses, AStmt, B);
5904}
5905
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005906StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5907 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5908 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005909 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005910 if (!AStmt)
5911 return StmtError();
5912
5913 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5914 OMPLoopDirective::HelperExprs B;
5915 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5916 // define the nested loops number.
5917 unsigned NestedLoopCount =
5918 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5919 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5920 VarsWithImplicitDSA, B);
5921 if (NestedLoopCount == 0)
5922 return StmtError();
5923
5924 assert((CurContext->isDependentContext() || B.builtAll()) &&
5925 "omp for loop exprs were not built");
5926
Alexey Bataev5a3af132016-03-29 08:58:54 +00005927 if (!CurContext->isDependentContext()) {
5928 // Finalize the clauses that need pre-built expressions for CodeGen.
5929 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005930 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005931 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005932 B.NumIterations, *this, CurScope,
5933 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005934 return StmtError();
5935 }
5936 }
5937
Alexey Bataev382967a2015-12-08 12:06:20 +00005938 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5939 // The grainsize clause and num_tasks clause are mutually exclusive and may
5940 // not appear on the same taskloop directive.
5941 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5942 return StmtError();
5943
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005944 getCurFunction()->setHasBranchProtectedScope();
5945 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5946 NestedLoopCount, Clauses, AStmt, B);
5947}
5948
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005949StmtResult Sema::ActOnOpenMPDistributeDirective(
5950 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5951 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005952 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005953 if (!AStmt)
5954 return StmtError();
5955
5956 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5957 OMPLoopDirective::HelperExprs B;
5958 // In presence of clause 'collapse' with number of loops, it will
5959 // define the nested loops number.
5960 unsigned NestedLoopCount =
5961 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5962 nullptr /*ordered not a clause on distribute*/, AStmt,
5963 *this, *DSAStack, VarsWithImplicitDSA, B);
5964 if (NestedLoopCount == 0)
5965 return StmtError();
5966
5967 assert((CurContext->isDependentContext() || B.builtAll()) &&
5968 "omp for loop exprs were not built");
5969
5970 getCurFunction()->setHasBranchProtectedScope();
5971 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5972 NestedLoopCount, Clauses, AStmt, B);
5973}
5974
Carlo Bertolli9925f152016-06-27 14:55:37 +00005975StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5976 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5977 SourceLocation EndLoc,
5978 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5979 if (!AStmt)
5980 return StmtError();
5981
5982 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5983 // 1.2.2 OpenMP Language Terminology
5984 // Structured block - An executable statement with a single entry at the
5985 // top and a single exit at the bottom.
5986 // The point of exit cannot be a branch out of the structured block.
5987 // longjmp() and throw() must not violate the entry/exit criteria.
5988 CS->getCapturedDecl()->setNothrow();
5989
5990 OMPLoopDirective::HelperExprs B;
5991 // In presence of clause 'collapse' with number of loops, it will
5992 // define the nested loops number.
5993 unsigned NestedLoopCount = CheckOpenMPLoop(
5994 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5995 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5996 VarsWithImplicitDSA, B);
5997 if (NestedLoopCount == 0)
5998 return StmtError();
5999
6000 assert((CurContext->isDependentContext() || B.builtAll()) &&
6001 "omp for loop exprs were not built");
6002
6003 getCurFunction()->setHasBranchProtectedScope();
6004 return OMPDistributeParallelForDirective::Create(
6005 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6006}
6007
Kelvin Li4a39add2016-07-05 05:00:15 +00006008StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6009 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6010 SourceLocation EndLoc,
6011 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6012 if (!AStmt)
6013 return StmtError();
6014
6015 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6016 // 1.2.2 OpenMP Language Terminology
6017 // Structured block - An executable statement with a single entry at the
6018 // top and a single exit at the bottom.
6019 // The point of exit cannot be a branch out of the structured block.
6020 // longjmp() and throw() must not violate the entry/exit criteria.
6021 CS->getCapturedDecl()->setNothrow();
6022
6023 OMPLoopDirective::HelperExprs B;
6024 // In presence of clause 'collapse' with number of loops, it will
6025 // define the nested loops number.
6026 unsigned NestedLoopCount = CheckOpenMPLoop(
6027 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6028 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6029 VarsWithImplicitDSA, B);
6030 if (NestedLoopCount == 0)
6031 return StmtError();
6032
6033 assert((CurContext->isDependentContext() || B.builtAll()) &&
6034 "omp for loop exprs were not built");
6035
Kelvin Lic5609492016-07-15 04:39:07 +00006036 if (checkSimdlenSafelenSpecified(*this, Clauses))
6037 return StmtError();
6038
Kelvin Li4a39add2016-07-05 05:00:15 +00006039 getCurFunction()->setHasBranchProtectedScope();
6040 return OMPDistributeParallelForSimdDirective::Create(
6041 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6042}
6043
Kelvin Li787f3fc2016-07-06 04:45:38 +00006044StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6045 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6046 SourceLocation EndLoc,
6047 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6048 if (!AStmt)
6049 return StmtError();
6050
6051 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6052 // 1.2.2 OpenMP Language Terminology
6053 // Structured block - An executable statement with a single entry at the
6054 // top and a single exit at the bottom.
6055 // The point of exit cannot be a branch out of the structured block.
6056 // longjmp() and throw() must not violate the entry/exit criteria.
6057 CS->getCapturedDecl()->setNothrow();
6058
6059 OMPLoopDirective::HelperExprs B;
6060 // In presence of clause 'collapse' with number of loops, it will
6061 // define the nested loops number.
6062 unsigned NestedLoopCount =
6063 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6064 nullptr /*ordered not a clause on distribute*/, AStmt,
6065 *this, *DSAStack, VarsWithImplicitDSA, B);
6066 if (NestedLoopCount == 0)
6067 return StmtError();
6068
6069 assert((CurContext->isDependentContext() || B.builtAll()) &&
6070 "omp for loop exprs were not built");
6071
Kelvin Lic5609492016-07-15 04:39:07 +00006072 if (checkSimdlenSafelenSpecified(*this, Clauses))
6073 return StmtError();
6074
Kelvin Li787f3fc2016-07-06 04:45:38 +00006075 getCurFunction()->setHasBranchProtectedScope();
6076 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6077 NestedLoopCount, Clauses, AStmt, B);
6078}
6079
Kelvin Lia579b912016-07-14 02:54:56 +00006080StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6081 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6082 SourceLocation EndLoc,
6083 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6084 if (!AStmt)
6085 return StmtError();
6086
6087 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6088 // 1.2.2 OpenMP Language Terminology
6089 // Structured block - An executable statement with a single entry at the
6090 // top and a single exit at the bottom.
6091 // The point of exit cannot be a branch out of the structured block.
6092 // longjmp() and throw() must not violate the entry/exit criteria.
6093 CS->getCapturedDecl()->setNothrow();
6094
6095 OMPLoopDirective::HelperExprs B;
6096 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6097 // define the nested loops number.
6098 unsigned NestedLoopCount = CheckOpenMPLoop(
6099 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6100 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6101 VarsWithImplicitDSA, B);
6102 if (NestedLoopCount == 0)
6103 return StmtError();
6104
6105 assert((CurContext->isDependentContext() || B.builtAll()) &&
6106 "omp target parallel for simd loop exprs were not built");
6107
6108 if (!CurContext->isDependentContext()) {
6109 // Finalize the clauses that need pre-built expressions for CodeGen.
6110 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006111 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006112 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6113 B.NumIterations, *this, CurScope,
6114 DSAStack))
6115 return StmtError();
6116 }
6117 }
Kelvin Lic5609492016-07-15 04:39:07 +00006118 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006119 return StmtError();
6120
6121 getCurFunction()->setHasBranchProtectedScope();
6122 return OMPTargetParallelForSimdDirective::Create(
6123 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6124}
6125
Kelvin Li986330c2016-07-20 22:57:10 +00006126StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6127 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6128 SourceLocation EndLoc,
6129 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6130 if (!AStmt)
6131 return StmtError();
6132
6133 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6134 // 1.2.2 OpenMP Language Terminology
6135 // Structured block - An executable statement with a single entry at the
6136 // top and a single exit at the bottom.
6137 // The point of exit cannot be a branch out of the structured block.
6138 // longjmp() and throw() must not violate the entry/exit criteria.
6139 CS->getCapturedDecl()->setNothrow();
6140
6141 OMPLoopDirective::HelperExprs B;
6142 // In presence of clause 'collapse' with number of loops, it will define the
6143 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006144 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006145 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6146 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6147 VarsWithImplicitDSA, B);
6148 if (NestedLoopCount == 0)
6149 return StmtError();
6150
6151 assert((CurContext->isDependentContext() || B.builtAll()) &&
6152 "omp target simd loop exprs were not built");
6153
6154 if (!CurContext->isDependentContext()) {
6155 // Finalize the clauses that need pre-built expressions for CodeGen.
6156 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006157 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006158 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6159 B.NumIterations, *this, CurScope,
6160 DSAStack))
6161 return StmtError();
6162 }
6163 }
6164
6165 if (checkSimdlenSafelenSpecified(*this, Clauses))
6166 return StmtError();
6167
6168 getCurFunction()->setHasBranchProtectedScope();
6169 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6170 NestedLoopCount, Clauses, AStmt, B);
6171}
6172
Kelvin Li02532872016-08-05 14:37:37 +00006173StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6174 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6175 SourceLocation EndLoc,
6176 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6177 if (!AStmt)
6178 return StmtError();
6179
6180 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6181 // 1.2.2 OpenMP Language Terminology
6182 // Structured block - An executable statement with a single entry at the
6183 // top and a single exit at the bottom.
6184 // The point of exit cannot be a branch out of the structured block.
6185 // longjmp() and throw() must not violate the entry/exit criteria.
6186 CS->getCapturedDecl()->setNothrow();
6187
6188 OMPLoopDirective::HelperExprs B;
6189 // In presence of clause 'collapse' with number of loops, it will
6190 // define the nested loops number.
6191 unsigned NestedLoopCount =
6192 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6193 nullptr /*ordered not a clause on distribute*/, AStmt,
6194 *this, *DSAStack, VarsWithImplicitDSA, B);
6195 if (NestedLoopCount == 0)
6196 return StmtError();
6197
6198 assert((CurContext->isDependentContext() || B.builtAll()) &&
6199 "omp teams distribute loop exprs were not built");
6200
6201 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006202 return OMPTeamsDistributeDirective::Create(
6203 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006204}
6205
Kelvin Li4e325f72016-10-25 12:50:55 +00006206StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6207 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6208 SourceLocation EndLoc,
6209 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6210 if (!AStmt)
6211 return StmtError();
6212
6213 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6214 // 1.2.2 OpenMP Language Terminology
6215 // Structured block - An executable statement with a single entry at the
6216 // top and a single exit at the bottom.
6217 // The point of exit cannot be a branch out of the structured block.
6218 // longjmp() and throw() must not violate the entry/exit criteria.
6219 CS->getCapturedDecl()->setNothrow();
6220
6221 OMPLoopDirective::HelperExprs B;
6222 // In presence of clause 'collapse' with number of loops, it will
6223 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006224 unsigned NestedLoopCount = CheckOpenMPLoop(
6225 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6226 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6227 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006228
6229 if (NestedLoopCount == 0)
6230 return StmtError();
6231
6232 assert((CurContext->isDependentContext() || B.builtAll()) &&
6233 "omp teams distribute simd loop exprs were not built");
6234
6235 if (!CurContext->isDependentContext()) {
6236 // Finalize the clauses that need pre-built expressions for CodeGen.
6237 for (auto C : Clauses) {
6238 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6239 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6240 B.NumIterations, *this, CurScope,
6241 DSAStack))
6242 return StmtError();
6243 }
6244 }
6245
6246 if (checkSimdlenSafelenSpecified(*this, Clauses))
6247 return StmtError();
6248
6249 getCurFunction()->setHasBranchProtectedScope();
6250 return OMPTeamsDistributeSimdDirective::Create(
6251 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6252}
6253
Kelvin Li579e41c2016-11-30 23:51:03 +00006254StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6255 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6256 SourceLocation EndLoc,
6257 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6258 if (!AStmt)
6259 return StmtError();
6260
6261 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6262 // 1.2.2 OpenMP Language Terminology
6263 // Structured block - An executable statement with a single entry at the
6264 // top and a single exit at the bottom.
6265 // The point of exit cannot be a branch out of the structured block.
6266 // longjmp() and throw() must not violate the entry/exit criteria.
6267 CS->getCapturedDecl()->setNothrow();
6268
6269 OMPLoopDirective::HelperExprs B;
6270 // In presence of clause 'collapse' with number of loops, it will
6271 // define the nested loops number.
6272 auto NestedLoopCount = CheckOpenMPLoop(
6273 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6274 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6275 VarsWithImplicitDSA, B);
6276
6277 if (NestedLoopCount == 0)
6278 return StmtError();
6279
6280 assert((CurContext->isDependentContext() || B.builtAll()) &&
6281 "omp for loop exprs were not built");
6282
6283 if (!CurContext->isDependentContext()) {
6284 // Finalize the clauses that need pre-built expressions for CodeGen.
6285 for (auto C : Clauses) {
6286 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6287 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6288 B.NumIterations, *this, CurScope,
6289 DSAStack))
6290 return StmtError();
6291 }
6292 }
6293
6294 if (checkSimdlenSafelenSpecified(*this, Clauses))
6295 return StmtError();
6296
6297 getCurFunction()->setHasBranchProtectedScope();
6298 return OMPTeamsDistributeParallelForSimdDirective::Create(
6299 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6300}
6301
Kelvin Li7ade93f2016-12-09 03:24:30 +00006302StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6303 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6304 SourceLocation EndLoc,
6305 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6306 if (!AStmt)
6307 return StmtError();
6308
6309 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6310 // 1.2.2 OpenMP Language Terminology
6311 // Structured block - An executable statement with a single entry at the
6312 // top and a single exit at the bottom.
6313 // The point of exit cannot be a branch out of the structured block.
6314 // longjmp() and throw() must not violate the entry/exit criteria.
6315 CS->getCapturedDecl()->setNothrow();
6316
6317 OMPLoopDirective::HelperExprs B;
6318 // In presence of clause 'collapse' with number of loops, it will
6319 // define the nested loops number.
6320 unsigned NestedLoopCount = CheckOpenMPLoop(
6321 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6322 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6323 VarsWithImplicitDSA, B);
6324
6325 if (NestedLoopCount == 0)
6326 return StmtError();
6327
6328 assert((CurContext->isDependentContext() || B.builtAll()) &&
6329 "omp for loop exprs were not built");
6330
6331 if (!CurContext->isDependentContext()) {
6332 // Finalize the clauses that need pre-built expressions for CodeGen.
6333 for (auto C : Clauses) {
6334 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6335 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6336 B.NumIterations, *this, CurScope,
6337 DSAStack))
6338 return StmtError();
6339 }
6340 }
6341
6342 getCurFunction()->setHasBranchProtectedScope();
6343 return OMPTeamsDistributeParallelForDirective::Create(
6344 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6345}
6346
Kelvin Libf594a52016-12-17 05:48:59 +00006347StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6348 Stmt *AStmt,
6349 SourceLocation StartLoc,
6350 SourceLocation EndLoc) {
6351 if (!AStmt)
6352 return StmtError();
6353
6354 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6355 // 1.2.2 OpenMP Language Terminology
6356 // Structured block - An executable statement with a single entry at the
6357 // top and a single exit at the bottom.
6358 // The point of exit cannot be a branch out of the structured block.
6359 // longjmp() and throw() must not violate the entry/exit criteria.
6360 CS->getCapturedDecl()->setNothrow();
6361
6362 getCurFunction()->setHasBranchProtectedScope();
6363
6364 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6365 AStmt);
6366}
6367
Kelvin Li83c451e2016-12-25 04:52:54 +00006368StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6369 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6370 SourceLocation EndLoc,
6371 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6372 if (!AStmt)
6373 return StmtError();
6374
6375 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6376 // 1.2.2 OpenMP Language Terminology
6377 // Structured block - An executable statement with a single entry at the
6378 // top and a single exit at the bottom.
6379 // The point of exit cannot be a branch out of the structured block.
6380 // longjmp() and throw() must not violate the entry/exit criteria.
6381 CS->getCapturedDecl()->setNothrow();
6382
6383 OMPLoopDirective::HelperExprs B;
6384 // In presence of clause 'collapse' with number of loops, it will
6385 // define the nested loops number.
6386 auto NestedLoopCount = CheckOpenMPLoop(
6387 OMPD_target_teams_distribute,
6388 getCollapseNumberExpr(Clauses),
6389 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6390 VarsWithImplicitDSA, B);
6391 if (NestedLoopCount == 0)
6392 return StmtError();
6393
6394 assert((CurContext->isDependentContext() || B.builtAll()) &&
6395 "omp target teams distribute loop exprs were not built");
6396
6397 getCurFunction()->setHasBranchProtectedScope();
6398 return OMPTargetTeamsDistributeDirective::Create(
6399 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6400}
6401
Kelvin Li80e8f562016-12-29 22:16:30 +00006402StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6403 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6404 SourceLocation EndLoc,
6405 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6406 if (!AStmt)
6407 return StmtError();
6408
6409 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6410 // 1.2.2 OpenMP Language Terminology
6411 // Structured block - An executable statement with a single entry at the
6412 // top and a single exit at the bottom.
6413 // The point of exit cannot be a branch out of the structured block.
6414 // longjmp() and throw() must not violate the entry/exit criteria.
6415 CS->getCapturedDecl()->setNothrow();
6416
6417 OMPLoopDirective::HelperExprs B;
6418 // In presence of clause 'collapse' with number of loops, it will
6419 // define the nested loops number.
6420 auto NestedLoopCount = CheckOpenMPLoop(
6421 OMPD_target_teams_distribute_parallel_for,
6422 getCollapseNumberExpr(Clauses),
6423 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6424 VarsWithImplicitDSA, B);
6425 if (NestedLoopCount == 0)
6426 return StmtError();
6427
6428 assert((CurContext->isDependentContext() || B.builtAll()) &&
6429 "omp target teams distribute parallel for loop exprs were not built");
6430
6431 if (!CurContext->isDependentContext()) {
6432 // Finalize the clauses that need pre-built expressions for CodeGen.
6433 for (auto C : Clauses) {
6434 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6435 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6436 B.NumIterations, *this, CurScope,
6437 DSAStack))
6438 return StmtError();
6439 }
6440 }
6441
6442 getCurFunction()->setHasBranchProtectedScope();
6443 return OMPTargetTeamsDistributeParallelForDirective::Create(
6444 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6445}
6446
Kelvin Li1851df52017-01-03 05:23:48 +00006447StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6448 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6449 SourceLocation EndLoc,
6450 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6451 if (!AStmt)
6452 return StmtError();
6453
6454 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6455 // 1.2.2 OpenMP Language Terminology
6456 // Structured block - An executable statement with a single entry at the
6457 // top and a single exit at the bottom.
6458 // The point of exit cannot be a branch out of the structured block.
6459 // longjmp() and throw() must not violate the entry/exit criteria.
6460 CS->getCapturedDecl()->setNothrow();
6461
6462 OMPLoopDirective::HelperExprs B;
6463 // In presence of clause 'collapse' with number of loops, it will
6464 // define the nested loops number.
6465 auto NestedLoopCount = CheckOpenMPLoop(
6466 OMPD_target_teams_distribute_parallel_for_simd,
6467 getCollapseNumberExpr(Clauses),
6468 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6469 VarsWithImplicitDSA, B);
6470 if (NestedLoopCount == 0)
6471 return StmtError();
6472
6473 assert((CurContext->isDependentContext() || B.builtAll()) &&
6474 "omp target teams distribute parallel for simd loop exprs were not "
6475 "built");
6476
6477 if (!CurContext->isDependentContext()) {
6478 // Finalize the clauses that need pre-built expressions for CodeGen.
6479 for (auto C : Clauses) {
6480 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6481 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6482 B.NumIterations, *this, CurScope,
6483 DSAStack))
6484 return StmtError();
6485 }
6486 }
6487
6488 getCurFunction()->setHasBranchProtectedScope();
6489 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6490 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6491}
6492
Kelvin Lida681182017-01-10 18:08:18 +00006493StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6494 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6495 SourceLocation EndLoc,
6496 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6497 if (!AStmt)
6498 return StmtError();
6499
6500 auto *CS = cast<CapturedStmt>(AStmt);
6501 // 1.2.2 OpenMP Language Terminology
6502 // Structured block - An executable statement with a single entry at the
6503 // top and a single exit at the bottom.
6504 // The point of exit cannot be a branch out of the structured block.
6505 // longjmp() and throw() must not violate the entry/exit criteria.
6506 CS->getCapturedDecl()->setNothrow();
6507
6508 OMPLoopDirective::HelperExprs B;
6509 // In presence of clause 'collapse' with number of loops, it will
6510 // define the nested loops number.
6511 auto NestedLoopCount = CheckOpenMPLoop(
6512 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6513 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6514 VarsWithImplicitDSA, B);
6515 if (NestedLoopCount == 0)
6516 return StmtError();
6517
6518 assert((CurContext->isDependentContext() || B.builtAll()) &&
6519 "omp target teams distribute simd loop exprs were not built");
6520
6521 getCurFunction()->setHasBranchProtectedScope();
6522 return OMPTargetTeamsDistributeSimdDirective::Create(
6523 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6524}
6525
Alexey Bataeved09d242014-05-28 05:53:51 +00006526OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006527 SourceLocation StartLoc,
6528 SourceLocation LParenLoc,
6529 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006530 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006531 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006532 case OMPC_final:
6533 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6534 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006535 case OMPC_num_threads:
6536 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6537 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006538 case OMPC_safelen:
6539 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6540 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006541 case OMPC_simdlen:
6542 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6543 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006544 case OMPC_collapse:
6545 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6546 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006547 case OMPC_ordered:
6548 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6549 break;
Michael Wonge710d542015-08-07 16:16:36 +00006550 case OMPC_device:
6551 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6552 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006553 case OMPC_num_teams:
6554 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6555 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006556 case OMPC_thread_limit:
6557 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6558 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006559 case OMPC_priority:
6560 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6561 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006562 case OMPC_grainsize:
6563 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6564 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006565 case OMPC_num_tasks:
6566 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6567 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006568 case OMPC_hint:
6569 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6570 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006571 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006572 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006573 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006574 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006575 case OMPC_private:
6576 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006577 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006578 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006579 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006580 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006581 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006582 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006583 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006584 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006585 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006586 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006587 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006588 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006589 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006590 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006591 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006592 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006593 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006594 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006595 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006596 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006597 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006598 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006599 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006600 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006601 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006602 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006603 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006604 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006605 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006606 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006607 llvm_unreachable("Clause is not allowed.");
6608 }
6609 return Res;
6610}
6611
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006612OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6613 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006614 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006615 SourceLocation NameModifierLoc,
6616 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006617 SourceLocation EndLoc) {
6618 Expr *ValExpr = Condition;
6619 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6620 !Condition->isInstantiationDependent() &&
6621 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006622 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006623 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006624 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006625
Richard Smith03a4aa32016-06-23 19:02:52 +00006626 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006627 }
6628
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006629 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6630 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006631}
6632
Alexey Bataev3778b602014-07-17 07:32:53 +00006633OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6634 SourceLocation StartLoc,
6635 SourceLocation LParenLoc,
6636 SourceLocation EndLoc) {
6637 Expr *ValExpr = Condition;
6638 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6639 !Condition->isInstantiationDependent() &&
6640 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006641 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006642 if (Val.isInvalid())
6643 return nullptr;
6644
Richard Smith03a4aa32016-06-23 19:02:52 +00006645 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006646 }
6647
6648 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6649}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006650ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6651 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006652 if (!Op)
6653 return ExprError();
6654
6655 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6656 public:
6657 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006658 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006659 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6660 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006661 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6662 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006663 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6664 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006665 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6666 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006667 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6668 QualType T,
6669 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006670 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6671 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006672 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6673 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006674 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006675 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006676 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006677 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6678 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006679 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6680 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006681 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6682 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006683 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006684 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006685 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006686 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6687 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006688 llvm_unreachable("conversion functions are permitted");
6689 }
6690 } ConvertDiagnoser;
6691 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6692}
6693
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006694static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006695 OpenMPClauseKind CKind,
6696 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006697 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6698 !ValExpr->isInstantiationDependent()) {
6699 SourceLocation Loc = ValExpr->getExprLoc();
6700 ExprResult Value =
6701 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6702 if (Value.isInvalid())
6703 return false;
6704
6705 ValExpr = Value.get();
6706 // The expression must evaluate to a non-negative integer value.
6707 llvm::APSInt Result;
6708 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006709 Result.isSigned() &&
6710 !((!StrictlyPositive && Result.isNonNegative()) ||
6711 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006712 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006713 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6714 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006715 return false;
6716 }
6717 }
6718 return true;
6719}
6720
Alexey Bataev568a8332014-03-06 06:15:19 +00006721OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6722 SourceLocation StartLoc,
6723 SourceLocation LParenLoc,
6724 SourceLocation EndLoc) {
6725 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006726
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006727 // OpenMP [2.5, Restrictions]
6728 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006729 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6730 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006731 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006732
Alexey Bataeved09d242014-05-28 05:53:51 +00006733 return new (Context)
6734 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006735}
6736
Alexey Bataev62c87d22014-03-21 04:51:18 +00006737ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006738 OpenMPClauseKind CKind,
6739 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006740 if (!E)
6741 return ExprError();
6742 if (E->isValueDependent() || E->isTypeDependent() ||
6743 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006744 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006745 llvm::APSInt Result;
6746 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6747 if (ICE.isInvalid())
6748 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006749 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6750 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006751 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006752 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6753 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006754 return ExprError();
6755 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006756 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6757 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6758 << E->getSourceRange();
6759 return ExprError();
6760 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006761 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6762 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006763 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006764 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006765 return ICE;
6766}
6767
6768OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6769 SourceLocation LParenLoc,
6770 SourceLocation EndLoc) {
6771 // OpenMP [2.8.1, simd construct, Description]
6772 // The parameter of the safelen clause must be a constant
6773 // positive integer expression.
6774 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6775 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006776 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006777 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006778 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006779}
6780
Alexey Bataev66b15b52015-08-21 11:14:16 +00006781OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6782 SourceLocation LParenLoc,
6783 SourceLocation EndLoc) {
6784 // OpenMP [2.8.1, simd construct, Description]
6785 // The parameter of the simdlen clause must be a constant
6786 // positive integer expression.
6787 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6788 if (Simdlen.isInvalid())
6789 return nullptr;
6790 return new (Context)
6791 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6792}
6793
Alexander Musman64d33f12014-06-04 07:53:32 +00006794OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6795 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006796 SourceLocation LParenLoc,
6797 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006798 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006799 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006800 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006801 // The parameter of the collapse clause must be a constant
6802 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006803 ExprResult NumForLoopsResult =
6804 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6805 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006806 return nullptr;
6807 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006808 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006809}
6810
Alexey Bataev10e775f2015-07-30 11:36:16 +00006811OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6812 SourceLocation EndLoc,
6813 SourceLocation LParenLoc,
6814 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006815 // OpenMP [2.7.1, loop construct, Description]
6816 // OpenMP [2.8.1, simd construct, Description]
6817 // OpenMP [2.9.6, distribute construct, Description]
6818 // The parameter of the ordered clause must be a constant
6819 // positive integer expression if any.
6820 if (NumForLoops && LParenLoc.isValid()) {
6821 ExprResult NumForLoopsResult =
6822 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6823 if (NumForLoopsResult.isInvalid())
6824 return nullptr;
6825 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006826 } else
6827 NumForLoops = nullptr;
6828 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006829 return new (Context)
6830 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6831}
6832
Alexey Bataeved09d242014-05-28 05:53:51 +00006833OMPClause *Sema::ActOnOpenMPSimpleClause(
6834 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6835 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006836 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006837 switch (Kind) {
6838 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006839 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006840 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6841 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006842 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006843 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006844 Res = ActOnOpenMPProcBindClause(
6845 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6846 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006847 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006848 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006849 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006850 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006851 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006852 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006853 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006854 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006855 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006856 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006857 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006858 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006859 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006860 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006861 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006862 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006863 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006864 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006865 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006866 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006867 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006868 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006869 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006870 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006871 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006872 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006873 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006874 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006875 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006876 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006877 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006878 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006879 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006880 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006881 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006882 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006883 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006884 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006885 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006886 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006887 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006888 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006889 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006890 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006891 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006892 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006893 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006894 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006895 llvm_unreachable("Clause is not allowed.");
6896 }
6897 return Res;
6898}
6899
Alexey Bataev6402bca2015-12-28 07:25:51 +00006900static std::string
6901getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6902 ArrayRef<unsigned> Exclude = llvm::None) {
6903 std::string Values;
6904 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6905 unsigned Skipped = Exclude.size();
6906 auto S = Exclude.begin(), E = Exclude.end();
6907 for (unsigned i = First; i < Last; ++i) {
6908 if (std::find(S, E, i) != E) {
6909 --Skipped;
6910 continue;
6911 }
6912 Values += "'";
6913 Values += getOpenMPSimpleClauseTypeName(K, i);
6914 Values += "'";
6915 if (i == Bound - Skipped)
6916 Values += " or ";
6917 else if (i != Bound + 1 - Skipped)
6918 Values += ", ";
6919 }
6920 return Values;
6921}
6922
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006923OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6924 SourceLocation KindKwLoc,
6925 SourceLocation StartLoc,
6926 SourceLocation LParenLoc,
6927 SourceLocation EndLoc) {
6928 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006929 static_assert(OMPC_DEFAULT_unknown > 0,
6930 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006931 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006932 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6933 /*Last=*/OMPC_DEFAULT_unknown)
6934 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006935 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006936 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006937 switch (Kind) {
6938 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006939 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006940 break;
6941 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006942 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006943 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006944 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006945 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006946 break;
6947 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006948 return new (Context)
6949 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006950}
6951
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006952OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6953 SourceLocation KindKwLoc,
6954 SourceLocation StartLoc,
6955 SourceLocation LParenLoc,
6956 SourceLocation EndLoc) {
6957 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006958 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006959 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6960 /*Last=*/OMPC_PROC_BIND_unknown)
6961 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006962 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006963 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006964 return new (Context)
6965 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006966}
6967
Alexey Bataev56dafe82014-06-20 07:16:17 +00006968OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006969 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006970 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006971 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006972 SourceLocation EndLoc) {
6973 OMPClause *Res = nullptr;
6974 switch (Kind) {
6975 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006976 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6977 assert(Argument.size() == NumberOfElements &&
6978 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006979 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006980 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6981 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6982 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6983 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6984 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006985 break;
6986 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006987 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6988 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6989 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6990 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006991 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006992 case OMPC_dist_schedule:
6993 Res = ActOnOpenMPDistScheduleClause(
6994 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6995 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6996 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006997 case OMPC_defaultmap:
6998 enum { Modifier, DefaultmapKind };
6999 Res = ActOnOpenMPDefaultmapClause(
7000 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7001 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007002 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7003 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007004 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007005 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007006 case OMPC_num_threads:
7007 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007008 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007009 case OMPC_collapse:
7010 case OMPC_default:
7011 case OMPC_proc_bind:
7012 case OMPC_private:
7013 case OMPC_firstprivate:
7014 case OMPC_lastprivate:
7015 case OMPC_shared:
7016 case OMPC_reduction:
7017 case OMPC_linear:
7018 case OMPC_aligned:
7019 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007020 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007021 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007022 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007023 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007024 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007025 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007026 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007027 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007028 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007029 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007030 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007031 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007032 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007033 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007034 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007035 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007036 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007037 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007038 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007039 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007040 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007041 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007042 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007043 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007044 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007045 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007046 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007047 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007048 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007049 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007050 llvm_unreachable("Clause is not allowed.");
7051 }
7052 return Res;
7053}
7054
Alexey Bataev6402bca2015-12-28 07:25:51 +00007055static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7056 OpenMPScheduleClauseModifier M2,
7057 SourceLocation M1Loc, SourceLocation M2Loc) {
7058 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7059 SmallVector<unsigned, 2> Excluded;
7060 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7061 Excluded.push_back(M2);
7062 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7063 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7064 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7065 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7066 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7067 << getListOfPossibleValues(OMPC_schedule,
7068 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7069 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7070 Excluded)
7071 << getOpenMPClauseName(OMPC_schedule);
7072 return true;
7073 }
7074 return false;
7075}
7076
Alexey Bataev56dafe82014-06-20 07:16:17 +00007077OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007078 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007079 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007080 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7081 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7082 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7083 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7084 return nullptr;
7085 // OpenMP, 2.7.1, Loop Construct, Restrictions
7086 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7087 // but not both.
7088 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7089 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7090 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7091 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7092 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7093 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7094 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7095 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7096 return nullptr;
7097 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007098 if (Kind == OMPC_SCHEDULE_unknown) {
7099 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007100 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7101 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7102 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7103 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7104 Exclude);
7105 } else {
7106 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7107 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007108 }
7109 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7110 << Values << getOpenMPClauseName(OMPC_schedule);
7111 return nullptr;
7112 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007113 // OpenMP, 2.7.1, Loop Construct, Restrictions
7114 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7115 // schedule(guided).
7116 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7117 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7118 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7119 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7120 diag::err_omp_schedule_nonmonotonic_static);
7121 return nullptr;
7122 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007123 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007124 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007125 if (ChunkSize) {
7126 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7127 !ChunkSize->isInstantiationDependent() &&
7128 !ChunkSize->containsUnexpandedParameterPack()) {
7129 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7130 ExprResult Val =
7131 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7132 if (Val.isInvalid())
7133 return nullptr;
7134
7135 ValExpr = Val.get();
7136
7137 // OpenMP [2.7.1, Restrictions]
7138 // chunk_size must be a loop invariant integer expression with a positive
7139 // value.
7140 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007141 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7142 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7143 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007144 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007145 return nullptr;
7146 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007147 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7148 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007149 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7150 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7151 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007152 }
7153 }
7154 }
7155
Alexey Bataev6402bca2015-12-28 07:25:51 +00007156 return new (Context)
7157 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007158 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007159}
7160
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007161OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7162 SourceLocation StartLoc,
7163 SourceLocation EndLoc) {
7164 OMPClause *Res = nullptr;
7165 switch (Kind) {
7166 case OMPC_ordered:
7167 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7168 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007169 case OMPC_nowait:
7170 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7171 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007172 case OMPC_untied:
7173 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7174 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007175 case OMPC_mergeable:
7176 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7177 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007178 case OMPC_read:
7179 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7180 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007181 case OMPC_write:
7182 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7183 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007184 case OMPC_update:
7185 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7186 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007187 case OMPC_capture:
7188 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7189 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007190 case OMPC_seq_cst:
7191 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7192 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007193 case OMPC_threads:
7194 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7195 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007196 case OMPC_simd:
7197 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7198 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007199 case OMPC_nogroup:
7200 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7201 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007202 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007203 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007204 case OMPC_num_threads:
7205 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007206 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007207 case OMPC_collapse:
7208 case OMPC_schedule:
7209 case OMPC_private:
7210 case OMPC_firstprivate:
7211 case OMPC_lastprivate:
7212 case OMPC_shared:
7213 case OMPC_reduction:
7214 case OMPC_linear:
7215 case OMPC_aligned:
7216 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007217 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007218 case OMPC_default:
7219 case OMPC_proc_bind:
7220 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007221 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007222 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007223 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007224 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007225 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007226 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007227 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007228 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007229 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007230 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007231 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007232 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007233 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007234 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007235 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007236 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007237 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007238 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007239 llvm_unreachable("Clause is not allowed.");
7240 }
7241 return Res;
7242}
7243
Alexey Bataev236070f2014-06-20 11:19:47 +00007244OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7245 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007246 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007247 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7248}
7249
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007250OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7251 SourceLocation EndLoc) {
7252 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7253}
7254
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007255OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7256 SourceLocation EndLoc) {
7257 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7258}
7259
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007260OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7261 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007262 return new (Context) OMPReadClause(StartLoc, EndLoc);
7263}
7264
Alexey Bataevdea47612014-07-23 07:46:59 +00007265OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7266 SourceLocation EndLoc) {
7267 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7268}
7269
Alexey Bataev67a4f222014-07-23 10:25:33 +00007270OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7271 SourceLocation EndLoc) {
7272 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7273}
7274
Alexey Bataev459dec02014-07-24 06:46:57 +00007275OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7276 SourceLocation EndLoc) {
7277 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7278}
7279
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007280OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7281 SourceLocation EndLoc) {
7282 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7283}
7284
Alexey Bataev346265e2015-09-25 10:37:12 +00007285OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7286 SourceLocation EndLoc) {
7287 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7288}
7289
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007290OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7291 SourceLocation EndLoc) {
7292 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7293}
7294
Alexey Bataevb825de12015-12-07 10:51:44 +00007295OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7296 SourceLocation EndLoc) {
7297 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7298}
7299
Alexey Bataevc5e02582014-06-16 07:08:35 +00007300OMPClause *Sema::ActOnOpenMPVarListClause(
7301 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7302 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7303 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007304 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007305 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7306 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7307 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007308 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007309 switch (Kind) {
7310 case OMPC_private:
7311 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7312 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007313 case OMPC_firstprivate:
7314 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7315 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007316 case OMPC_lastprivate:
7317 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7318 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007319 case OMPC_shared:
7320 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7321 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007322 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007323 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7324 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007325 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007326 case OMPC_linear:
7327 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007328 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007329 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007330 case OMPC_aligned:
7331 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7332 ColonLoc, EndLoc);
7333 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007334 case OMPC_copyin:
7335 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7336 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007337 case OMPC_copyprivate:
7338 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7339 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007340 case OMPC_flush:
7341 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7342 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007343 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007344 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007345 StartLoc, LParenLoc, EndLoc);
7346 break;
7347 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007348 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7349 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7350 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007351 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007352 case OMPC_to:
7353 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7354 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007355 case OMPC_from:
7356 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7357 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007358 case OMPC_use_device_ptr:
7359 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7360 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007361 case OMPC_is_device_ptr:
7362 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7363 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007364 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007365 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007366 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007367 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007368 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007369 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007370 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007371 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007372 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007373 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007374 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007375 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007376 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007377 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007378 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007379 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007380 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007381 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007382 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007383 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007384 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007385 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007386 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007387 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007388 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007389 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007390 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007391 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007392 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007393 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007394 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007395 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007396 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007397 llvm_unreachable("Clause is not allowed.");
7398 }
7399 return Res;
7400}
7401
Alexey Bataev90c228f2016-02-08 09:29:13 +00007402ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007403 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007404 ExprResult Res = BuildDeclRefExpr(
7405 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7406 if (!Res.isUsable())
7407 return ExprError();
7408 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7409 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7410 if (!Res.isUsable())
7411 return ExprError();
7412 }
7413 if (VK != VK_LValue && Res.get()->isGLValue()) {
7414 Res = DefaultLvalueConversion(Res.get());
7415 if (!Res.isUsable())
7416 return ExprError();
7417 }
7418 return Res;
7419}
7420
Alexey Bataev60da77e2016-02-29 05:54:20 +00007421static std::pair<ValueDecl *, bool>
7422getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7423 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007424 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7425 RefExpr->containsUnexpandedParameterPack())
7426 return std::make_pair(nullptr, true);
7427
Alexey Bataevd985eda2016-02-10 11:29:16 +00007428 // OpenMP [3.1, C/C++]
7429 // A list item is a variable name.
7430 // OpenMP [2.9.3.3, Restrictions, p.1]
7431 // A variable that is part of another variable (as an array or
7432 // structure element) cannot appear in a private clause.
7433 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007434 enum {
7435 NoArrayExpr = -1,
7436 ArraySubscript = 0,
7437 OMPArraySection = 1
7438 } IsArrayExpr = NoArrayExpr;
7439 if (AllowArraySection) {
7440 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7441 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7442 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7443 Base = TempASE->getBase()->IgnoreParenImpCasts();
7444 RefExpr = Base;
7445 IsArrayExpr = ArraySubscript;
7446 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7447 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7448 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7449 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7450 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7451 Base = TempASE->getBase()->IgnoreParenImpCasts();
7452 RefExpr = Base;
7453 IsArrayExpr = OMPArraySection;
7454 }
7455 }
7456 ELoc = RefExpr->getExprLoc();
7457 ERange = RefExpr->getSourceRange();
7458 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007459 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7460 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7461 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7462 (S.getCurrentThisType().isNull() || !ME ||
7463 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7464 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007465 if (IsArrayExpr != NoArrayExpr)
7466 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7467 << ERange;
7468 else {
7469 S.Diag(ELoc,
7470 AllowArraySection
7471 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7472 : diag::err_omp_expected_var_name_member_expr)
7473 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7474 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007475 return std::make_pair(nullptr, false);
7476 }
7477 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7478}
7479
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007480OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7481 SourceLocation StartLoc,
7482 SourceLocation LParenLoc,
7483 SourceLocation EndLoc) {
7484 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007485 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007486 for (auto &RefExpr : VarList) {
7487 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007488 SourceLocation ELoc;
7489 SourceRange ERange;
7490 Expr *SimpleRefExpr = RefExpr;
7491 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007492 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007493 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007494 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007495 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007496 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007497 ValueDecl *D = Res.first;
7498 if (!D)
7499 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007500
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007501 QualType Type = D->getType();
7502 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007503
7504 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7505 // A variable that appears in a private clause must not have an incomplete
7506 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007507 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007508 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007509 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007510
Alexey Bataev758e55e2013-09-06 18:03:48 +00007511 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7512 // in a Construct]
7513 // Variables with the predetermined data-sharing attributes may not be
7514 // listed in data-sharing attributes clauses, except for the cases
7515 // listed below. For these exceptions only, listing a predetermined
7516 // variable in a data-sharing attribute clause is allowed and overrides
7517 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007518 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007519 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007520 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7521 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007522 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007523 continue;
7524 }
7525
Kelvin Libf594a52016-12-17 05:48:59 +00007526 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007527 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007528 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007529 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007530 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7531 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007532 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007533 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007534 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007535 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007536 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007537 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007538 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007539 continue;
7540 }
7541
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007542 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7543 // A list item cannot appear in both a map clause and a data-sharing
7544 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007545 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007546 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007547 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007548 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007549 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007550 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007551 CurrDir == OMPD_target_parallel_for_simd ||
7552 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007553 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007554 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007555 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007556 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7557 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7558 ConflictKind = WhereFoundClauseKind;
7559 return true;
7560 })) {
7561 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007562 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007563 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007564 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007565 ReportOriginalDSA(*this, DSAStack, D, DVar);
7566 continue;
7567 }
7568 }
7569
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007570 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7571 // A variable of class type (or array thereof) that appears in a private
7572 // clause requires an accessible, unambiguous default constructor for the
7573 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007574 // Generate helper private variable and initialize it with the default
7575 // value. The address of the original variable is replaced by the address of
7576 // the new private variable in CodeGen. This new variable is not added to
7577 // IdResolver, so the code in the OpenMP region uses original variable for
7578 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007579 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007580 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7581 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00007582 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007583 if (VDPrivate->isInvalidDecl())
7584 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007585 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007586 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007587
Alexey Bataev90c228f2016-02-08 09:29:13 +00007588 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007589 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007590 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007591 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007592 Vars.push_back((VD || CurContext->isDependentContext())
7593 ? RefExpr->IgnoreParens()
7594 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007595 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007596 }
7597
Alexey Bataeved09d242014-05-28 05:53:51 +00007598 if (Vars.empty())
7599 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007600
Alexey Bataev03b340a2014-10-21 03:16:40 +00007601 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7602 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007603}
7604
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007605namespace {
7606class DiagsUninitializedSeveretyRAII {
7607private:
7608 DiagnosticsEngine &Diags;
7609 SourceLocation SavedLoc;
7610 bool IsIgnored;
7611
7612public:
7613 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7614 bool IsIgnored)
7615 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7616 if (!IsIgnored) {
7617 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7618 /*Map*/ diag::Severity::Ignored, Loc);
7619 }
7620 }
7621 ~DiagsUninitializedSeveretyRAII() {
7622 if (!IsIgnored)
7623 Diags.popMappings(SavedLoc);
7624 }
7625};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007626}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007627
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007628OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7629 SourceLocation StartLoc,
7630 SourceLocation LParenLoc,
7631 SourceLocation EndLoc) {
7632 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007633 SmallVector<Expr *, 8> PrivateCopies;
7634 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007635 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007636 bool IsImplicitClause =
7637 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7638 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7639
Alexey Bataeved09d242014-05-28 05:53:51 +00007640 for (auto &RefExpr : VarList) {
7641 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007642 SourceLocation ELoc;
7643 SourceRange ERange;
7644 Expr *SimpleRefExpr = RefExpr;
7645 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007646 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007647 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007648 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007649 PrivateCopies.push_back(nullptr);
7650 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007651 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007652 ValueDecl *D = Res.first;
7653 if (!D)
7654 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007655
Alexey Bataev60da77e2016-02-29 05:54:20 +00007656 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007657 QualType Type = D->getType();
7658 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007659
7660 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7661 // A variable that appears in a private clause must not have an incomplete
7662 // type or a reference type.
7663 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007664 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007665 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007666 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007667
7668 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7669 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007670 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007671 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007672 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007673
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007674 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007675 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007676 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007677 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007678 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007679 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007680 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7681 // A list item that specifies a given variable may not appear in more
7682 // than one clause on the same directive, except that a variable may be
7683 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007684 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007685 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007686 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007687 << getOpenMPClauseName(DVar.CKind)
7688 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007689 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007690 continue;
7691 }
7692
7693 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7694 // in a Construct]
7695 // Variables with the predetermined data-sharing attributes may not be
7696 // listed in data-sharing attributes clauses, except for the cases
7697 // listed below. For these exceptions only, listing a predetermined
7698 // variable in a data-sharing attribute clause is allowed and overrides
7699 // the variable's predetermined data-sharing attributes.
7700 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7701 // in a Construct, C/C++, p.2]
7702 // Variables with const-qualified type having no mutable member may be
7703 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007704 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007705 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7706 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007707 << getOpenMPClauseName(DVar.CKind)
7708 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007709 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007710 continue;
7711 }
7712
Alexey Bataevf29276e2014-06-18 04:14:57 +00007713 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007714 // OpenMP [2.9.3.4, Restrictions, p.2]
7715 // A list item that is private within a parallel region must not appear
7716 // in a firstprivate clause on a worksharing construct if any of the
7717 // worksharing regions arising from the worksharing construct ever bind
7718 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007719 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007720 !isOpenMPParallelDirective(CurrDir) &&
7721 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007722 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007723 if (DVar.CKind != OMPC_shared &&
7724 (isOpenMPParallelDirective(DVar.DKind) ||
7725 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007726 Diag(ELoc, diag::err_omp_required_access)
7727 << getOpenMPClauseName(OMPC_firstprivate)
7728 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007729 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007730 continue;
7731 }
7732 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007733 // OpenMP [2.9.3.4, Restrictions, p.3]
7734 // A list item that appears in a reduction clause of a parallel construct
7735 // must not appear in a firstprivate clause on a worksharing or task
7736 // construct if any of the worksharing or task regions arising from the
7737 // worksharing or task construct ever bind to any of the parallel regions
7738 // arising from the parallel construct.
7739 // OpenMP [2.9.3.4, Restrictions, p.4]
7740 // A list item that appears in a reduction clause in worksharing
7741 // construct must not appear in a firstprivate clause in a task construct
7742 // encountered during execution of any of the worksharing regions arising
7743 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007744 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007745 DVar = DSAStack->hasInnermostDSA(
7746 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7747 [](OpenMPDirectiveKind K) -> bool {
7748 return isOpenMPParallelDirective(K) ||
7749 isOpenMPWorksharingDirective(K);
7750 },
7751 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007752 if (DVar.CKind == OMPC_reduction &&
7753 (isOpenMPParallelDirective(DVar.DKind) ||
7754 isOpenMPWorksharingDirective(DVar.DKind))) {
7755 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7756 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007757 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007758 continue;
7759 }
7760 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007761
7762 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7763 // A list item that is private within a teams region must not appear in a
7764 // firstprivate clause on a distribute construct if any of the distribute
7765 // regions arising from the distribute construct ever bind to any of the
7766 // teams regions arising from the teams construct.
7767 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7768 // A list item that appears in a reduction clause of a teams construct
7769 // must not appear in a firstprivate clause on a distribute construct if
7770 // any of the distribute regions arising from the distribute construct
7771 // ever bind to any of the teams regions arising from the teams construct.
7772 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7773 // A list item may appear in a firstprivate or lastprivate clause but not
7774 // both.
7775 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007776 DVar = DSAStack->hasInnermostDSA(
7777 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7778 [](OpenMPDirectiveKind K) -> bool {
7779 return isOpenMPTeamsDirective(K);
7780 },
7781 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007782 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7783 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007784 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007785 continue;
7786 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007787 DVar = DSAStack->hasInnermostDSA(
7788 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7789 [](OpenMPDirectiveKind K) -> bool {
7790 return isOpenMPTeamsDirective(K);
7791 },
7792 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007793 if (DVar.CKind == OMPC_reduction &&
7794 isOpenMPTeamsDirective(DVar.DKind)) {
7795 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007796 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007797 continue;
7798 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007799 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007800 if (DVar.CKind == OMPC_lastprivate) {
7801 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007802 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007803 continue;
7804 }
7805 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007806 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7807 // A list item cannot appear in both a map clause and a data-sharing
7808 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007809 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007810 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007811 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007812 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007813 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007814 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007815 CurrDir == OMPD_target_parallel_for_simd ||
7816 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007817 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007818 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007819 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007820 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7821 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7822 ConflictKind = WhereFoundClauseKind;
7823 return true;
7824 })) {
7825 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007826 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007827 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007828 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7829 ReportOriginalDSA(*this, DSAStack, D, DVar);
7830 continue;
7831 }
7832 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007833 }
7834
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007835 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007836 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007837 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007838 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7839 << getOpenMPClauseName(OMPC_firstprivate) << Type
7840 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7841 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007842 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007843 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007844 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007845 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007846 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007847 continue;
7848 }
7849
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007850 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007851 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7852 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007853 // Generate helper private variable and initialize it with the value of the
7854 // original variable. The address of the original variable is replaced by
7855 // the address of the new private variable in the CodeGen. This new variable
7856 // is not added to IdResolver, so the code in the OpenMP region uses
7857 // original variable for proper diagnostics and variable capturing.
7858 Expr *VDInitRefExpr = nullptr;
7859 // For arrays generate initializer for single element and replace it by the
7860 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007861 if (Type->isArrayType()) {
7862 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007863 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007864 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007865 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007866 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007867 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007868 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007869 InitializedEntity Entity =
7870 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007871 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7872
7873 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7874 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7875 if (Result.isInvalid())
7876 VDPrivate->setInvalidDecl();
7877 else
7878 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007879 // Remove temp variable declaration.
7880 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007881 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007882 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7883 ".firstprivate.temp");
7884 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7885 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007886 AddInitializerToDecl(VDPrivate,
7887 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007888 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007889 }
7890 if (VDPrivate->isInvalidDecl()) {
7891 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007892 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007893 diag::note_omp_task_predetermined_firstprivate_here);
7894 }
7895 continue;
7896 }
7897 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007898 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007899 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7900 RefExpr->getExprLoc());
7901 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007902 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007903 if (TopDVar.CKind == OMPC_lastprivate)
7904 Ref = TopDVar.PrivateCopy;
7905 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007906 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007907 if (!IsOpenMPCapturedDecl(D))
7908 ExprCaptures.push_back(Ref->getDecl());
7909 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007910 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007911 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007912 Vars.push_back((VD || CurContext->isDependentContext())
7913 ? RefExpr->IgnoreParens()
7914 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007915 PrivateCopies.push_back(VDPrivateRefExpr);
7916 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007917 }
7918
Alexey Bataeved09d242014-05-28 05:53:51 +00007919 if (Vars.empty())
7920 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007921
7922 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007923 Vars, PrivateCopies, Inits,
7924 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007925}
7926
Alexander Musman1bb328c2014-06-04 13:06:39 +00007927OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7928 SourceLocation StartLoc,
7929 SourceLocation LParenLoc,
7930 SourceLocation EndLoc) {
7931 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007932 SmallVector<Expr *, 8> SrcExprs;
7933 SmallVector<Expr *, 8> DstExprs;
7934 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007935 SmallVector<Decl *, 4> ExprCaptures;
7936 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007937 for (auto &RefExpr : VarList) {
7938 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007939 SourceLocation ELoc;
7940 SourceRange ERange;
7941 Expr *SimpleRefExpr = RefExpr;
7942 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007943 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007944 // It will be analyzed later.
7945 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007946 SrcExprs.push_back(nullptr);
7947 DstExprs.push_back(nullptr);
7948 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007949 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007950 ValueDecl *D = Res.first;
7951 if (!D)
7952 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007953
Alexey Bataev74caaf22016-02-20 04:09:36 +00007954 QualType Type = D->getType();
7955 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007956
7957 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7958 // A variable that appears in a lastprivate clause must not have an
7959 // incomplete type or a reference type.
7960 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007961 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007962 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007963 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007964
7965 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7966 // in a Construct]
7967 // Variables with the predetermined data-sharing attributes may not be
7968 // listed in data-sharing attributes clauses, except for the cases
7969 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007970 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007971 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7972 DVar.CKind != OMPC_firstprivate &&
7973 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7974 Diag(ELoc, diag::err_omp_wrong_dsa)
7975 << getOpenMPClauseName(DVar.CKind)
7976 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007977 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007978 continue;
7979 }
7980
Alexey Bataevf29276e2014-06-18 04:14:57 +00007981 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7982 // OpenMP [2.14.3.5, Restrictions, p.2]
7983 // A list item that is private within a parallel region, or that appears in
7984 // the reduction clause of a parallel construct, must not appear in a
7985 // lastprivate clause on a worksharing construct if any of the corresponding
7986 // worksharing regions ever binds to any of the corresponding parallel
7987 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007988 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007989 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007990 !isOpenMPParallelDirective(CurrDir) &&
7991 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007992 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007993 if (DVar.CKind != OMPC_shared) {
7994 Diag(ELoc, diag::err_omp_required_access)
7995 << getOpenMPClauseName(OMPC_lastprivate)
7996 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007997 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007998 continue;
7999 }
8000 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008001
8002 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8003 // A list item may appear in a firstprivate or lastprivate clause but not
8004 // both.
8005 if (CurrDir == OMPD_distribute) {
8006 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8007 if (DVar.CKind == OMPC_firstprivate) {
8008 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8009 ReportOriginalDSA(*this, DSAStack, D, DVar);
8010 continue;
8011 }
8012 }
8013
Alexander Musman1bb328c2014-06-04 13:06:39 +00008014 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008015 // A variable of class type (or array thereof) that appears in a
8016 // lastprivate clause requires an accessible, unambiguous default
8017 // constructor for the class type, unless the list item is also specified
8018 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008019 // A variable of class type (or array thereof) that appears in a
8020 // lastprivate clause requires an accessible, unambiguous copy assignment
8021 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008022 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008023 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008024 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008025 D->hasAttrs() ? &D->getAttrs() : nullptr);
8026 auto *PseudoSrcExpr =
8027 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008028 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008029 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008030 D->hasAttrs() ? &D->getAttrs() : nullptr);
8031 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008032 // For arrays generate assignment operation for single element and replace
8033 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008034 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008035 PseudoDstExpr, PseudoSrcExpr);
8036 if (AssignmentOp.isInvalid())
8037 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008038 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008039 /*DiscardedValue=*/true);
8040 if (AssignmentOp.isInvalid())
8041 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008042
Alexey Bataev74caaf22016-02-20 04:09:36 +00008043 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008044 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008045 if (TopDVar.CKind == OMPC_firstprivate)
8046 Ref = TopDVar.PrivateCopy;
8047 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008048 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008049 if (!IsOpenMPCapturedDecl(D))
8050 ExprCaptures.push_back(Ref->getDecl());
8051 }
8052 if (TopDVar.CKind == OMPC_firstprivate ||
8053 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008054 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008055 ExprResult RefRes = DefaultLvalueConversion(Ref);
8056 if (!RefRes.isUsable())
8057 continue;
8058 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008059 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8060 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008061 if (!PostUpdateRes.isUsable())
8062 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008063 ExprPostUpdates.push_back(
8064 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008065 }
8066 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008067 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008068 Vars.push_back((VD || CurContext->isDependentContext())
8069 ? RefExpr->IgnoreParens()
8070 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008071 SrcExprs.push_back(PseudoSrcExpr);
8072 DstExprs.push_back(PseudoDstExpr);
8073 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008074 }
8075
8076 if (Vars.empty())
8077 return nullptr;
8078
8079 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008080 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008081 buildPreInits(Context, ExprCaptures),
8082 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008083}
8084
Alexey Bataev758e55e2013-09-06 18:03:48 +00008085OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8086 SourceLocation StartLoc,
8087 SourceLocation LParenLoc,
8088 SourceLocation EndLoc) {
8089 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008090 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008091 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008092 SourceLocation ELoc;
8093 SourceRange ERange;
8094 Expr *SimpleRefExpr = RefExpr;
8095 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008096 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008097 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008098 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008099 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008100 ValueDecl *D = Res.first;
8101 if (!D)
8102 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008103
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008104 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008105 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8106 // in a Construct]
8107 // Variables with the predetermined data-sharing attributes may not be
8108 // listed in data-sharing attributes clauses, except for the cases
8109 // listed below. For these exceptions only, listing a predetermined
8110 // variable in a data-sharing attribute clause is allowed and overrides
8111 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008112 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008113 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8114 DVar.RefExpr) {
8115 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8116 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008117 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008118 continue;
8119 }
8120
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008121 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008122 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008123 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008124 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008125 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8126 ? RefExpr->IgnoreParens()
8127 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008128 }
8129
Alexey Bataeved09d242014-05-28 05:53:51 +00008130 if (Vars.empty())
8131 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008132
8133 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8134}
8135
Alexey Bataevc5e02582014-06-16 07:08:35 +00008136namespace {
8137class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8138 DSAStackTy *Stack;
8139
8140public:
8141 bool VisitDeclRefExpr(DeclRefExpr *E) {
8142 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008143 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008144 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8145 return false;
8146 if (DVar.CKind != OMPC_unknown)
8147 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008148 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8149 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8150 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008151 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008152 return true;
8153 return false;
8154 }
8155 return false;
8156 }
8157 bool VisitStmt(Stmt *S) {
8158 for (auto Child : S->children()) {
8159 if (Child && Visit(Child))
8160 return true;
8161 }
8162 return false;
8163 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008164 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008165};
Alexey Bataev23b69422014-06-18 07:08:49 +00008166} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008167
Alexey Bataev60da77e2016-02-29 05:54:20 +00008168namespace {
8169// Transform MemberExpression for specified FieldDecl of current class to
8170// DeclRefExpr to specified OMPCapturedExprDecl.
8171class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8172 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8173 ValueDecl *Field;
8174 DeclRefExpr *CapturedExpr;
8175
8176public:
8177 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8178 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8179
8180 ExprResult TransformMemberExpr(MemberExpr *E) {
8181 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8182 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008183 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008184 return CapturedExpr;
8185 }
8186 return BaseTransform::TransformMemberExpr(E);
8187 }
8188 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8189};
8190} // namespace
8191
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008192template <typename T>
8193static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8194 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8195 for (auto &Set : Lookups) {
8196 for (auto *D : Set) {
8197 if (auto Res = Gen(cast<ValueDecl>(D)))
8198 return Res;
8199 }
8200 }
8201 return T();
8202}
8203
8204static ExprResult
8205buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8206 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8207 const DeclarationNameInfo &ReductionId, QualType Ty,
8208 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8209 if (ReductionIdScopeSpec.isInvalid())
8210 return ExprError();
8211 SmallVector<UnresolvedSet<8>, 4> Lookups;
8212 if (S) {
8213 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8214 Lookup.suppressDiagnostics();
8215 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8216 auto *D = Lookup.getRepresentativeDecl();
8217 do {
8218 S = S->getParent();
8219 } while (S && !S->isDeclScope(D));
8220 if (S)
8221 S = S->getParent();
8222 Lookups.push_back(UnresolvedSet<8>());
8223 Lookups.back().append(Lookup.begin(), Lookup.end());
8224 Lookup.clear();
8225 }
8226 } else if (auto *ULE =
8227 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8228 Lookups.push_back(UnresolvedSet<8>());
8229 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008230 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008231 if (D == PrevD)
8232 Lookups.push_back(UnresolvedSet<8>());
8233 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8234 Lookups.back().addDecl(DRD);
8235 PrevD = D;
8236 }
8237 }
8238 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8239 Ty->containsUnexpandedParameterPack() ||
8240 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8241 return !D->isInvalidDecl() &&
8242 (D->getType()->isDependentType() ||
8243 D->getType()->isInstantiationDependentType() ||
8244 D->getType()->containsUnexpandedParameterPack());
8245 })) {
8246 UnresolvedSet<8> ResSet;
8247 for (auto &Set : Lookups) {
8248 ResSet.append(Set.begin(), Set.end());
8249 // The last item marks the end of all declarations at the specified scope.
8250 ResSet.addDecl(Set[Set.size() - 1]);
8251 }
8252 return UnresolvedLookupExpr::Create(
8253 SemaRef.Context, /*NamingClass=*/nullptr,
8254 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8255 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8256 }
8257 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8258 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8259 if (!D->isInvalidDecl() &&
8260 SemaRef.Context.hasSameType(D->getType(), Ty))
8261 return D;
8262 return nullptr;
8263 }))
8264 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8265 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8266 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8267 if (!D->isInvalidDecl() &&
8268 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8269 !Ty.isMoreQualifiedThan(D->getType()))
8270 return D;
8271 return nullptr;
8272 })) {
8273 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8274 /*DetectVirtual=*/false);
8275 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8276 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8277 VD->getType().getUnqualifiedType()))) {
8278 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8279 /*DiagID=*/0) !=
8280 Sema::AR_inaccessible) {
8281 SemaRef.BuildBasePathArray(Paths, BasePath);
8282 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8283 }
8284 }
8285 }
8286 }
8287 if (ReductionIdScopeSpec.isSet()) {
8288 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8289 return ExprError();
8290 }
8291 return ExprEmpty();
8292}
8293
Alexey Bataevc5e02582014-06-16 07:08:35 +00008294OMPClause *Sema::ActOnOpenMPReductionClause(
8295 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8296 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008297 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8298 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008299 auto DN = ReductionId.getName();
8300 auto OOK = DN.getCXXOverloadedOperator();
8301 BinaryOperatorKind BOK = BO_Comma;
8302
8303 // OpenMP [2.14.3.6, reduction clause]
8304 // C
8305 // reduction-identifier is either an identifier or one of the following
8306 // operators: +, -, *, &, |, ^, && and ||
8307 // C++
8308 // reduction-identifier is either an id-expression or one of the following
8309 // operators: +, -, *, &, |, ^, && and ||
8310 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8311 switch (OOK) {
8312 case OO_Plus:
8313 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008314 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008315 break;
8316 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008317 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008318 break;
8319 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008320 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008321 break;
8322 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008323 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008324 break;
8325 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008326 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008327 break;
8328 case OO_AmpAmp:
8329 BOK = BO_LAnd;
8330 break;
8331 case OO_PipePipe:
8332 BOK = BO_LOr;
8333 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008334 case OO_New:
8335 case OO_Delete:
8336 case OO_Array_New:
8337 case OO_Array_Delete:
8338 case OO_Slash:
8339 case OO_Percent:
8340 case OO_Tilde:
8341 case OO_Exclaim:
8342 case OO_Equal:
8343 case OO_Less:
8344 case OO_Greater:
8345 case OO_LessEqual:
8346 case OO_GreaterEqual:
8347 case OO_PlusEqual:
8348 case OO_MinusEqual:
8349 case OO_StarEqual:
8350 case OO_SlashEqual:
8351 case OO_PercentEqual:
8352 case OO_CaretEqual:
8353 case OO_AmpEqual:
8354 case OO_PipeEqual:
8355 case OO_LessLess:
8356 case OO_GreaterGreater:
8357 case OO_LessLessEqual:
8358 case OO_GreaterGreaterEqual:
8359 case OO_EqualEqual:
8360 case OO_ExclaimEqual:
8361 case OO_PlusPlus:
8362 case OO_MinusMinus:
8363 case OO_Comma:
8364 case OO_ArrowStar:
8365 case OO_Arrow:
8366 case OO_Call:
8367 case OO_Subscript:
8368 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008369 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008370 case NUM_OVERLOADED_OPERATORS:
8371 llvm_unreachable("Unexpected reduction identifier");
8372 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008373 if (auto II = DN.getAsIdentifierInfo()) {
8374 if (II->isStr("max"))
8375 BOK = BO_GT;
8376 else if (II->isStr("min"))
8377 BOK = BO_LT;
8378 }
8379 break;
8380 }
8381 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008382 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008383 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008384 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008385
8386 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008387 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008388 SmallVector<Expr *, 8> LHSs;
8389 SmallVector<Expr *, 8> RHSs;
8390 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008391 SmallVector<Decl *, 4> ExprCaptures;
8392 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008393 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8394 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008395 for (auto RefExpr : VarList) {
8396 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008397 // OpenMP [2.1, C/C++]
8398 // A list item is a variable or array section, subject to the restrictions
8399 // specified in Section 2.4 on page 42 and in each of the sections
8400 // describing clauses and directives for which a list appears.
8401 // OpenMP [2.14.3.3, Restrictions, p.1]
8402 // A variable that is part of another variable (as an array or
8403 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008404 if (!FirstIter && IR != ER)
8405 ++IR;
8406 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008407 SourceLocation ELoc;
8408 SourceRange ERange;
8409 Expr *SimpleRefExpr = RefExpr;
8410 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8411 /*AllowArraySection=*/true);
8412 if (Res.second) {
8413 // It will be analyzed later.
8414 Vars.push_back(RefExpr);
8415 Privates.push_back(nullptr);
8416 LHSs.push_back(nullptr);
8417 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008418 // Try to find 'declare reduction' corresponding construct before using
8419 // builtin/overloaded operators.
8420 QualType Type = Context.DependentTy;
8421 CXXCastPath BasePath;
8422 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8423 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8424 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8425 if (CurContext->isDependentContext() &&
8426 (DeclareReductionRef.isUnset() ||
8427 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8428 ReductionOps.push_back(DeclareReductionRef.get());
8429 else
8430 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008431 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008432 ValueDecl *D = Res.first;
8433 if (!D)
8434 continue;
8435
Alexey Bataeva1764212015-09-30 09:22:36 +00008436 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008437 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8438 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8439 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008440 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008441 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008442 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8443 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8444 Type = ATy->getElementType();
8445 else
8446 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008447 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008448 } else
8449 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8450 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008451
Alexey Bataevc5e02582014-06-16 07:08:35 +00008452 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8453 // A variable that appears in a private clause must not have an incomplete
8454 // type or a reference type.
8455 if (RequireCompleteType(ELoc, Type,
8456 diag::err_omp_reduction_incomplete_type))
8457 continue;
8458 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008459 // A list item that appears in a reduction clause must not be
8460 // const-qualified.
8461 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008462 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008463 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008464 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008465 bool IsDecl = !VD ||
8466 VD->isThisDeclarationADefinition(Context) ==
8467 VarDecl::DeclarationOnly;
8468 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008469 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008470 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008471 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008472 continue;
8473 }
8474 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8475 // If a list-item is a reference type then it must bind to the same object
8476 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008477 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008478 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008479 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008480 DSARefChecker Check(DSAStack);
8481 if (Check.Visit(VDDef->getInit())) {
8482 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8483 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8484 continue;
8485 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008486 }
8487 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008488
Alexey Bataevc5e02582014-06-16 07:08:35 +00008489 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8490 // in a Construct]
8491 // Variables with the predetermined data-sharing attributes may not be
8492 // listed in data-sharing attributes clauses, except for the cases
8493 // listed below. For these exceptions only, listing a predetermined
8494 // variable in a data-sharing attribute clause is allowed and overrides
8495 // the variable's predetermined data-sharing attributes.
8496 // OpenMP [2.14.3.6, Restrictions, p.3]
8497 // Any number of reduction clauses can be specified on the directive,
8498 // but a list item can appear only once in the reduction clauses for that
8499 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008500 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008501 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008502 if (DVar.CKind == OMPC_reduction) {
8503 Diag(ELoc, diag::err_omp_once_referenced)
8504 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008505 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008506 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008507 } else if (DVar.CKind != OMPC_unknown) {
8508 Diag(ELoc, diag::err_omp_wrong_dsa)
8509 << getOpenMPClauseName(DVar.CKind)
8510 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008511 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008512 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008513 }
8514
8515 // OpenMP [2.14.3.6, Restrictions, p.1]
8516 // A list item that appears in a reduction clause of a worksharing
8517 // construct must be shared in the parallel regions to which any of the
8518 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008519 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8520 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008521 !isOpenMPParallelDirective(CurrDir) &&
8522 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008523 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008524 if (DVar.CKind != OMPC_shared) {
8525 Diag(ELoc, diag::err_omp_required_access)
8526 << getOpenMPClauseName(OMPC_reduction)
8527 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008528 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008529 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008530 }
8531 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008532
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008533 // Try to find 'declare reduction' corresponding construct before using
8534 // builtin/overloaded operators.
8535 CXXCastPath BasePath;
8536 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8537 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8538 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8539 if (DeclareReductionRef.isInvalid())
8540 continue;
8541 if (CurContext->isDependentContext() &&
8542 (DeclareReductionRef.isUnset() ||
8543 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8544 Vars.push_back(RefExpr);
8545 Privates.push_back(nullptr);
8546 LHSs.push_back(nullptr);
8547 RHSs.push_back(nullptr);
8548 ReductionOps.push_back(DeclareReductionRef.get());
8549 continue;
8550 }
8551 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8552 // Not allowed reduction identifier is found.
8553 Diag(ReductionId.getLocStart(),
8554 diag::err_omp_unknown_reduction_identifier)
8555 << Type << ReductionIdRange;
8556 continue;
8557 }
8558
8559 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8560 // The type of a list item that appears in a reduction clause must be valid
8561 // for the reduction-identifier. For a max or min reduction in C, the type
8562 // of the list item must be an allowed arithmetic data type: char, int,
8563 // float, double, or _Bool, possibly modified with long, short, signed, or
8564 // unsigned. For a max or min reduction in C++, the type of the list item
8565 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8566 // double, or bool, possibly modified with long, short, signed, or unsigned.
8567 if (DeclareReductionRef.isUnset()) {
8568 if ((BOK == BO_GT || BOK == BO_LT) &&
8569 !(Type->isScalarType() ||
8570 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8571 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8572 << getLangOpts().CPlusPlus;
8573 if (!ASE && !OASE) {
8574 bool IsDecl = !VD ||
8575 VD->isThisDeclarationADefinition(Context) ==
8576 VarDecl::DeclarationOnly;
8577 Diag(D->getLocation(),
8578 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8579 << D;
8580 }
8581 continue;
8582 }
8583 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8584 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8585 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8586 if (!ASE && !OASE) {
8587 bool IsDecl = !VD ||
8588 VD->isThisDeclarationADefinition(Context) ==
8589 VarDecl::DeclarationOnly;
8590 Diag(D->getLocation(),
8591 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8592 << D;
8593 }
8594 continue;
8595 }
8596 }
8597
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008598 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008599 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008600 D->hasAttrs() ? &D->getAttrs() : nullptr);
8601 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8602 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008603 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008604 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008605 (!ASE &&
8606 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008607 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008608 // Create pseudo array type for private copy. The size for this array will
8609 // be generated during codegen.
8610 // For array subscripts or single variables Private Ty is the same as Type
8611 // (type of the variable or single array element).
8612 PrivateTy = Context.getVariableArrayType(
8613 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8614 Context.getSizeType(), VK_RValue),
8615 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008616 } else if (!ASE && !OASE &&
8617 Context.getAsArrayType(D->getType().getNonReferenceType()))
8618 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008619 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008620 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8621 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008622 // Add initializer for private variable.
8623 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008624 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8625 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8626 if (DeclareReductionRef.isUsable()) {
8627 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8628 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8629 if (DRD->getInitializer()) {
8630 Init = DRDRef;
8631 RHSVD->setInit(DRDRef);
8632 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008633 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008634 } else {
8635 switch (BOK) {
8636 case BO_Add:
8637 case BO_Xor:
8638 case BO_Or:
8639 case BO_LOr:
8640 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8641 if (Type->isScalarType() || Type->isAnyComplexType())
8642 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8643 break;
8644 case BO_Mul:
8645 case BO_LAnd:
8646 if (Type->isScalarType() || Type->isAnyComplexType()) {
8647 // '*' and '&&' reduction ops - initializer is '1'.
8648 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008649 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008650 break;
8651 case BO_And: {
8652 // '&' reduction op - initializer is '~0'.
8653 QualType OrigType = Type;
8654 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8655 Type = ComplexTy->getElementType();
8656 if (Type->isRealFloatingType()) {
8657 llvm::APFloat InitValue =
8658 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8659 /*isIEEE=*/true);
8660 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8661 Type, ELoc);
8662 } else if (Type->isScalarType()) {
8663 auto Size = Context.getTypeSize(Type);
8664 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8665 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8666 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8667 }
8668 if (Init && OrigType->isAnyComplexType()) {
8669 // Init = 0xFFFF + 0xFFFFi;
8670 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8671 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8672 }
8673 Type = OrigType;
8674 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008675 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008676 case BO_LT:
8677 case BO_GT: {
8678 // 'min' reduction op - initializer is 'Largest representable number in
8679 // the reduction list item type'.
8680 // 'max' reduction op - initializer is 'Least representable number in
8681 // the reduction list item type'.
8682 if (Type->isIntegerType() || Type->isPointerType()) {
8683 bool IsSigned = Type->hasSignedIntegerRepresentation();
8684 auto Size = Context.getTypeSize(Type);
8685 QualType IntTy =
8686 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8687 llvm::APInt InitValue =
8688 (BOK != BO_LT)
8689 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8690 : llvm::APInt::getMinValue(Size)
8691 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8692 : llvm::APInt::getMaxValue(Size);
8693 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8694 if (Type->isPointerType()) {
8695 // Cast to pointer type.
8696 auto CastExpr = BuildCStyleCastExpr(
8697 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8698 SourceLocation(), Init);
8699 if (CastExpr.isInvalid())
8700 continue;
8701 Init = CastExpr.get();
8702 }
8703 } else if (Type->isRealFloatingType()) {
8704 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8705 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8706 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8707 Type, ELoc);
8708 }
8709 break;
8710 }
8711 case BO_PtrMemD:
8712 case BO_PtrMemI:
8713 case BO_MulAssign:
8714 case BO_Div:
8715 case BO_Rem:
8716 case BO_Sub:
8717 case BO_Shl:
8718 case BO_Shr:
8719 case BO_LE:
8720 case BO_GE:
8721 case BO_EQ:
8722 case BO_NE:
8723 case BO_AndAssign:
8724 case BO_XorAssign:
8725 case BO_OrAssign:
8726 case BO_Assign:
8727 case BO_AddAssign:
8728 case BO_SubAssign:
8729 case BO_DivAssign:
8730 case BO_RemAssign:
8731 case BO_ShlAssign:
8732 case BO_ShrAssign:
8733 case BO_Comma:
8734 llvm_unreachable("Unexpected reduction operation");
8735 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008736 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008737 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00008738 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008739 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00008740 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008741 if (RHSVD->isInvalidDecl())
8742 continue;
8743 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008744 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8745 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008746 bool IsDecl =
8747 !VD ||
8748 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8749 Diag(D->getLocation(),
8750 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8751 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008752 continue;
8753 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008754 // Store initializer for single element in private copy. Will be used during
8755 // codegen.
8756 PrivateVD->setInit(RHSVD->getInit());
8757 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008758 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008759 ExprResult ReductionOp;
8760 if (DeclareReductionRef.isUsable()) {
8761 QualType RedTy = DeclareReductionRef.get()->getType();
8762 QualType PtrRedTy = Context.getPointerType(RedTy);
8763 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8764 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8765 if (!BasePath.empty()) {
8766 LHS = DefaultLvalueConversion(LHS.get());
8767 RHS = DefaultLvalueConversion(RHS.get());
8768 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8769 CK_UncheckedDerivedToBase, LHS.get(),
8770 &BasePath, LHS.get()->getValueKind());
8771 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8772 CK_UncheckedDerivedToBase, RHS.get(),
8773 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008774 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008775 FunctionProtoType::ExtProtoInfo EPI;
8776 QualType Params[] = {PtrRedTy, PtrRedTy};
8777 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8778 auto *OVE = new (Context) OpaqueValueExpr(
8779 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8780 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8781 Expr *Args[] = {LHS.get(), RHS.get()};
8782 ReductionOp = new (Context)
8783 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8784 } else {
8785 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8786 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8787 if (ReductionOp.isUsable()) {
8788 if (BOK != BO_LT && BOK != BO_GT) {
8789 ReductionOp =
8790 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8791 BO_Assign, LHSDRE, ReductionOp.get());
8792 } else {
8793 auto *ConditionalOp = new (Context) ConditionalOperator(
8794 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8795 RHSDRE, Type, VK_LValue, OK_Ordinary);
8796 ReductionOp =
8797 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8798 BO_Assign, LHSDRE, ConditionalOp);
8799 }
8800 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8801 }
8802 if (ReductionOp.isInvalid())
8803 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008804 }
8805
Alexey Bataev60da77e2016-02-29 05:54:20 +00008806 DeclRefExpr *Ref = nullptr;
8807 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008808 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008809 if (ASE || OASE) {
8810 TransformExprToCaptures RebuildToCapture(*this, D);
8811 VarsExpr =
8812 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8813 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008814 } else {
8815 VarsExpr = Ref =
8816 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008817 }
8818 if (!IsOpenMPCapturedDecl(D)) {
8819 ExprCaptures.push_back(Ref->getDecl());
8820 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8821 ExprResult RefRes = DefaultLvalueConversion(Ref);
8822 if (!RefRes.isUsable())
8823 continue;
8824 ExprResult PostUpdateRes =
8825 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8826 SimpleRefExpr, RefRes.get());
8827 if (!PostUpdateRes.isUsable())
8828 continue;
8829 ExprPostUpdates.push_back(
8830 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008831 }
8832 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008833 }
8834 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8835 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008836 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008837 LHSs.push_back(LHSDRE);
8838 RHSs.push_back(RHSDRE);
8839 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008840 }
8841
8842 if (Vars.empty())
8843 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008844
Alexey Bataevc5e02582014-06-16 07:08:35 +00008845 return OMPReductionClause::Create(
8846 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008847 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008848 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8849 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008850}
8851
Alexey Bataevecba70f2016-04-12 11:02:11 +00008852bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8853 SourceLocation LinLoc) {
8854 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8855 LinKind == OMPC_LINEAR_unknown) {
8856 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8857 return true;
8858 }
8859 return false;
8860}
8861
8862bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8863 OpenMPLinearClauseKind LinKind,
8864 QualType Type) {
8865 auto *VD = dyn_cast_or_null<VarDecl>(D);
8866 // A variable must not have an incomplete type or a reference type.
8867 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8868 return true;
8869 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8870 !Type->isReferenceType()) {
8871 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8872 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8873 return true;
8874 }
8875 Type = Type.getNonReferenceType();
8876
8877 // A list item must not be const-qualified.
8878 if (Type.isConstant(Context)) {
8879 Diag(ELoc, diag::err_omp_const_variable)
8880 << getOpenMPClauseName(OMPC_linear);
8881 if (D) {
8882 bool IsDecl =
8883 !VD ||
8884 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8885 Diag(D->getLocation(),
8886 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8887 << D;
8888 }
8889 return true;
8890 }
8891
8892 // A list item must be of integral or pointer type.
8893 Type = Type.getUnqualifiedType().getCanonicalType();
8894 const auto *Ty = Type.getTypePtrOrNull();
8895 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8896 !Ty->isPointerType())) {
8897 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8898 if (D) {
8899 bool IsDecl =
8900 !VD ||
8901 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8902 Diag(D->getLocation(),
8903 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8904 << D;
8905 }
8906 return true;
8907 }
8908 return false;
8909}
8910
Alexey Bataev182227b2015-08-20 10:54:39 +00008911OMPClause *Sema::ActOnOpenMPLinearClause(
8912 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8913 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8914 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008915 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008916 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008917 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008918 SmallVector<Decl *, 4> ExprCaptures;
8919 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008920 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008921 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008922 for (auto &RefExpr : VarList) {
8923 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008924 SourceLocation ELoc;
8925 SourceRange ERange;
8926 Expr *SimpleRefExpr = RefExpr;
8927 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8928 /*AllowArraySection=*/false);
8929 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008930 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008931 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008932 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008933 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008934 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008935 ValueDecl *D = Res.first;
8936 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008937 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008938
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008939 QualType Type = D->getType();
8940 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008941
8942 // OpenMP [2.14.3.7, linear clause]
8943 // A list-item cannot appear in more than one linear clause.
8944 // A list-item that appears in a linear clause cannot appear in any
8945 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008946 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008947 if (DVar.RefExpr) {
8948 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8949 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008950 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008951 continue;
8952 }
8953
Alexey Bataevecba70f2016-04-12 11:02:11 +00008954 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008955 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008956 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008957
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008958 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008959 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8960 D->hasAttrs() ? &D->getAttrs() : nullptr);
8961 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008962 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008963 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008964 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008965 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008966 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008967 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8968 if (!IsOpenMPCapturedDecl(D)) {
8969 ExprCaptures.push_back(Ref->getDecl());
8970 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8971 ExprResult RefRes = DefaultLvalueConversion(Ref);
8972 if (!RefRes.isUsable())
8973 continue;
8974 ExprResult PostUpdateRes =
8975 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8976 SimpleRefExpr, RefRes.get());
8977 if (!PostUpdateRes.isUsable())
8978 continue;
8979 ExprPostUpdates.push_back(
8980 IgnoredValueConversions(PostUpdateRes.get()).get());
8981 }
8982 }
8983 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008984 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008985 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008986 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008987 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008988 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008989 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008990 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8991
8992 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008993 Vars.push_back((VD || CurContext->isDependentContext())
8994 ? RefExpr->IgnoreParens()
8995 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008996 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008997 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008998 }
8999
9000 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009001 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009002
9003 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009004 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009005 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9006 !Step->isInstantiationDependent() &&
9007 !Step->containsUnexpandedParameterPack()) {
9008 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009009 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009010 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009011 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009012 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009013
Alexander Musman3276a272015-03-21 10:12:56 +00009014 // Build var to save the step value.
9015 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009016 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009017 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009018 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009019 ExprResult CalcStep =
9020 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009021 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009022
Alexander Musman8dba6642014-04-22 13:09:42 +00009023 // Warn about zero linear step (it would be probably better specified as
9024 // making corresponding variables 'const').
9025 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009026 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9027 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009028 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9029 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009030 if (!IsConstant && CalcStep.isUsable()) {
9031 // Calculate the step beforehand instead of doing this on each iteration.
9032 // (This is not used if the number of iterations may be kfold-ed).
9033 CalcStepExpr = CalcStep.get();
9034 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009035 }
9036
Alexey Bataev182227b2015-08-20 10:54:39 +00009037 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9038 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009039 StepExpr, CalcStepExpr,
9040 buildPreInits(Context, ExprCaptures),
9041 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009042}
9043
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009044static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9045 Expr *NumIterations, Sema &SemaRef,
9046 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009047 // Walk the vars and build update/final expressions for the CodeGen.
9048 SmallVector<Expr *, 8> Updates;
9049 SmallVector<Expr *, 8> Finals;
9050 Expr *Step = Clause.getStep();
9051 Expr *CalcStep = Clause.getCalcStep();
9052 // OpenMP [2.14.3.7, linear clause]
9053 // If linear-step is not specified it is assumed to be 1.
9054 if (Step == nullptr)
9055 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009056 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009057 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009058 }
Alexander Musman3276a272015-03-21 10:12:56 +00009059 bool HasErrors = false;
9060 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009061 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009062 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009063 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009064 SourceLocation ELoc;
9065 SourceRange ERange;
9066 Expr *SimpleRefExpr = RefExpr;
9067 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9068 /*AllowArraySection=*/false);
9069 ValueDecl *D = Res.first;
9070 if (Res.second || !D) {
9071 Updates.push_back(nullptr);
9072 Finals.push_back(nullptr);
9073 HasErrors = true;
9074 continue;
9075 }
9076 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9077 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9078 ->getMemberDecl();
9079 }
9080 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009081 Expr *InitExpr = *CurInit;
9082
9083 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009084 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009085 Expr *CapturedRef;
9086 if (LinKind == OMPC_LINEAR_uval)
9087 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9088 else
9089 CapturedRef =
9090 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9091 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9092 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009093
9094 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009095 ExprResult Update;
9096 if (!Info.first) {
9097 Update =
9098 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9099 InitExpr, IV, Step, /* Subtract */ false);
9100 } else
9101 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009102 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9103 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009104
9105 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009106 ExprResult Final;
9107 if (!Info.first) {
9108 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9109 InitExpr, NumIterations, Step,
9110 /* Subtract */ false);
9111 } else
9112 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009113 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9114 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009115
Alexander Musman3276a272015-03-21 10:12:56 +00009116 if (!Update.isUsable() || !Final.isUsable()) {
9117 Updates.push_back(nullptr);
9118 Finals.push_back(nullptr);
9119 HasErrors = true;
9120 } else {
9121 Updates.push_back(Update.get());
9122 Finals.push_back(Final.get());
9123 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009124 ++CurInit;
9125 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009126 }
9127 Clause.setUpdates(Updates);
9128 Clause.setFinals(Finals);
9129 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009130}
9131
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009132OMPClause *Sema::ActOnOpenMPAlignedClause(
9133 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9134 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9135
9136 SmallVector<Expr *, 8> Vars;
9137 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009138 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9139 SourceLocation ELoc;
9140 SourceRange ERange;
9141 Expr *SimpleRefExpr = RefExpr;
9142 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9143 /*AllowArraySection=*/false);
9144 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009145 // It will be analyzed later.
9146 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009147 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009148 ValueDecl *D = Res.first;
9149 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009150 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009151
Alexey Bataev1efd1662016-03-29 10:59:56 +00009152 QualType QType = D->getType();
9153 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009154
9155 // OpenMP [2.8.1, simd construct, Restrictions]
9156 // The type of list items appearing in the aligned clause must be
9157 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009158 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009159 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009160 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009161 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009162 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009163 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009164 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009165 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009166 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009167 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009168 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009169 continue;
9170 }
9171
9172 // OpenMP [2.8.1, simd construct, Restrictions]
9173 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009174 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009175 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009176 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9177 << getOpenMPClauseName(OMPC_aligned);
9178 continue;
9179 }
9180
Alexey Bataev1efd1662016-03-29 10:59:56 +00009181 DeclRefExpr *Ref = nullptr;
9182 if (!VD && IsOpenMPCapturedDecl(D))
9183 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9184 Vars.push_back(DefaultFunctionArrayConversion(
9185 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9186 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009187 }
9188
9189 // OpenMP [2.8.1, simd construct, Description]
9190 // The parameter of the aligned clause, alignment, must be a constant
9191 // positive integer expression.
9192 // If no optional parameter is specified, implementation-defined default
9193 // alignments for SIMD instructions on the target platforms are assumed.
9194 if (Alignment != nullptr) {
9195 ExprResult AlignResult =
9196 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9197 if (AlignResult.isInvalid())
9198 return nullptr;
9199 Alignment = AlignResult.get();
9200 }
9201 if (Vars.empty())
9202 return nullptr;
9203
9204 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9205 EndLoc, Vars, Alignment);
9206}
9207
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009208OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9209 SourceLocation StartLoc,
9210 SourceLocation LParenLoc,
9211 SourceLocation EndLoc) {
9212 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009213 SmallVector<Expr *, 8> SrcExprs;
9214 SmallVector<Expr *, 8> DstExprs;
9215 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009216 for (auto &RefExpr : VarList) {
9217 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9218 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009219 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009220 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009221 SrcExprs.push_back(nullptr);
9222 DstExprs.push_back(nullptr);
9223 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009224 continue;
9225 }
9226
Alexey Bataeved09d242014-05-28 05:53:51 +00009227 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009228 // OpenMP [2.1, C/C++]
9229 // A list item is a variable name.
9230 // OpenMP [2.14.4.1, Restrictions, p.1]
9231 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009232 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009233 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009234 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9235 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009236 continue;
9237 }
9238
9239 Decl *D = DE->getDecl();
9240 VarDecl *VD = cast<VarDecl>(D);
9241
9242 QualType Type = VD->getType();
9243 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9244 // It will be analyzed later.
9245 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009246 SrcExprs.push_back(nullptr);
9247 DstExprs.push_back(nullptr);
9248 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009249 continue;
9250 }
9251
9252 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9253 // A list item that appears in a copyin clause must be threadprivate.
9254 if (!DSAStack->isThreadPrivate(VD)) {
9255 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009256 << getOpenMPClauseName(OMPC_copyin)
9257 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009258 continue;
9259 }
9260
9261 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9262 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009263 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009264 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009265 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009266 auto *SrcVD =
9267 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9268 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009269 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009270 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9271 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009272 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9273 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009274 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009275 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009276 // For arrays generate assignment operation for single element and replace
9277 // it by the original array element in CodeGen.
9278 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9279 PseudoDstExpr, PseudoSrcExpr);
9280 if (AssignmentOp.isInvalid())
9281 continue;
9282 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9283 /*DiscardedValue=*/true);
9284 if (AssignmentOp.isInvalid())
9285 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009286
9287 DSAStack->addDSA(VD, DE, OMPC_copyin);
9288 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009289 SrcExprs.push_back(PseudoSrcExpr);
9290 DstExprs.push_back(PseudoDstExpr);
9291 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009292 }
9293
Alexey Bataeved09d242014-05-28 05:53:51 +00009294 if (Vars.empty())
9295 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009296
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009297 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9298 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009299}
9300
Alexey Bataevbae9a792014-06-27 10:37:06 +00009301OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9302 SourceLocation StartLoc,
9303 SourceLocation LParenLoc,
9304 SourceLocation EndLoc) {
9305 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009306 SmallVector<Expr *, 8> SrcExprs;
9307 SmallVector<Expr *, 8> DstExprs;
9308 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009309 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009310 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9311 SourceLocation ELoc;
9312 SourceRange ERange;
9313 Expr *SimpleRefExpr = RefExpr;
9314 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9315 /*AllowArraySection=*/false);
9316 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009317 // It will be analyzed later.
9318 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009319 SrcExprs.push_back(nullptr);
9320 DstExprs.push_back(nullptr);
9321 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009322 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009323 ValueDecl *D = Res.first;
9324 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009325 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009326
Alexey Bataeve122da12016-03-17 10:50:17 +00009327 QualType Type = D->getType();
9328 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009329
9330 // OpenMP [2.14.4.2, Restrictions, p.2]
9331 // A list item that appears in a copyprivate clause may not appear in a
9332 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009333 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9334 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009335 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9336 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009337 Diag(ELoc, diag::err_omp_wrong_dsa)
9338 << getOpenMPClauseName(DVar.CKind)
9339 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009340 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009341 continue;
9342 }
9343
9344 // OpenMP [2.11.4.2, Restrictions, p.1]
9345 // All list items that appear in a copyprivate clause must be either
9346 // threadprivate or private in the enclosing context.
9347 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009348 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009349 if (DVar.CKind == OMPC_shared) {
9350 Diag(ELoc, diag::err_omp_required_access)
9351 << getOpenMPClauseName(OMPC_copyprivate)
9352 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009353 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009354 continue;
9355 }
9356 }
9357 }
9358
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009359 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009360 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009361 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009362 << getOpenMPClauseName(OMPC_copyprivate) << Type
9363 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009364 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009365 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009366 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009367 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009368 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009369 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009370 continue;
9371 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009372
Alexey Bataevbae9a792014-06-27 10:37:06 +00009373 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9374 // A variable of class type (or array thereof) that appears in a
9375 // copyin clause requires an accessible, unambiguous copy assignment
9376 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009377 Type = Context.getBaseElementType(Type.getNonReferenceType())
9378 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009379 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009380 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9381 D->hasAttrs() ? &D->getAttrs() : nullptr);
9382 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009383 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009384 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9385 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009386 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009387 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009388 PseudoDstExpr, PseudoSrcExpr);
9389 if (AssignmentOp.isInvalid())
9390 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009391 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009392 /*DiscardedValue=*/true);
9393 if (AssignmentOp.isInvalid())
9394 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009395
9396 // No need to mark vars as copyprivate, they are already threadprivate or
9397 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009398 assert(VD || IsOpenMPCapturedDecl(D));
9399 Vars.push_back(
9400 VD ? RefExpr->IgnoreParens()
9401 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009402 SrcExprs.push_back(PseudoSrcExpr);
9403 DstExprs.push_back(PseudoDstExpr);
9404 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009405 }
9406
9407 if (Vars.empty())
9408 return nullptr;
9409
Alexey Bataeva63048e2015-03-23 06:18:07 +00009410 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9411 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009412}
9413
Alexey Bataev6125da92014-07-21 11:26:11 +00009414OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9415 SourceLocation StartLoc,
9416 SourceLocation LParenLoc,
9417 SourceLocation EndLoc) {
9418 if (VarList.empty())
9419 return nullptr;
9420
9421 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9422}
Alexey Bataevdea47612014-07-23 07:46:59 +00009423
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009424OMPClause *
9425Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9426 SourceLocation DepLoc, SourceLocation ColonLoc,
9427 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9428 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009429 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009430 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009431 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009432 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009433 return nullptr;
9434 }
9435 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009436 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9437 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009438 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009439 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009440 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9441 /*Last=*/OMPC_DEPEND_unknown, Except)
9442 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009443 return nullptr;
9444 }
9445 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009446 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009447 llvm::APSInt DepCounter(/*BitWidth=*/32);
9448 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9449 if (DepKind == OMPC_DEPEND_sink) {
9450 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9451 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9452 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009453 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009454 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009455 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9456 DSAStack->getParentOrderedRegionParam()) {
9457 for (auto &RefExpr : VarList) {
9458 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009459 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009460 // It will be analyzed later.
9461 Vars.push_back(RefExpr);
9462 continue;
9463 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009464
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009465 SourceLocation ELoc = RefExpr->getExprLoc();
9466 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9467 if (DepKind == OMPC_DEPEND_sink) {
9468 if (DepCounter >= TotalDepCount) {
9469 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9470 continue;
9471 }
9472 ++DepCounter;
9473 // OpenMP [2.13.9, Summary]
9474 // depend(dependence-type : vec), where dependence-type is:
9475 // 'sink' and where vec is the iteration vector, which has the form:
9476 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9477 // where n is the value specified by the ordered clause in the loop
9478 // directive, xi denotes the loop iteration variable of the i-th nested
9479 // loop associated with the loop directive, and di is a constant
9480 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009481 if (CurContext->isDependentContext()) {
9482 // It will be analyzed later.
9483 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009484 continue;
9485 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009486 SimpleExpr = SimpleExpr->IgnoreImplicit();
9487 OverloadedOperatorKind OOK = OO_None;
9488 SourceLocation OOLoc;
9489 Expr *LHS = SimpleExpr;
9490 Expr *RHS = nullptr;
9491 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9492 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9493 OOLoc = BO->getOperatorLoc();
9494 LHS = BO->getLHS()->IgnoreParenImpCasts();
9495 RHS = BO->getRHS()->IgnoreParenImpCasts();
9496 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9497 OOK = OCE->getOperator();
9498 OOLoc = OCE->getOperatorLoc();
9499 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9500 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9501 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9502 OOK = MCE->getMethodDecl()
9503 ->getNameInfo()
9504 .getName()
9505 .getCXXOverloadedOperator();
9506 OOLoc = MCE->getCallee()->getExprLoc();
9507 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9508 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9509 }
9510 SourceLocation ELoc;
9511 SourceRange ERange;
9512 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9513 /*AllowArraySection=*/false);
9514 if (Res.second) {
9515 // It will be analyzed later.
9516 Vars.push_back(RefExpr);
9517 }
9518 ValueDecl *D = Res.first;
9519 if (!D)
9520 continue;
9521
9522 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9523 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9524 continue;
9525 }
9526 if (RHS) {
9527 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9528 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9529 if (RHSRes.isInvalid())
9530 continue;
9531 }
9532 if (!CurContext->isDependentContext() &&
9533 DSAStack->getParentOrderedRegionParam() &&
9534 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9535 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9536 << DSAStack->getParentLoopControlVariable(
9537 DepCounter.getZExtValue());
9538 continue;
9539 }
9540 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009541 } else {
9542 // OpenMP [2.11.1.1, Restrictions, p.3]
9543 // A variable that is part of another variable (such as a field of a
9544 // structure) but is not an array element or an array section cannot
9545 // appear in a depend clause.
9546 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9547 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9548 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9549 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9550 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009551 (ASE &&
9552 !ASE->getBase()
9553 ->getType()
9554 .getNonReferenceType()
9555 ->isPointerType() &&
9556 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009557 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9558 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009559 continue;
9560 }
9561 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009562 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9563 }
9564
9565 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9566 TotalDepCount > VarList.size() &&
9567 DSAStack->getParentOrderedRegionParam()) {
9568 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9569 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9570 }
9571 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9572 Vars.empty())
9573 return nullptr;
9574 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009575 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9576 DepKind, DepLoc, ColonLoc, Vars);
9577 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9578 DSAStack->addDoacrossDependClause(C, OpsOffs);
9579 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009580}
Michael Wonge710d542015-08-07 16:16:36 +00009581
9582OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9583 SourceLocation LParenLoc,
9584 SourceLocation EndLoc) {
9585 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009586
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009587 // OpenMP [2.9.1, Restrictions]
9588 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009589 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9590 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009591 return nullptr;
9592
Michael Wonge710d542015-08-07 16:16:36 +00009593 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9594}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009595
9596static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9597 DSAStackTy *Stack, CXXRecordDecl *RD) {
9598 if (!RD || RD->isInvalidDecl())
9599 return true;
9600
9601 auto QTy = SemaRef.Context.getRecordType(RD);
9602 if (RD->isDynamicClass()) {
9603 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9604 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9605 return false;
9606 }
9607 auto *DC = RD;
9608 bool IsCorrect = true;
9609 for (auto *I : DC->decls()) {
9610 if (I) {
9611 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9612 if (MD->isStatic()) {
9613 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9614 SemaRef.Diag(MD->getLocation(),
9615 diag::note_omp_static_member_in_target);
9616 IsCorrect = false;
9617 }
9618 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9619 if (VD->isStaticDataMember()) {
9620 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9621 SemaRef.Diag(VD->getLocation(),
9622 diag::note_omp_static_member_in_target);
9623 IsCorrect = false;
9624 }
9625 }
9626 }
9627 }
9628
9629 for (auto &I : RD->bases()) {
9630 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9631 I.getType()->getAsCXXRecordDecl()))
9632 IsCorrect = false;
9633 }
9634 return IsCorrect;
9635}
9636
9637static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9638 DSAStackTy *Stack, QualType QTy) {
9639 NamedDecl *ND;
9640 if (QTy->isIncompleteType(&ND)) {
9641 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9642 return false;
9643 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009644 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009645 return false;
9646 }
9647 return true;
9648}
9649
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009650/// \brief Return true if it can be proven that the provided array expression
9651/// (array section or array subscript) does NOT specify the whole size of the
9652/// array whose base type is \a BaseQTy.
9653static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9654 const Expr *E,
9655 QualType BaseQTy) {
9656 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9657
9658 // If this is an array subscript, it refers to the whole size if the size of
9659 // the dimension is constant and equals 1. Also, an array section assumes the
9660 // format of an array subscript if no colon is used.
9661 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9662 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9663 return ATy->getSize().getSExtValue() != 1;
9664 // Size can't be evaluated statically.
9665 return false;
9666 }
9667
9668 assert(OASE && "Expecting array section if not an array subscript.");
9669 auto *LowerBound = OASE->getLowerBound();
9670 auto *Length = OASE->getLength();
9671
9672 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009673 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009674 if (LowerBound) {
9675 llvm::APSInt ConstLowerBound;
9676 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9677 return false; // Can't get the integer value as a constant.
9678 if (ConstLowerBound.getSExtValue())
9679 return true;
9680 }
9681
9682 // If we don't have a length we covering the whole dimension.
9683 if (!Length)
9684 return false;
9685
9686 // If the base is a pointer, we don't have a way to get the size of the
9687 // pointee.
9688 if (BaseQTy->isPointerType())
9689 return false;
9690
9691 // We can only check if the length is the same as the size of the dimension
9692 // if we have a constant array.
9693 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9694 if (!CATy)
9695 return false;
9696
9697 llvm::APSInt ConstLength;
9698 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9699 return false; // Can't get the integer value as a constant.
9700
9701 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9702}
9703
9704// Return true if it can be proven that the provided array expression (array
9705// section or array subscript) does NOT specify a single element of the array
9706// whose base type is \a BaseQTy.
9707static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009708 const Expr *E,
9709 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009710 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9711
9712 // An array subscript always refer to a single element. Also, an array section
9713 // assumes the format of an array subscript if no colon is used.
9714 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9715 return false;
9716
9717 assert(OASE && "Expecting array section if not an array subscript.");
9718 auto *Length = OASE->getLength();
9719
9720 // If we don't have a length we have to check if the array has unitary size
9721 // for this dimension. Also, we should always expect a length if the base type
9722 // is pointer.
9723 if (!Length) {
9724 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9725 return ATy->getSize().getSExtValue() != 1;
9726 // We cannot assume anything.
9727 return false;
9728 }
9729
9730 // Check if the length evaluates to 1.
9731 llvm::APSInt ConstLength;
9732 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9733 return false; // Can't get the integer value as a constant.
9734
9735 return ConstLength.getSExtValue() != 1;
9736}
9737
Samuel Antao661c0902016-05-26 17:39:58 +00009738// Return the expression of the base of the mappable expression or null if it
9739// cannot be determined and do all the necessary checks to see if the expression
9740// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009741// components of the expression.
9742static Expr *CheckMapClauseExpressionBase(
9743 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009744 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9745 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009746 SourceLocation ELoc = E->getExprLoc();
9747 SourceRange ERange = E->getSourceRange();
9748
9749 // The base of elements of list in a map clause have to be either:
9750 // - a reference to variable or field.
9751 // - a member expression.
9752 // - an array expression.
9753 //
9754 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9755 // reference to 'r'.
9756 //
9757 // If we have:
9758 //
9759 // struct SS {
9760 // Bla S;
9761 // foo() {
9762 // #pragma omp target map (S.Arr[:12]);
9763 // }
9764 // }
9765 //
9766 // We want to retrieve the member expression 'this->S';
9767
9768 Expr *RelevantExpr = nullptr;
9769
Samuel Antao5de996e2016-01-22 20:21:36 +00009770 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9771 // If a list item is an array section, it must specify contiguous storage.
9772 //
9773 // For this restriction it is sufficient that we make sure only references
9774 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009775 // exist except in the rightmost expression (unless they cover the whole
9776 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009777 //
9778 // r.ArrS[3:5].Arr[6:7]
9779 //
9780 // r.ArrS[3:5].x
9781 //
9782 // but these would be valid:
9783 // r.ArrS[3].Arr[6:7]
9784 //
9785 // r.ArrS[3].x
9786
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009787 bool AllowUnitySizeArraySection = true;
9788 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009789
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009790 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009791 E = E->IgnoreParenImpCasts();
9792
9793 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9794 if (!isa<VarDecl>(CurE->getDecl()))
9795 break;
9796
9797 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009798
9799 // If we got a reference to a declaration, we should not expect any array
9800 // section before that.
9801 AllowUnitySizeArraySection = false;
9802 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009803
9804 // Record the component.
9805 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9806 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009807 continue;
9808 }
9809
9810 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9811 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9812
9813 if (isa<CXXThisExpr>(BaseE))
9814 // We found a base expression: this->Val.
9815 RelevantExpr = CurE;
9816 else
9817 E = BaseE;
9818
9819 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9820 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9821 << CurE->getSourceRange();
9822 break;
9823 }
9824
9825 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9826
9827 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9828 // A bit-field cannot appear in a map clause.
9829 //
9830 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009831 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9832 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009833 break;
9834 }
9835
9836 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9837 // If the type of a list item is a reference to a type T then the type
9838 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009839 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009840
9841 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9842 // A list item cannot be a variable that is a member of a structure with
9843 // a union type.
9844 //
9845 if (auto *RT = CurType->getAs<RecordType>())
9846 if (RT->isUnionType()) {
9847 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9848 << CurE->getSourceRange();
9849 break;
9850 }
9851
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009852 // If we got a member expression, we should not expect any array section
9853 // before that:
9854 //
9855 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9856 // If a list item is an element of a structure, only the rightmost symbol
9857 // of the variable reference can be an array section.
9858 //
9859 AllowUnitySizeArraySection = false;
9860 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009861
9862 // Record the component.
9863 CurComponents.push_back(
9864 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009865 continue;
9866 }
9867
9868 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9869 E = CurE->getBase()->IgnoreParenImpCasts();
9870
9871 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9872 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9873 << 0 << CurE->getSourceRange();
9874 break;
9875 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009876
9877 // If we got an array subscript that express the whole dimension we
9878 // can have any array expressions before. If it only expressing part of
9879 // the dimension, we can only have unitary-size array expressions.
9880 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9881 E->getType()))
9882 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009883
9884 // Record the component - we don't have any declaration associated.
9885 CurComponents.push_back(
9886 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009887 continue;
9888 }
9889
9890 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009891 E = CurE->getBase()->IgnoreParenImpCasts();
9892
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009893 auto CurType =
9894 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9895
Samuel Antao5de996e2016-01-22 20:21:36 +00009896 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9897 // If the type of a list item is a reference to a type T then the type
9898 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009899 if (CurType->isReferenceType())
9900 CurType = CurType->getPointeeType();
9901
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009902 bool IsPointer = CurType->isAnyPointerType();
9903
9904 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009905 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9906 << 0 << CurE->getSourceRange();
9907 break;
9908 }
9909
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009910 bool NotWhole =
9911 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9912 bool NotUnity =
9913 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9914
Samuel Antaodab51bb2016-07-18 23:22:11 +00009915 if (AllowWholeSizeArraySection) {
9916 // Any array section is currently allowed. Allowing a whole size array
9917 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009918 //
9919 // If this array section refers to the whole dimension we can still
9920 // accept other array sections before this one, except if the base is a
9921 // pointer. Otherwise, only unitary sections are accepted.
9922 if (NotWhole || IsPointer)
9923 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009924 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009925 // A unity or whole array section is not allowed and that is not
9926 // compatible with the properties of the current array section.
9927 SemaRef.Diag(
9928 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9929 << CurE->getSourceRange();
9930 break;
9931 }
Samuel Antao90927002016-04-26 14:54:23 +00009932
9933 // Record the component - we don't have any declaration associated.
9934 CurComponents.push_back(
9935 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009936 continue;
9937 }
9938
9939 // If nothing else worked, this is not a valid map clause expression.
9940 SemaRef.Diag(ELoc,
9941 diag::err_omp_expected_named_var_member_or_array_expression)
9942 << ERange;
9943 break;
9944 }
9945
9946 return RelevantExpr;
9947}
9948
9949// Return true if expression E associated with value VD has conflicts with other
9950// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009951static bool CheckMapConflicts(
9952 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9953 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009954 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9955 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009956 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009957 SourceLocation ELoc = E->getExprLoc();
9958 SourceRange ERange = E->getSourceRange();
9959
9960 // In order to easily check the conflicts we need to match each component of
9961 // the expression under test with the components of the expressions that are
9962 // already in the stack.
9963
Samuel Antao5de996e2016-01-22 20:21:36 +00009964 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009965 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009966 "Map clause expression with unexpected base!");
9967
9968 // Variables to help detecting enclosing problems in data environment nests.
9969 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009970 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009971
Samuel Antao90927002016-04-26 14:54:23 +00009972 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9973 VD, CurrentRegionOnly,
9974 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009975 StackComponents,
9976 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009977
Samuel Antao5de996e2016-01-22 20:21:36 +00009978 assert(!StackComponents.empty() &&
9979 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009980 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009981 "Map clause expression with unexpected base!");
9982
Samuel Antao90927002016-04-26 14:54:23 +00009983 // The whole expression in the stack.
9984 auto *RE = StackComponents.front().getAssociatedExpression();
9985
Samuel Antao5de996e2016-01-22 20:21:36 +00009986 // Expressions must start from the same base. Here we detect at which
9987 // point both expressions diverge from each other and see if we can
9988 // detect if the memory referred to both expressions is contiguous and
9989 // do not overlap.
9990 auto CI = CurComponents.rbegin();
9991 auto CE = CurComponents.rend();
9992 auto SI = StackComponents.rbegin();
9993 auto SE = StackComponents.rend();
9994 for (; CI != CE && SI != SE; ++CI, ++SI) {
9995
9996 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9997 // At most one list item can be an array item derived from a given
9998 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009999 if (CurrentRegionOnly &&
10000 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10001 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10002 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10003 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10004 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010005 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010006 << CI->getAssociatedExpression()->getSourceRange();
10007 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10008 diag::note_used_here)
10009 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010010 return true;
10011 }
10012
10013 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010014 if (CI->getAssociatedExpression()->getStmtClass() !=
10015 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010016 break;
10017
10018 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010019 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010020 break;
10021 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010022 // Check if the extra components of the expressions in the enclosing
10023 // data environment are redundant for the current base declaration.
10024 // If they are, the maps completely overlap, which is legal.
10025 for (; SI != SE; ++SI) {
10026 QualType Type;
10027 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010028 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010029 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010030 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10031 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010032 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10033 Type =
10034 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10035 }
10036 if (Type.isNull() || Type->isAnyPointerType() ||
10037 CheckArrayExpressionDoesNotReferToWholeSize(
10038 SemaRef, SI->getAssociatedExpression(), Type))
10039 break;
10040 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010041
10042 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10043 // List items of map clauses in the same construct must not share
10044 // original storage.
10045 //
10046 // If the expressions are exactly the same or one is a subset of the
10047 // other, it means they are sharing storage.
10048 if (CI == CE && SI == SE) {
10049 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010050 if (CKind == OMPC_map)
10051 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10052 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010053 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010054 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10055 << ERange;
10056 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010057 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10058 << RE->getSourceRange();
10059 return true;
10060 } else {
10061 // If we find the same expression in the enclosing data environment,
10062 // that is legal.
10063 IsEnclosedByDataEnvironmentExpr = true;
10064 return false;
10065 }
10066 }
10067
Samuel Antao90927002016-04-26 14:54:23 +000010068 QualType DerivedType =
10069 std::prev(CI)->getAssociatedDeclaration()->getType();
10070 SourceLocation DerivedLoc =
10071 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010072
10073 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10074 // If the type of a list item is a reference to a type T then the type
10075 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010076 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010077
10078 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10079 // A variable for which the type is pointer and an array section
10080 // derived from that variable must not appear as list items of map
10081 // clauses of the same construct.
10082 //
10083 // Also, cover one of the cases in:
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
10087 // must have corresponding storage in the device data environment.
10088 //
10089 if (DerivedType->isAnyPointerType()) {
10090 if (CI == CE || SI == SE) {
10091 SemaRef.Diag(
10092 DerivedLoc,
10093 diag::err_omp_pointer_mapped_along_with_derived_section)
10094 << DerivedLoc;
10095 } else {
10096 assert(CI != CE && SI != SE);
10097 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10098 << DerivedLoc;
10099 }
10100 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10101 << RE->getSourceRange();
10102 return true;
10103 }
10104
10105 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10106 // List items of map clauses in the same construct must not share
10107 // original storage.
10108 //
10109 // An expression is a subset of the other.
10110 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010111 if (CKind == OMPC_map)
10112 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10113 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010114 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010115 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10116 << ERange;
10117 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010118 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10119 << RE->getSourceRange();
10120 return true;
10121 }
10122
10123 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010124 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010125 if (!CurrentRegionOnly && SI != SE)
10126 EnclosingExpr = RE;
10127
10128 // The current expression is a subset of the expression in the data
10129 // environment.
10130 IsEnclosedByDataEnvironmentExpr |=
10131 (!CurrentRegionOnly && CI != CE && SI == SE);
10132
10133 return false;
10134 });
10135
10136 if (CurrentRegionOnly)
10137 return FoundError;
10138
10139 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10140 // If any part of the original storage of a list item has corresponding
10141 // storage in the device data environment, all of the original storage must
10142 // have corresponding storage in the device data environment.
10143 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10144 // If a list item is an element of a structure, and a different element of
10145 // the structure has a corresponding list item in the device data environment
10146 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010147 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010148 // data environment prior to the task encountering the construct.
10149 //
10150 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10151 SemaRef.Diag(ELoc,
10152 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10153 << ERange;
10154 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10155 << EnclosingExpr->getSourceRange();
10156 return true;
10157 }
10158
10159 return FoundError;
10160}
10161
Samuel Antao661c0902016-05-26 17:39:58 +000010162namespace {
10163// Utility struct that gathers all the related lists associated with a mappable
10164// expression.
10165struct MappableVarListInfo final {
10166 // The list of expressions.
10167 ArrayRef<Expr *> VarList;
10168 // The list of processed expressions.
10169 SmallVector<Expr *, 16> ProcessedVarList;
10170 // The mappble components for each expression.
10171 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10172 // The base declaration of the variable.
10173 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10174
10175 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10176 // We have a list of components and base declarations for each entry in the
10177 // variable list.
10178 VarComponents.reserve(VarList.size());
10179 VarBaseDeclarations.reserve(VarList.size());
10180 }
10181};
10182}
10183
10184// Check the validity of the provided variable list for the provided clause kind
10185// \a CKind. In the check process the valid expressions, and mappable expression
10186// components and variables are extracted and used to fill \a Vars,
10187// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10188// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10189static void
10190checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10191 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10192 SourceLocation StartLoc,
10193 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10194 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010195 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10196 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010197 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010198
Samuel Antao90927002016-04-26 14:54:23 +000010199 // Keep track of the mappable components and base declarations in this clause.
10200 // Each entry in the list is going to have a list of components associated. We
10201 // record each set of the components so that we can build the clause later on.
10202 // In the end we should have the same amount of declarations and component
10203 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010204
Samuel Antao661c0902016-05-26 17:39:58 +000010205 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010206 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010207 SourceLocation ELoc = RE->getExprLoc();
10208
Kelvin Li0bff7af2015-11-23 05:32:03 +000010209 auto *VE = RE->IgnoreParenLValueCasts();
10210
10211 if (VE->isValueDependent() || VE->isTypeDependent() ||
10212 VE->isInstantiationDependent() ||
10213 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010214 // We can only analyze this information once the missing information is
10215 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010216 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010217 continue;
10218 }
10219
10220 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010221
Samuel Antao5de996e2016-01-22 20:21:36 +000010222 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010223 SemaRef.Diag(ELoc,
10224 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010225 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010226 continue;
10227 }
10228
Samuel Antao90927002016-04-26 14:54:23 +000010229 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10230 ValueDecl *CurDeclaration = nullptr;
10231
10232 // Obtain the array or member expression bases if required. Also, fill the
10233 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010234 auto *BE =
10235 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010236 if (!BE)
10237 continue;
10238
Samuel Antao90927002016-04-26 14:54:23 +000010239 assert(!CurComponents.empty() &&
10240 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010241
Samuel Antao90927002016-04-26 14:54:23 +000010242 // For the following checks, we rely on the base declaration which is
10243 // expected to be associated with the last component. The declaration is
10244 // expected to be a variable or a field (if 'this' is being mapped).
10245 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10246 assert(CurDeclaration && "Null decl on map clause.");
10247 assert(
10248 CurDeclaration->isCanonicalDecl() &&
10249 "Expecting components to have associated only canonical declarations.");
10250
10251 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10252 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010253
10254 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010255 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010256
10257 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010258 // threadprivate variables cannot appear in a map clause.
10259 // OpenMP 4.5 [2.10.5, target update Construct]
10260 // threadprivate variables cannot appear in a from clause.
10261 if (VD && DSAS->isThreadPrivate(VD)) {
10262 auto DVar = DSAS->getTopDSA(VD, false);
10263 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10264 << getOpenMPClauseName(CKind);
10265 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010266 continue;
10267 }
10268
Samuel Antao5de996e2016-01-22 20:21:36 +000010269 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10270 // A list item cannot appear in both a map clause and a data-sharing
10271 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010272
Samuel Antao5de996e2016-01-22 20:21:36 +000010273 // Check conflicts with other map clause expressions. We check the conflicts
10274 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010275 // environment, because the restrictions are different. We only have to
10276 // check conflicts across regions for the map clauses.
10277 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10278 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010279 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010280 if (CKind == OMPC_map &&
10281 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10282 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010283 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010284
Samuel Antao661c0902016-05-26 17:39:58 +000010285 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010286 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10287 // If the type of a list item is a reference to a type T then the type will
10288 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010289 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010290
Samuel Antao661c0902016-05-26 17:39:58 +000010291 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10292 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010293 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010294 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010295 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10296 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010297 continue;
10298
Samuel Antao661c0902016-05-26 17:39:58 +000010299 if (CKind == OMPC_map) {
10300 // target enter data
10301 // OpenMP [2.10.2, Restrictions, p. 99]
10302 // A map-type must be specified in all map clauses and must be either
10303 // to or alloc.
10304 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10305 if (DKind == OMPD_target_enter_data &&
10306 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10307 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10308 << (IsMapTypeImplicit ? 1 : 0)
10309 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10310 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010311 continue;
10312 }
Samuel Antao661c0902016-05-26 17:39:58 +000010313
10314 // target exit_data
10315 // OpenMP [2.10.3, Restrictions, p. 102]
10316 // A map-type must be specified in all map clauses and must be either
10317 // from, release, or delete.
10318 if (DKind == OMPD_target_exit_data &&
10319 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10320 MapType == OMPC_MAP_delete)) {
10321 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10322 << (IsMapTypeImplicit ? 1 : 0)
10323 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10324 << getOpenMPDirectiveName(DKind);
10325 continue;
10326 }
10327
10328 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10329 // A list item cannot appear in both a map clause and a data-sharing
10330 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010331 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010332 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010333 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010334 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10335 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010336 auto DVar = DSAS->getTopDSA(VD, false);
10337 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010338 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010339 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010340 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010341 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10342 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10343 continue;
10344 }
10345 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010346 }
10347
Samuel Antao90927002016-04-26 14:54:23 +000010348 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010349 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010350
10351 // Store the components in the stack so that they can be used to check
10352 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010353 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10354 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010355
10356 // Save the components and declaration to create the clause. For purposes of
10357 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010358 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010359 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10360 MVLI.VarComponents.back().append(CurComponents.begin(),
10361 CurComponents.end());
10362 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10363 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010364 }
Samuel Antao661c0902016-05-26 17:39:58 +000010365}
10366
10367OMPClause *
10368Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10369 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10370 SourceLocation MapLoc, SourceLocation ColonLoc,
10371 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10372 SourceLocation LParenLoc, SourceLocation EndLoc) {
10373 MappableVarListInfo MVLI(VarList);
10374 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10375 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010376
Samuel Antao5de996e2016-01-22 20:21:36 +000010377 // We need to produce a map clause even if we don't have variables so that
10378 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010379 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10380 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10381 MVLI.VarComponents, MapTypeModifier, MapType,
10382 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010383}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010384
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010385QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10386 TypeResult ParsedType) {
10387 assert(ParsedType.isUsable());
10388
10389 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10390 if (ReductionType.isNull())
10391 return QualType();
10392
10393 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10394 // A type name in a declare reduction directive cannot be a function type, an
10395 // array type, a reference type, or a type qualified with const, volatile or
10396 // restrict.
10397 if (ReductionType.hasQualifiers()) {
10398 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10399 return QualType();
10400 }
10401
10402 if (ReductionType->isFunctionType()) {
10403 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10404 return QualType();
10405 }
10406 if (ReductionType->isReferenceType()) {
10407 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10408 return QualType();
10409 }
10410 if (ReductionType->isArrayType()) {
10411 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10412 return QualType();
10413 }
10414 return ReductionType;
10415}
10416
10417Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10418 Scope *S, DeclContext *DC, DeclarationName Name,
10419 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10420 AccessSpecifier AS, Decl *PrevDeclInScope) {
10421 SmallVector<Decl *, 8> Decls;
10422 Decls.reserve(ReductionTypes.size());
10423
10424 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10425 ForRedeclaration);
10426 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10427 // A reduction-identifier may not be re-declared in the current scope for the
10428 // same type or for a type that is compatible according to the base language
10429 // rules.
10430 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10431 OMPDeclareReductionDecl *PrevDRD = nullptr;
10432 bool InCompoundScope = true;
10433 if (S != nullptr) {
10434 // Find previous declaration with the same name not referenced in other
10435 // declarations.
10436 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10437 InCompoundScope =
10438 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10439 LookupName(Lookup, S);
10440 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10441 /*AllowInlineNamespace=*/false);
10442 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10443 auto Filter = Lookup.makeFilter();
10444 while (Filter.hasNext()) {
10445 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10446 if (InCompoundScope) {
10447 auto I = UsedAsPrevious.find(PrevDecl);
10448 if (I == UsedAsPrevious.end())
10449 UsedAsPrevious[PrevDecl] = false;
10450 if (auto *D = PrevDecl->getPrevDeclInScope())
10451 UsedAsPrevious[D] = true;
10452 }
10453 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10454 PrevDecl->getLocation();
10455 }
10456 Filter.done();
10457 if (InCompoundScope) {
10458 for (auto &PrevData : UsedAsPrevious) {
10459 if (!PrevData.second) {
10460 PrevDRD = PrevData.first;
10461 break;
10462 }
10463 }
10464 }
10465 } else if (PrevDeclInScope != nullptr) {
10466 auto *PrevDRDInScope = PrevDRD =
10467 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10468 do {
10469 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10470 PrevDRDInScope->getLocation();
10471 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10472 } while (PrevDRDInScope != nullptr);
10473 }
10474 for (auto &TyData : ReductionTypes) {
10475 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10476 bool Invalid = false;
10477 if (I != PreviousRedeclTypes.end()) {
10478 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10479 << TyData.first;
10480 Diag(I->second, diag::note_previous_definition);
10481 Invalid = true;
10482 }
10483 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10484 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10485 Name, TyData.first, PrevDRD);
10486 DC->addDecl(DRD);
10487 DRD->setAccess(AS);
10488 Decls.push_back(DRD);
10489 if (Invalid)
10490 DRD->setInvalidDecl();
10491 else
10492 PrevDRD = DRD;
10493 }
10494
10495 return DeclGroupPtrTy::make(
10496 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10497}
10498
10499void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10500 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10501
10502 // Enter new function scope.
10503 PushFunctionScope();
10504 getCurFunction()->setHasBranchProtectedScope();
10505 getCurFunction()->setHasOMPDeclareReductionCombiner();
10506
10507 if (S != nullptr)
10508 PushDeclContext(S, DRD);
10509 else
10510 CurContext = DRD;
10511
10512 PushExpressionEvaluationContext(PotentiallyEvaluated);
10513
10514 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010515 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10516 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10517 // uses semantics of argument handles by value, but it should be passed by
10518 // reference. C lang does not support references, so pass all parameters as
10519 // pointers.
10520 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010521 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010522 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010523 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10524 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10525 // uses semantics of argument handles by value, but it should be passed by
10526 // reference. C lang does not support references, so pass all parameters as
10527 // pointers.
10528 // Create 'T omp_out;' variable.
10529 auto *OmpOutParm =
10530 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10531 if (S != nullptr) {
10532 PushOnScopeChains(OmpInParm, S);
10533 PushOnScopeChains(OmpOutParm, S);
10534 } else {
10535 DRD->addDecl(OmpInParm);
10536 DRD->addDecl(OmpOutParm);
10537 }
10538}
10539
10540void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10541 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10542 DiscardCleanupsInEvaluationContext();
10543 PopExpressionEvaluationContext();
10544
10545 PopDeclContext();
10546 PopFunctionScopeInfo();
10547
10548 if (Combiner != nullptr)
10549 DRD->setCombiner(Combiner);
10550 else
10551 DRD->setInvalidDecl();
10552}
10553
10554void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10555 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10556
10557 // Enter new function scope.
10558 PushFunctionScope();
10559 getCurFunction()->setHasBranchProtectedScope();
10560
10561 if (S != nullptr)
10562 PushDeclContext(S, DRD);
10563 else
10564 CurContext = DRD;
10565
10566 PushExpressionEvaluationContext(PotentiallyEvaluated);
10567
10568 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010569 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10570 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10571 // uses semantics of argument handles by value, but it should be passed by
10572 // reference. C lang does not support references, so pass all parameters as
10573 // pointers.
10574 // Create 'T omp_priv;' variable.
10575 auto *OmpPrivParm =
10576 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010577 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10578 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10579 // uses semantics of argument handles by value, but it should be passed by
10580 // reference. C lang does not support references, so pass all parameters as
10581 // pointers.
10582 // Create 'T omp_orig;' variable.
10583 auto *OmpOrigParm =
10584 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010585 if (S != nullptr) {
10586 PushOnScopeChains(OmpPrivParm, S);
10587 PushOnScopeChains(OmpOrigParm, S);
10588 } else {
10589 DRD->addDecl(OmpPrivParm);
10590 DRD->addDecl(OmpOrigParm);
10591 }
10592}
10593
10594void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10595 Expr *Initializer) {
10596 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10597 DiscardCleanupsInEvaluationContext();
10598 PopExpressionEvaluationContext();
10599
10600 PopDeclContext();
10601 PopFunctionScopeInfo();
10602
10603 if (Initializer != nullptr)
10604 DRD->setInitializer(Initializer);
10605 else
10606 DRD->setInvalidDecl();
10607}
10608
10609Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10610 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10611 for (auto *D : DeclReductions.get()) {
10612 if (IsValid) {
10613 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10614 if (S != nullptr)
10615 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10616 } else
10617 D->setInvalidDecl();
10618 }
10619 return DeclReductions;
10620}
10621
David Majnemer9d168222016-08-05 17:44:54 +000010622OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010623 SourceLocation StartLoc,
10624 SourceLocation LParenLoc,
10625 SourceLocation EndLoc) {
10626 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010627
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010628 // OpenMP [teams Constrcut, Restrictions]
10629 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010630 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10631 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010632 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010633
10634 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10635}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010636
10637OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10638 SourceLocation StartLoc,
10639 SourceLocation LParenLoc,
10640 SourceLocation EndLoc) {
10641 Expr *ValExpr = ThreadLimit;
10642
10643 // OpenMP [teams Constrcut, Restrictions]
10644 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010645 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10646 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010647 return nullptr;
10648
David Majnemer9d168222016-08-05 17:44:54 +000010649 return new (Context)
10650 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010651}
Alexey Bataeva0569352015-12-01 10:17:31 +000010652
10653OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10654 SourceLocation StartLoc,
10655 SourceLocation LParenLoc,
10656 SourceLocation EndLoc) {
10657 Expr *ValExpr = Priority;
10658
10659 // OpenMP [2.9.1, task Constrcut]
10660 // The priority-value is a non-negative numerical scalar expression.
10661 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10662 /*StrictlyPositive=*/false))
10663 return nullptr;
10664
10665 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10666}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010667
10668OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10669 SourceLocation StartLoc,
10670 SourceLocation LParenLoc,
10671 SourceLocation EndLoc) {
10672 Expr *ValExpr = Grainsize;
10673
10674 // OpenMP [2.9.2, taskloop Constrcut]
10675 // The parameter of the grainsize clause must be a positive integer
10676 // expression.
10677 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10678 /*StrictlyPositive=*/true))
10679 return nullptr;
10680
10681 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10682}
Alexey Bataev382967a2015-12-08 12:06:20 +000010683
10684OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10685 SourceLocation StartLoc,
10686 SourceLocation LParenLoc,
10687 SourceLocation EndLoc) {
10688 Expr *ValExpr = NumTasks;
10689
10690 // OpenMP [2.9.2, taskloop Constrcut]
10691 // The parameter of the num_tasks clause must be a positive integer
10692 // expression.
10693 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10694 /*StrictlyPositive=*/true))
10695 return nullptr;
10696
10697 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10698}
10699
Alexey Bataev28c75412015-12-15 08:19:24 +000010700OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10701 SourceLocation LParenLoc,
10702 SourceLocation EndLoc) {
10703 // OpenMP [2.13.2, critical construct, Description]
10704 // ... where hint-expression is an integer constant expression that evaluates
10705 // to a valid lock hint.
10706 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10707 if (HintExpr.isInvalid())
10708 return nullptr;
10709 return new (Context)
10710 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10711}
10712
Carlo Bertollib4adf552016-01-15 18:50:31 +000010713OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10714 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10715 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10716 SourceLocation EndLoc) {
10717 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10718 std::string Values;
10719 Values += "'";
10720 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10721 Values += "'";
10722 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10723 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10724 return nullptr;
10725 }
10726 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010727 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010728 if (ChunkSize) {
10729 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10730 !ChunkSize->isInstantiationDependent() &&
10731 !ChunkSize->containsUnexpandedParameterPack()) {
10732 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10733 ExprResult Val =
10734 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10735 if (Val.isInvalid())
10736 return nullptr;
10737
10738 ValExpr = Val.get();
10739
10740 // OpenMP [2.7.1, Restrictions]
10741 // chunk_size must be a loop invariant integer expression with a positive
10742 // value.
10743 llvm::APSInt Result;
10744 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10745 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10746 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10747 << "dist_schedule" << ChunkSize->getSourceRange();
10748 return nullptr;
10749 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010750 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10751 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010752 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10753 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10754 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010755 }
10756 }
10757 }
10758
10759 return new (Context)
10760 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010761 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010762}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010763
10764OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10765 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10766 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10767 SourceLocation KindLoc, SourceLocation EndLoc) {
10768 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010769 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010770 std::string Value;
10771 SourceLocation Loc;
10772 Value += "'";
10773 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10774 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010775 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010776 Loc = MLoc;
10777 } else {
10778 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010779 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010780 Loc = KindLoc;
10781 }
10782 Value += "'";
10783 Diag(Loc, diag::err_omp_unexpected_clause_value)
10784 << Value << getOpenMPClauseName(OMPC_defaultmap);
10785 return nullptr;
10786 }
10787
10788 return new (Context)
10789 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10790}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010791
10792bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10793 DeclContext *CurLexicalContext = getCurLexicalContext();
10794 if (!CurLexicalContext->isFileContext() &&
10795 !CurLexicalContext->isExternCContext() &&
10796 !CurLexicalContext->isExternCXXContext()) {
10797 Diag(Loc, diag::err_omp_region_not_file_context);
10798 return false;
10799 }
10800 if (IsInOpenMPDeclareTargetContext) {
10801 Diag(Loc, diag::err_omp_enclosed_declare_target);
10802 return false;
10803 }
10804
10805 IsInOpenMPDeclareTargetContext = true;
10806 return true;
10807}
10808
10809void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10810 assert(IsInOpenMPDeclareTargetContext &&
10811 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10812
10813 IsInOpenMPDeclareTargetContext = false;
10814}
10815
David Majnemer9d168222016-08-05 17:44:54 +000010816void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10817 CXXScopeSpec &ScopeSpec,
10818 const DeclarationNameInfo &Id,
10819 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10820 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010821 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10822 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10823
10824 if (Lookup.isAmbiguous())
10825 return;
10826 Lookup.suppressDiagnostics();
10827
10828 if (!Lookup.isSingleResult()) {
10829 if (TypoCorrection Corrected =
10830 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10831 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10832 CTK_ErrorRecovery)) {
10833 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10834 << Id.getName());
10835 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10836 return;
10837 }
10838
10839 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10840 return;
10841 }
10842
10843 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10844 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10845 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10846 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10847
10848 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10849 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10850 ND->addAttr(A);
10851 if (ASTMutationListener *ML = Context.getASTMutationListener())
10852 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10853 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10854 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10855 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10856 << Id.getName();
10857 }
10858 } else
10859 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10860}
10861
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010862static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10863 Sema &SemaRef, Decl *D) {
10864 if (!D)
10865 return;
10866 Decl *LD = nullptr;
10867 if (isa<TagDecl>(D)) {
10868 LD = cast<TagDecl>(D)->getDefinition();
10869 } else if (isa<VarDecl>(D)) {
10870 LD = cast<VarDecl>(D)->getDefinition();
10871
10872 // If this is an implicit variable that is legal and we do not need to do
10873 // anything.
10874 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010875 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10876 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10877 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010878 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010879 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010880 return;
10881 }
10882
10883 } else if (isa<FunctionDecl>(D)) {
10884 const FunctionDecl *FD = nullptr;
10885 if (cast<FunctionDecl>(D)->hasBody(FD))
10886 LD = const_cast<FunctionDecl *>(FD);
10887
10888 // If the definition is associated with the current declaration in the
10889 // target region (it can be e.g. a lambda) that is legal and we do not need
10890 // to do anything else.
10891 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010892 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10893 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10894 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010895 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010896 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010897 return;
10898 }
10899 }
10900 if (!LD)
10901 LD = D;
10902 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10903 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10904 // Outlined declaration is not declared target.
10905 if (LD->isOutOfLine()) {
10906 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10907 SemaRef.Diag(SL, diag::note_used_here) << SR;
10908 } else {
10909 DeclContext *DC = LD->getDeclContext();
10910 while (DC) {
10911 if (isa<FunctionDecl>(DC) &&
10912 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10913 break;
10914 DC = DC->getParent();
10915 }
10916 if (DC)
10917 return;
10918
10919 // Is not declared in target context.
10920 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10921 SemaRef.Diag(SL, diag::note_used_here) << SR;
10922 }
10923 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010924 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10925 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10926 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010927 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010928 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010929 }
10930}
10931
10932static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10933 Sema &SemaRef, DSAStackTy *Stack,
10934 ValueDecl *VD) {
10935 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10936 return true;
10937 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10938 return false;
10939 return true;
10940}
10941
10942void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10943 if (!D || D->isInvalidDecl())
10944 return;
10945 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10946 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10947 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10948 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10949 if (DSAStack->isThreadPrivate(VD)) {
10950 Diag(SL, diag::err_omp_threadprivate_in_target);
10951 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10952 return;
10953 }
10954 }
10955 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10956 // Problem if any with var declared with incomplete type will be reported
10957 // as normal, so no need to check it here.
10958 if ((E || !VD->getType()->isIncompleteType()) &&
10959 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10960 // Mark decl as declared target to prevent further diagnostic.
10961 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010962 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10963 Context, OMPDeclareTargetDeclAttr::MT_To);
10964 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010965 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010966 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010967 }
10968 return;
10969 }
10970 }
10971 if (!E) {
10972 // Checking declaration inside declare target region.
10973 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10974 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010975 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10976 Context, OMPDeclareTargetDeclAttr::MT_To);
10977 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010978 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010979 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010980 }
10981 return;
10982 }
10983 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10984}
Samuel Antao661c0902016-05-26 17:39:58 +000010985
10986OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10987 SourceLocation StartLoc,
10988 SourceLocation LParenLoc,
10989 SourceLocation EndLoc) {
10990 MappableVarListInfo MVLI(VarList);
10991 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10992 if (MVLI.ProcessedVarList.empty())
10993 return nullptr;
10994
10995 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10996 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10997 MVLI.VarComponents);
10998}
Samuel Antaoec172c62016-05-26 17:49:04 +000010999
11000OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11001 SourceLocation StartLoc,
11002 SourceLocation LParenLoc,
11003 SourceLocation EndLoc) {
11004 MappableVarListInfo MVLI(VarList);
11005 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11006 if (MVLI.ProcessedVarList.empty())
11007 return nullptr;
11008
11009 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11010 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11011 MVLI.VarComponents);
11012}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011013
11014OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11015 SourceLocation StartLoc,
11016 SourceLocation LParenLoc,
11017 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011018 MappableVarListInfo MVLI(VarList);
11019 SmallVector<Expr *, 8> PrivateCopies;
11020 SmallVector<Expr *, 8> Inits;
11021
Carlo Bertolli2404b172016-07-13 15:37:16 +000011022 for (auto &RefExpr : VarList) {
11023 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11024 SourceLocation ELoc;
11025 SourceRange ERange;
11026 Expr *SimpleRefExpr = RefExpr;
11027 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11028 if (Res.second) {
11029 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011030 MVLI.ProcessedVarList.push_back(RefExpr);
11031 PrivateCopies.push_back(nullptr);
11032 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011033 }
11034 ValueDecl *D = Res.first;
11035 if (!D)
11036 continue;
11037
11038 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011039 Type = Type.getNonReferenceType().getUnqualifiedType();
11040
11041 auto *VD = dyn_cast<VarDecl>(D);
11042
11043 // Item should be a pointer or reference to pointer.
11044 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011045 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11046 << 0 << RefExpr->getSourceRange();
11047 continue;
11048 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011049
11050 // Build the private variable and the expression that refers to it.
11051 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11052 D->hasAttrs() ? &D->getAttrs() : nullptr);
11053 if (VDPrivate->isInvalidDecl())
11054 continue;
11055
11056 CurContext->addDecl(VDPrivate);
11057 auto VDPrivateRefExpr = buildDeclRefExpr(
11058 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11059
11060 // Add temporary variable to initialize the private copy of the pointer.
11061 auto *VDInit =
11062 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11063 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11064 RefExpr->getExprLoc());
11065 AddInitializerToDecl(VDPrivate,
11066 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011067 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011068
11069 // If required, build a capture to implement the privatization initialized
11070 // with the current list item value.
11071 DeclRefExpr *Ref = nullptr;
11072 if (!VD)
11073 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11074 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11075 PrivateCopies.push_back(VDPrivateRefExpr);
11076 Inits.push_back(VDInitRefExpr);
11077
11078 // We need to add a data sharing attribute for this variable to make sure it
11079 // is correctly captured. A variable that shows up in a use_device_ptr has
11080 // similar properties of a first private variable.
11081 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11082
11083 // Create a mappable component for the list item. List items in this clause
11084 // only need a component.
11085 MVLI.VarBaseDeclarations.push_back(D);
11086 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11087 MVLI.VarComponents.back().push_back(
11088 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011089 }
11090
Samuel Antaocc10b852016-07-28 14:23:26 +000011091 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011092 return nullptr;
11093
Samuel Antaocc10b852016-07-28 14:23:26 +000011094 return OMPUseDevicePtrClause::Create(
11095 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11096 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011097}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011098
11099OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11100 SourceLocation StartLoc,
11101 SourceLocation LParenLoc,
11102 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011103 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011104 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011105 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011106 SourceLocation ELoc;
11107 SourceRange ERange;
11108 Expr *SimpleRefExpr = RefExpr;
11109 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11110 if (Res.second) {
11111 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011112 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011113 }
11114 ValueDecl *D = Res.first;
11115 if (!D)
11116 continue;
11117
11118 QualType Type = D->getType();
11119 // item should be a pointer or array or reference to pointer or array
11120 if (!Type.getNonReferenceType()->isPointerType() &&
11121 !Type.getNonReferenceType()->isArrayType()) {
11122 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11123 << 0 << RefExpr->getSourceRange();
11124 continue;
11125 }
Samuel Antao6890b092016-07-28 14:25:09 +000011126
11127 // Check if the declaration in the clause does not show up in any data
11128 // sharing attribute.
11129 auto DVar = DSAStack->getTopDSA(D, false);
11130 if (isOpenMPPrivate(DVar.CKind)) {
11131 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11132 << getOpenMPClauseName(DVar.CKind)
11133 << getOpenMPClauseName(OMPC_is_device_ptr)
11134 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11135 ReportOriginalDSA(*this, DSAStack, D, DVar);
11136 continue;
11137 }
11138
11139 Expr *ConflictExpr;
11140 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011141 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011142 [&ConflictExpr](
11143 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11144 OpenMPClauseKind) -> bool {
11145 ConflictExpr = R.front().getAssociatedExpression();
11146 return true;
11147 })) {
11148 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11149 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11150 << ConflictExpr->getSourceRange();
11151 continue;
11152 }
11153
11154 // Store the components in the stack so that they can be used to check
11155 // against other clauses later on.
11156 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11157 DSAStack->addMappableExpressionComponents(
11158 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11159
11160 // Record the expression we've just processed.
11161 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11162
11163 // Create a mappable component for the list item. List items in this clause
11164 // only need a component. We use a null declaration to signal fields in
11165 // 'this'.
11166 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11167 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11168 "Unexpected device pointer expression!");
11169 MVLI.VarBaseDeclarations.push_back(
11170 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11171 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11172 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011173 }
11174
Samuel Antao6890b092016-07-28 14:25:09 +000011175 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011176 return nullptr;
11177
Samuel Antao6890b092016-07-28 14:25:09 +000011178 return OMPIsDevicePtrClause::Create(
11179 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11180 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011181}