blob: c384d5f16af420c5efc654779efd918a35726357 [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.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000121 DeclSAMapTy Threadprivates;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000122 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000123 /// \brief true, if check for DSA must be from parent directive, false, if
124 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000126 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000127 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000128 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000129
130 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
131
David Majnemer9d168222016-08-05 17:44:54 +0000132 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000133
134 /// \brief Checks if the variable is a local for OpenMP region.
135 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000136
Alexey Bataev758e55e2013-09-06 18:03:48 +0000137public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000138 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000139
Alexey Bataevaac108a2015-06-23 04:51:00 +0000140 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
141 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000142
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000143 bool isForceVarCapturing() const { return ForceCapturing; }
144 void setForceVarCapturing(bool V) { ForceCapturing = V; }
145
Alexey Bataev758e55e2013-09-06 18:03:48 +0000146 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000147 Scope *CurScope, SourceLocation Loc) {
148 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
149 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000150 }
151
152 void pop() {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000153 assert(!Stack.empty() && "Data-sharing attributes stack is empty!");
Alexey Bataev758e55e2013-09-06 18:03:48 +0000154 Stack.pop_back();
155 }
156
Alexey Bataev28c75412015-12-15 08:19:24 +0000157 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
158 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
159 }
160 const std::pair<OMPCriticalDirective *, llvm::APSInt>
161 getCriticalWithHint(const DeclarationNameInfo &Name) const {
162 auto I = Criticals.find(Name.getAsString());
163 if (I != Criticals.end())
164 return I->second;
165 return std::make_pair(nullptr, llvm::APSInt());
166 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000167 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000168 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000169 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000170 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000171
Alexey Bataev9c821032015-04-30 04:23:23 +0000172 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000173 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000174 /// \brief Check if the specified variable is a loop control variable for
175 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000176 /// \return The index of the loop control variable in the list of associated
177 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000178 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000179 /// \brief Check if the specified variable is a loop control variable for
180 /// parent region.
181 /// \return The index of the loop control variable in the list of associated
182 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000183 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000184 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
185 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000186 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000187
Alexey Bataev758e55e2013-09-06 18:03:48 +0000188 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000189 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
190 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191
Alexey Bataev758e55e2013-09-06 18:03:48 +0000192 /// \brief Returns data sharing attributes from top of the stack for the
193 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000194 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000195 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000196 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000197 /// \brief Checks if the specified variables has data-sharing attributes which
198 /// match specified \a CPred predicate in any directive which matches \a DPred
199 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000200 DSAVarData hasDSA(ValueDecl *D,
201 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
202 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
203 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000204 /// \brief Checks if the specified variables has data-sharing attributes which
205 /// match specified \a CPred predicate in any innermost directive which
206 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000207 DSAVarData
208 hasInnermostDSA(ValueDecl *D,
209 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
210 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
211 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000212 /// \brief Checks if the specified variables has explicit data-sharing
213 /// attributes which match specified \a CPred predicate at the specified
214 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000215 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000216 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000217 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000218
219 /// \brief Returns true if the directive at level \Level matches in the
220 /// specified \a DPred predicate.
221 bool hasExplicitDirective(
222 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
223 unsigned Level);
224
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000225 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000226 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
227 const DeclarationNameInfo &,
228 SourceLocation)> &DPred,
229 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000230
Alexey Bataev758e55e2013-09-06 18:03:48 +0000231 /// \brief Returns currently analyzed directive.
232 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000233 return Stack.empty() ? OMPD_unknown : Stack.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000234 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000235 /// \brief Returns parent directive.
236 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000237 if (Stack.size() > 1)
Alexey Bataev549210e2014-06-24 04:39:47 +0000238 return Stack[Stack.size() - 2].Directive;
239 return OMPD_unknown;
240 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000241
242 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000243 void setDefaultDSANone(SourceLocation Loc) {
244 Stack.back().DefaultAttr = DSA_none;
245 Stack.back().DefaultAttrLoc = Loc;
246 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000247 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000248 void setDefaultDSAShared(SourceLocation Loc) {
249 Stack.back().DefaultAttr = DSA_shared;
250 Stack.back().DefaultAttrLoc = Loc;
251 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000252
253 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000254 return Stack.empty() ? DSA_unspecified : Stack.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000255 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000256 SourceLocation getDefaultDSALocation() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000257 return Stack.empty() ? SourceLocation() : Stack.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000258 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000259
Alexey Bataevf29276e2014-06-18 04:14:57 +0000260 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000261 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000262 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000263 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000264 }
265
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000266 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000267 void setOrderedRegion(bool IsOrdered, Expr *Param) {
268 Stack.back().OrderedRegion.setInt(IsOrdered);
269 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000270 }
271 /// \brief Returns true, if parent region is ordered (has associated
272 /// 'ordered' clause), false - otherwise.
273 bool isParentOrderedRegion() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000274 if (Stack.size() > 1)
Alexey Bataev346265e2015-09-25 10:37:12 +0000275 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000276 return false;
277 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000278 /// \brief Returns optional parameter for the ordered region.
279 Expr *getParentOrderedRegionParam() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000280 if (Stack.size() > 1)
Alexey Bataev346265e2015-09-25 10:37:12 +0000281 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
282 return nullptr;
283 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000284 /// \brief Marks current region as nowait (it has a 'nowait' clause).
285 void setNowaitRegion(bool IsNowait = true) {
286 Stack.back().NowaitRegion = IsNowait;
287 }
288 /// \brief Returns true, if parent region is nowait (has associated
289 /// 'nowait' clause), false - otherwise.
290 bool isParentNowaitRegion() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000291 if (Stack.size() > 1)
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000292 return Stack[Stack.size() - 2].NowaitRegion;
293 return false;
294 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000295 /// \brief Marks parent region as cancel region.
296 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000297 if (Stack.size() > 1)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000298 Stack[Stack.size() - 2].CancelRegion =
299 Stack[Stack.size() - 2].CancelRegion || Cancel;
300 }
301 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000302 bool isCancelRegion() const {
303 return Stack.empty() ? false : Stack.back().CancelRegion;
304 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000305
Alexey Bataev9c821032015-04-30 04:23:23 +0000306 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000307 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000308 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000309 unsigned getAssociatedLoops() const {
310 return Stack.empty() ? 0 : Stack.back().AssociatedLoops;
311 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000312
Alexey Bataev13314bf2014-10-09 04:18:56 +0000313 /// \brief Marks current target region as one with closely nested teams
314 /// region.
315 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000316 if (Stack.size() > 1)
Alexey Bataev13314bf2014-10-09 04:18:56 +0000317 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
318 }
319 /// \brief Returns true, if current region has closely nested teams region.
320 bool hasInnerTeamsRegion() const {
321 return getInnerTeamsRegionLoc().isValid();
322 }
323 /// \brief Returns location of the nested teams region (if any).
324 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000325 return Stack.empty() ? SourceLocation() : Stack.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000326 }
327
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000328 Scope *getCurScope() const {
329 return Stack.empty() ? nullptr : Stack.back().CurScope;
330 }
331 Scope *getCurScope() {
332 return Stack.empty() ? nullptr : Stack.back().CurScope;
333 }
334 SourceLocation getConstructLoc() {
335 return Stack.empty() ? SourceLocation() : Stack.back().ConstructLoc;
336 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000337
Samuel Antao4c8035b2016-12-12 18:00:20 +0000338 /// Do the check specified in \a Check to all component lists and return true
339 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000340 bool checkMappableExprComponentListsForDecl(
341 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000342 const llvm::function_ref<
343 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
344 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000345 auto SI = Stack.rbegin();
346 auto SE = Stack.rend();
347
348 if (SI == SE)
349 return false;
350
351 if (CurrentRegionOnly) {
352 SE = std::next(SI);
353 } else {
354 ++SI;
355 }
356
357 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000358 auto MI = SI->MappedExprComponents.find(VD);
359 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000360 for (auto &L : MI->second.Components)
361 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000362 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000363 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000364 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000365 }
366
Samuel Antao4c8035b2016-12-12 18:00:20 +0000367 /// Create a new mappable expression component list associated with a given
368 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000369 void addMappableExpressionComponents(
370 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000371 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
372 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000373 assert(!Stack.empty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000374 "Not expecting to retrieve components from a empty stack!");
375 auto &MEC = Stack.back().MappedExprComponents[VD];
376 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000377 MEC.Components.resize(MEC.Components.size() + 1);
378 MEC.Components.back().append(Components.begin(), Components.end());
379 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000380 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000381
382 unsigned getNestingLevel() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000383 assert(!Stack.empty());
384 return Stack.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000385 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000386 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000387 assert(Stack.size() > 1);
Alexey Bataev8b427062016-05-25 12:36:08 +0000388 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
389 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
390 }
391 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
392 getDoacrossDependClauses() const {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000393 assert(!Stack.empty());
394 if (isOpenMPWorksharingDirective(Stack.back().Directive)) {
395 auto &Ref = Stack.back().DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000396 return llvm::make_range(Ref.begin(), Ref.end());
397 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000398 return llvm::make_range(Stack.back().DoacrossDepends.end(),
399 Stack.back().DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000400 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000401};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000402bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000403 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
404 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000405}
Alexey Bataeved09d242014-05-28 05:53:51 +0000406} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000407
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000408static ValueDecl *getCanonicalDecl(ValueDecl *D) {
409 auto *VD = dyn_cast<VarDecl>(D);
410 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000411 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000412 VD = VD->getCanonicalDecl();
413 D = VD;
414 } else {
415 assert(FD);
416 FD = FD->getCanonicalDecl();
417 D = FD;
418 }
419 return D;
420}
421
David Majnemer9d168222016-08-05 17:44:54 +0000422DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000423 ValueDecl *D) {
424 D = getCanonicalDecl(D);
425 auto *VD = dyn_cast<VarDecl>(D);
426 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000427 DSAVarData DVar;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000428 if (Iter == Stack.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000429 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
430 // in a region but not in construct]
431 // File-scope or namespace-scope variables referenced in called routines
432 // in the region are shared unless they appear in a threadprivate
433 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000434 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000435 DVar.CKind = OMPC_shared;
436
437 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
438 // in a region but not in construct]
439 // Variables with static storage duration that are declared in called
440 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000441 if (VD && VD->hasGlobalStorage())
442 DVar.CKind = OMPC_shared;
443
444 // Non-static data members are shared by default.
445 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000446 DVar.CKind = OMPC_shared;
447
Alexey Bataev758e55e2013-09-06 18:03:48 +0000448 return DVar;
449 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000450
Alexey Bataev758e55e2013-09-06 18:03:48 +0000451 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000452 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
453 // in a Construct, C/C++, predetermined, p.1]
454 // Variables with automatic storage duration that are declared in a scope
455 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000456 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
457 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000458 DVar.CKind = OMPC_private;
459 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000460 }
461
Alexey Bataev758e55e2013-09-06 18:03:48 +0000462 // Explicitly specified attributes and local variables with predetermined
463 // attributes.
464 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000465 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000466 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000467 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000468 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000469 return DVar;
470 }
471
472 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
473 // in a Construct, C/C++, implicitly determined, p.1]
474 // In a parallel or task construct, the data-sharing attributes of these
475 // variables are determined by the default clause, if present.
476 switch (Iter->DefaultAttr) {
477 case DSA_shared:
478 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000480 return DVar;
481 case DSA_none:
482 return DVar;
483 case DSA_unspecified:
484 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
485 // in a Construct, implicitly determined, p.2]
486 // In a parallel construct, if no default clause is present, these
487 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000488 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000489 if (isOpenMPParallelDirective(DVar.DKind) ||
490 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000491 DVar.CKind = OMPC_shared;
492 return DVar;
493 }
494
495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
496 // in a Construct, implicitly determined, p.4]
497 // In a task construct, if no default clause is present, a variable that in
498 // the enclosing context is determined to be shared by all implicit tasks
499 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000500 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000501 DSAVarData DVarTemp;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000502 auto I = Iter, E = Stack.rend();
503 do {
504 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000505 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000506 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000507 // In a task construct, if no default clause is present, a variable
508 // whose data-sharing attribute is not determined by the rules above is
509 // firstprivate.
510 DVarTemp = getDSA(I, D);
511 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000512 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000513 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000514 return DVar;
515 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000516 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000518 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 return DVar;
520 }
521 }
522 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
523 // in a Construct, implicitly determined, p.3]
524 // For constructs other than task, if no default clause is present, these
525 // variables inherit their data-sharing attributes from the enclosing
526 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000527 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000528}
529
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000530Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000531 assert(!Stack.empty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000532 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000533 auto It = Stack.back().AlignedMap.find(D);
534 if (It == Stack.back().AlignedMap.end()) {
535 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
536 Stack.back().AlignedMap[D] = NewDE;
537 return nullptr;
538 } else {
539 assert(It->second && "Unexpected nullptr expr in the aligned map");
540 return It->second;
541 }
542 return nullptr;
543}
544
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000545void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000546 assert(!Stack.empty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000547 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000548 Stack.back().LCVMap.insert(
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000549 {D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000550}
551
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000552DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000553 assert(!Stack.empty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000554 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000555 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000559DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000561 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000562 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
563 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565}
566
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000567ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000568 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000569 if (Stack[Stack.size() - 2].LCVMap.size() < I)
570 return nullptr;
571 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000572 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000573 return Pair.first;
574 }
575 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000576}
577
Alexey Bataev90c228f2016-02-08 09:29:13 +0000578void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
579 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000581 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000582 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000583 Data.Attributes = A;
584 Data.RefExpr.setPointer(E);
585 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000586 } else {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000587 assert(!Stack.empty() && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000588 auto &Data = Stack.back().SharingMap[D];
589 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
590 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
591 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
592 (isLoopControlVariable(D).first && A == OMPC_private));
593 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
594 Data.RefExpr.setInt(/*IntVal=*/true);
595 return;
596 }
597 const bool IsLastprivate =
598 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
599 Data.Attributes = A;
600 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
601 Data.PrivateCopy = PrivateCopy;
602 if (PrivateCopy) {
603 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
604 Data.Attributes = A;
605 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
606 Data.PrivateCopy = nullptr;
607 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000608 }
609}
610
Alexey Bataeved09d242014-05-28 05:53:51 +0000611bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000612 D = D->getCanonicalDecl();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000613 if (Stack.size() > 1) {
614 reverse_iterator I = Iter, E = Stack.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000615 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000616 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000618 if (I == E)
619 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000620 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000621 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000622 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000623 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000624 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000625 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000626 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000627}
628
Alexey Bataev39f915b82015-05-08 10:41:21 +0000629/// \brief Build a variable declaration for OpenMP loop iteration variable.
630static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000632 DeclContext *DC = SemaRef.CurContext;
633 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
634 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
635 VarDecl *Decl =
636 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000637 if (Attrs) {
638 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
639 I != E; ++I)
640 Decl->addAttr(*I);
641 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000642 Decl->setImplicit();
643 return Decl;
644}
645
646static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
647 SourceLocation Loc,
648 bool RefersToCapture = false) {
649 D->setReferenced();
650 D->markUsed(S.Context);
651 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
652 SourceLocation(), D, RefersToCapture, Loc, Ty,
653 VK_LValue);
654}
655
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000656DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
657 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000658 DSAVarData DVar;
659
660 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
661 // in a Construct, C/C++, predetermined, p.1]
662 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000663 auto *VD = dyn_cast<VarDecl>(D);
664 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
665 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000666 SemaRef.getLangOpts().OpenMPUseTLS &&
667 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000668 (VD && VD->getStorageClass() == SC_Register &&
669 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
670 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000671 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000672 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000673 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000674 auto TI = Threadprivates.find(D);
675 if (TI != Threadprivates.end()) {
676 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677 DVar.CKind = OMPC_threadprivate;
678 return DVar;
679 }
680
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000681 if (Stack.empty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000682 // Not in OpenMP execution region and top scope was already checked.
683 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000684
Alexey Bataev758e55e2013-09-06 18:03:48 +0000685 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000686 // in a Construct, C/C++, predetermined, p.4]
687 // Static data members are shared.
688 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
689 // in a Construct, C/C++, predetermined, p.7]
690 // Variables with static storage duration that are declared in a scope
691 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000692 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000693 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000694 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000695 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000696 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000697
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000698 DVar.CKind = OMPC_shared;
699 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000700 }
701
702 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000703 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
704 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000705 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
706 // in a Construct, C/C++, predetermined, p.6]
707 // Variables with const qualified type having no mutable member are
708 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000709 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000710 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000711 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
712 if (auto *CTD = CTSD->getSpecializedTemplate())
713 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000714 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000715 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
716 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000717 // Variables with const-qualified type having no mutable member may be
718 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000719 DSAVarData DVarTemp = hasDSA(
720 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
721 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000722 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
723 return DVar;
724
Alexey Bataev758e55e2013-09-06 18:03:48 +0000725 DVar.CKind = OMPC_shared;
726 return DVar;
727 }
728
Alexey Bataev758e55e2013-09-06 18:03:48 +0000729 // Explicitly specified attributes and local variables with predetermined
730 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000731 auto StartI = std::next(Stack.rbegin());
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000732 auto EndI = Stack.rend();
733 if (FromParent && StartI != EndI)
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000734 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000735 auto I = std::prev(StartI);
736 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000737 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000738 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000739 DVar.CKind = I->SharingMap[D].Attributes;
740 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000741 }
742
743 return DVar;
744}
745
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000746DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
747 bool FromParent) {
748 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000749 auto StartI = Stack.rbegin();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000750 auto EndI = Stack.rend();
751 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000752 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000753 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000754}
755
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000756DSAStackTy::DSAVarData
757DSAStackTy::hasDSA(ValueDecl *D,
758 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
759 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
760 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000761 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000762 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000763 auto EndI = Stack.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000764 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000765 StartI = std::next(StartI);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000766 if (StartI == EndI)
767 return {};
768 auto I = std::prev(StartI);
769 do {
770 ++I;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000771 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000772 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000773 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000774 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000775 return DVar;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000776 } while (I != EndI);
777 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000778}
779
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000780DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
781 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
782 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
783 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000784 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000785 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000786 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000787 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000788 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000789 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000790 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000791 DSAVarData DVar = getDSA(StartI, D);
792 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000793}
794
Alexey Bataevaac108a2015-06-23 04:51:00 +0000795bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000796 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000797 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000798 if (CPred(ClauseKindMode))
799 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000800 D = getCanonicalDecl(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000801 auto StartI = Stack.begin();
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000802 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000803 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000804 return false;
805 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000806 return (StartI->SharingMap.count(D) > 0) &&
807 StartI->SharingMap[D].RefExpr.getPointer() &&
808 CPred(StartI->SharingMap[D].Attributes) &&
809 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000810}
811
Samuel Antao4be30e92015-10-02 17:14:03 +0000812bool DSAStackTy::hasExplicitDirective(
813 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
814 unsigned Level) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000815 auto StartI = Stack.begin();
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000817 if (std::distance(StartI, EndI) <= (int)Level)
818 return false;
819 std::advance(StartI, Level);
820 return DPred(StartI->Directive);
821}
822
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000823bool DSAStackTy::hasDirective(
824 const llvm::function_ref<bool(OpenMPDirectiveKind,
825 const DeclarationNameInfo &, SourceLocation)>
826 &DPred,
827 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000828 // We look only in the enclosing region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000829 if (Stack.size() < 1)
Samuel Antaof0d79752016-05-27 15:21:27 +0000830 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000831 auto StartI = std::next(Stack.rbegin());
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000832 auto EndI = Stack.rend();
833 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000834 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000835 for (auto I = StartI, EE = EndI; I != EE; ++I) {
836 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
837 return true;
838 }
839 return false;
840}
841
Alexey Bataev758e55e2013-09-06 18:03:48 +0000842void Sema::InitDataSharingAttributesStack() {
843 VarDataSharingAttributesStack = new DSAStackTy(*this);
844}
845
846#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
847
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000848bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000849 assert(LangOpts.OpenMP && "OpenMP is not allowed");
850
851 auto &Ctx = getASTContext();
852 bool IsByRef = true;
853
854 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000855 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000856
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000857 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000858 // This table summarizes how a given variable should be passed to the device
859 // given its type and the clauses where it appears. This table is based on
860 // the description in OpenMP 4.5 [2.10.4, target Construct] and
861 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
862 //
863 // =========================================================================
864 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
865 // | |(tofrom:scalar)| | pvt | | | |
866 // =========================================================================
867 // | scl | | | | - | | bycopy|
868 // | scl | | - | x | - | - | bycopy|
869 // | scl | | x | - | - | - | null |
870 // | scl | x | | | - | | byref |
871 // | scl | x | - | x | - | - | bycopy|
872 // | scl | x | x | - | - | - | null |
873 // | scl | | - | - | - | x | byref |
874 // | scl | x | - | - | - | x | byref |
875 //
876 // | agg | n.a. | | | - | | byref |
877 // | agg | n.a. | - | x | - | - | byref |
878 // | agg | n.a. | x | - | - | - | null |
879 // | agg | n.a. | - | - | - | x | byref |
880 // | agg | n.a. | - | - | - | x[] | byref |
881 //
882 // | ptr | n.a. | | | - | | bycopy|
883 // | ptr | n.a. | - | x | - | - | bycopy|
884 // | ptr | n.a. | x | - | - | - | null |
885 // | ptr | n.a. | - | - | - | x | byref |
886 // | ptr | n.a. | - | - | - | x[] | bycopy|
887 // | ptr | n.a. | - | - | x | | bycopy|
888 // | ptr | n.a. | - | - | x | x | bycopy|
889 // | ptr | n.a. | - | - | x | x[] | bycopy|
890 // =========================================================================
891 // Legend:
892 // scl - scalar
893 // ptr - pointer
894 // agg - aggregate
895 // x - applies
896 // - - invalid in this combination
897 // [] - mapped with an array section
898 // byref - should be mapped by reference
899 // byval - should be mapped by value
900 // null - initialize a local variable to null on the device
901 //
902 // Observations:
903 // - All scalar declarations that show up in a map clause have to be passed
904 // by reference, because they may have been mapped in the enclosing data
905 // environment.
906 // - If the scalar value does not fit the size of uintptr, it has to be
907 // passed by reference, regardless the result in the table above.
908 // - For pointers mapped by value that have either an implicit map or an
909 // array section, the runtime library may pass the NULL value to the
910 // device instead of the value passed to it by the compiler.
911
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000912 if (Ty->isReferenceType())
913 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000914
915 // Locate map clauses and see if the variable being captured is referred to
916 // in any of those clauses. Here we only care about variables, not fields,
917 // because fields are part of aggregates.
918 bool IsVariableUsedInMapClause = false;
919 bool IsVariableAssociatedWithSection = false;
920
921 DSAStack->checkMappableExprComponentListsForDecl(
922 D, /*CurrentRegionOnly=*/true,
923 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000924 MapExprComponents,
925 OpenMPClauseKind WhereFoundClauseKind) {
926 // Only the map clause information influences how a variable is
927 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000928 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000929 if (WhereFoundClauseKind != OMPC_map)
930 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000931
932 auto EI = MapExprComponents.rbegin();
933 auto EE = MapExprComponents.rend();
934
935 assert(EI != EE && "Invalid map expression!");
936
937 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
938 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
939
940 ++EI;
941 if (EI == EE)
942 return false;
943
944 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
945 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
946 isa<MemberExpr>(EI->getAssociatedExpression())) {
947 IsVariableAssociatedWithSection = true;
948 // There is nothing more we need to know about this variable.
949 return true;
950 }
951
952 // Keep looking for more map info.
953 return false;
954 });
955
956 if (IsVariableUsedInMapClause) {
957 // If variable is identified in a map clause it is always captured by
958 // reference except if it is a pointer that is dereferenced somehow.
959 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
960 } else {
961 // By default, all the data that has a scalar type is mapped by copy.
962 IsByRef = !Ty->isScalarType();
963 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000964 }
965
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000966 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
967 IsByRef = !DSAStack->hasExplicitDSA(
968 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
969 Level, /*NotLastprivate=*/true);
970 }
971
Samuel Antao86ace552016-04-27 22:40:57 +0000972 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000973 // and alignment, because the runtime library only deals with uintptr types.
974 // If it does not fit the uintptr size, we need to pass the data by reference
975 // instead.
976 if (!IsByRef &&
977 (Ctx.getTypeSizeInChars(Ty) >
978 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000979 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000980 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000981 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000982
983 return IsByRef;
984}
985
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000986unsigned Sema::getOpenMPNestingLevel() const {
987 assert(getLangOpts().OpenMP);
988 return DSAStack->getNestingLevel();
989}
990
Alexey Bataev90c228f2016-02-08 09:29:13 +0000991VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000992 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000993 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000994
995 // If we are attempting to capture a global variable in a directive with
996 // 'target' we return true so that this global is also mapped to the device.
997 //
998 // FIXME: If the declaration is enclosed in a 'declare target' directive,
999 // then it should not be captured. Therefore, an extra check has to be
1000 // inserted here once support for 'declare target' is added.
1001 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001002 auto *VD = dyn_cast<VarDecl>(D);
1003 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001004 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001005 !DSAStack->isClauseParsingMode())
1006 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001007 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001008 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1009 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001010 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001011 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001012 false))
1013 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001014 }
1015
Alexey Bataev48977c32015-08-04 08:10:48 +00001016 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1017 (!DSAStack->isClauseParsingMode() ||
1018 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001019 auto &&Info = DSAStack->isLoopControlVariable(D);
1020 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001021 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001022 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001023 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001024 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001025 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001026 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001027 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001028 DVarPrivate = DSAStack->hasDSA(
1029 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1030 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001031 if (DVarPrivate.CKind != OMPC_unknown)
1032 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001033 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001034 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001040 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001041}
1042
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001043bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001044 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1045 // Return true if the current level is no longer enclosed in a target region.
1046
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001047 auto *VD = dyn_cast<VarDecl>(D);
1048 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001049 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1050 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001051}
1052
Alexey Bataeved09d242014-05-28 05:53:51 +00001053void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054
1055void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1056 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001057 Scope *CurScope, SourceLocation Loc) {
1058 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001059 PushExpressionEvaluationContext(
1060 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001061}
1062
Alexey Bataevaac108a2015-06-23 04:51:00 +00001063void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1064 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001065}
1066
Alexey Bataevaac108a2015-06-23 04:51:00 +00001067void Sema::EndOpenMPClause() {
1068 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001069}
1070
Alexey Bataev758e55e2013-09-06 18:03:48 +00001071void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001072 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1073 // A variable of class type (or array thereof) that appears in a lastprivate
1074 // clause requires an accessible, unambiguous default constructor for the
1075 // class type, unless the list item is also specified in a firstprivate
1076 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001077 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 for (auto *C : D->clauses()) {
1079 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1080 SmallVector<Expr *, 8> PrivateCopies;
1081 for (auto *DE : Clause->varlists()) {
1082 if (DE->isValueDependent() || DE->isTypeDependent()) {
1083 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001084 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001085 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001086 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001087 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1088 QualType Type = VD->getType().getNonReferenceType();
1089 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001090 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001091 // Generate helper private variable and initialize it with the
1092 // default value. The address of the original variable is replaced
1093 // by the address of the new private variable in CodeGen. This new
1094 // variable is not added to IdResolver, so the code in the OpenMP
1095 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001096 auto *VDPrivate = buildVarDecl(
1097 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001098 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001099 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001100 if (VDPrivate->isInvalidDecl())
1101 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001102 PrivateCopies.push_back(buildDeclRefExpr(
1103 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001104 } else {
1105 // The variable is also a firstprivate, so initialization sequence
1106 // for private copy is generated already.
1107 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001108 }
1109 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001110 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001111 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001112 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001113 }
1114 }
1115 }
1116
Alexey Bataev758e55e2013-09-06 18:03:48 +00001117 DSAStack->pop();
1118 DiscardCleanupsInEvaluationContext();
1119 PopExpressionEvaluationContext();
1120}
1121
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001122static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1123 Expr *NumIterations, Sema &SemaRef,
1124 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001125
Alexey Bataeva769e072013-03-22 06:34:35 +00001126namespace {
1127
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128class VarDeclFilterCCC : public CorrectionCandidateCallback {
1129private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001130 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001131
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001132public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001133 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001134 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001135 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001136 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001137 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001138 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1139 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001140 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001141 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001142 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001143};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001144
1145class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1146private:
1147 Sema &SemaRef;
1148
1149public:
1150 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1151 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1152 NamedDecl *ND = Candidate.getCorrectionDecl();
1153 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1154 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1155 SemaRef.getCurScope());
1156 }
1157 return false;
1158 }
1159};
1160
Alexey Bataeved09d242014-05-28 05:53:51 +00001161} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001162
1163ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1164 CXXScopeSpec &ScopeSpec,
1165 const DeclarationNameInfo &Id) {
1166 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1167 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1168
1169 if (Lookup.isAmbiguous())
1170 return ExprError();
1171
1172 VarDecl *VD;
1173 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001174 if (TypoCorrection Corrected = CorrectTypo(
1175 Id, LookupOrdinaryName, CurScope, nullptr,
1176 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001178 PDiag(Lookup.empty()
1179 ? diag::err_undeclared_var_use_suggest
1180 : diag::err_omp_expected_var_arg_suggest)
1181 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001182 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001183 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001184 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1185 : diag::err_omp_expected_var_arg)
1186 << Id.getName();
1187 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001188 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001189 } else {
1190 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001191 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001192 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1193 return ExprError();
1194 }
1195 }
1196 Lookup.suppressDiagnostics();
1197
1198 // OpenMP [2.9.2, Syntax, C/C++]
1199 // Variables must be file-scope, namespace-scope, or static block-scope.
1200 if (!VD->hasGlobalStorage()) {
1201 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001202 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1203 bool IsDecl =
1204 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001205 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001206 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1207 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001208 return ExprError();
1209 }
1210
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001211 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1212 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001213 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1214 // A threadprivate directive for file-scope variables must appear outside
1215 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001216 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1217 !getCurLexicalContext()->isTranslationUnit()) {
1218 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001219 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1220 bool IsDecl =
1221 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1222 Diag(VD->getLocation(),
1223 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1224 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001225 return ExprError();
1226 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001227 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1228 // A threadprivate directive for static class member variables must appear
1229 // in the class definition, in the same scope in which the member
1230 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001231 if (CanonicalVD->isStaticDataMember() &&
1232 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1233 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001234 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1235 bool IsDecl =
1236 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1237 Diag(VD->getLocation(),
1238 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1239 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001240 return ExprError();
1241 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001242 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1243 // A threadprivate directive for namespace-scope variables must appear
1244 // outside any definition or declaration other than the namespace
1245 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001246 if (CanonicalVD->getDeclContext()->isNamespace() &&
1247 (!getCurLexicalContext()->isFileContext() ||
1248 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1249 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001250 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1251 bool IsDecl =
1252 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1253 Diag(VD->getLocation(),
1254 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1255 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001256 return ExprError();
1257 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001258 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1259 // A threadprivate directive for static block-scope variables must appear
1260 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001261 if (CanonicalVD->isStaticLocal() && CurScope &&
1262 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001264 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1265 bool IsDecl =
1266 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1267 Diag(VD->getLocation(),
1268 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1269 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 return ExprError();
1271 }
1272
1273 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1274 // A threadprivate directive must lexically precede all references to any
1275 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001276 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001277 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001278 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001279 return ExprError();
1280 }
1281
1282 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001283 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1284 SourceLocation(), VD,
1285 /*RefersToEnclosingVariableOrCapture=*/false,
1286 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001287}
1288
Alexey Bataeved09d242014-05-28 05:53:51 +00001289Sema::DeclGroupPtrTy
1290Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1291 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001292 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001293 CurContext->addDecl(D);
1294 return DeclGroupPtrTy::make(DeclGroupRef(D));
1295 }
David Blaikie0403cb12016-01-15 23:43:25 +00001296 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001297}
1298
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299namespace {
1300class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1301 Sema &SemaRef;
1302
1303public:
1304 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001305 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001306 if (VD->hasLocalStorage()) {
1307 SemaRef.Diag(E->getLocStart(),
1308 diag::err_omp_local_var_in_threadprivate_init)
1309 << E->getSourceRange();
1310 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1311 << VD << VD->getSourceRange();
1312 return true;
1313 }
1314 }
1315 return false;
1316 }
1317 bool VisitStmt(const Stmt *S) {
1318 for (auto Child : S->children()) {
1319 if (Child && Visit(Child))
1320 return true;
1321 }
1322 return false;
1323 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001324 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001325};
1326} // namespace
1327
Alexey Bataeved09d242014-05-28 05:53:51 +00001328OMPThreadPrivateDecl *
1329Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001330 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001331 for (auto &RefExpr : VarList) {
1332 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001333 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1334 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001335
Alexey Bataev376b4a42016-02-09 09:41:09 +00001336 // Mark variable as used.
1337 VD->setReferenced();
1338 VD->markUsed(Context);
1339
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001340 QualType QType = VD->getType();
1341 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1342 // It will be analyzed later.
1343 Vars.push_back(DE);
1344 continue;
1345 }
1346
Alexey Bataeva769e072013-03-22 06:34:35 +00001347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have an incomplete type.
1349 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001350 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001351 continue;
1352 }
1353
1354 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1355 // A threadprivate variable must not have a reference type.
1356 if (VD->getType()->isReferenceType()) {
1357 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001358 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1359 bool IsDecl =
1360 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1361 Diag(VD->getLocation(),
1362 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1363 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001364 continue;
1365 }
1366
Samuel Antaof8b50122015-07-13 22:54:53 +00001367 // Check if this is a TLS variable. If TLS is not being supported, produce
1368 // the corresponding diagnostic.
1369 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1370 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1371 getLangOpts().OpenMPUseTLS &&
1372 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001373 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1374 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001375 Diag(ILoc, diag::err_omp_var_thread_local)
1376 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001377 bool IsDecl =
1378 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1379 Diag(VD->getLocation(),
1380 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1381 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001382 continue;
1383 }
1384
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001385 // Check if initial value of threadprivate variable reference variable with
1386 // local storage (it is not supported by runtime).
1387 if (auto Init = VD->getAnyInitializer()) {
1388 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001389 if (Checker.Visit(Init))
1390 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001391 }
1392
Alexey Bataeved09d242014-05-28 05:53:51 +00001393 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001394 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001395 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1396 Context, SourceRange(Loc, Loc)));
1397 if (auto *ML = Context.getASTMutationListener())
1398 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001399 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001400 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001401 if (!Vars.empty()) {
1402 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1403 Vars);
1404 D->setAccess(AS_public);
1405 }
1406 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001407}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001408
Alexey Bataev7ff55242014-06-19 09:13:45 +00001409static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001410 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001411 bool IsLoopIterVar = false) {
1412 if (DVar.RefExpr) {
1413 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1414 << getOpenMPClauseName(DVar.CKind);
1415 return;
1416 }
1417 enum {
1418 PDSA_StaticMemberShared,
1419 PDSA_StaticLocalVarShared,
1420 PDSA_LoopIterVarPrivate,
1421 PDSA_LoopIterVarLinear,
1422 PDSA_LoopIterVarLastprivate,
1423 PDSA_ConstVarShared,
1424 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001425 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001426 PDSA_LocalVarPrivate,
1427 PDSA_Implicit
1428 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001429 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001430 auto ReportLoc = D->getLocation();
1431 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001432 if (IsLoopIterVar) {
1433 if (DVar.CKind == OMPC_private)
1434 Reason = PDSA_LoopIterVarPrivate;
1435 else if (DVar.CKind == OMPC_lastprivate)
1436 Reason = PDSA_LoopIterVarLastprivate;
1437 else
1438 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001439 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1440 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001441 Reason = PDSA_TaskVarFirstprivate;
1442 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001443 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001444 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001445 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001446 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001447 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001448 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001449 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001450 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001451 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001452 ReportHint = true;
1453 Reason = PDSA_LocalVarPrivate;
1454 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001455 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001456 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001457 << Reason << ReportHint
1458 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1459 } else if (DVar.ImplicitDSALoc.isValid()) {
1460 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1461 << getOpenMPClauseName(DVar.CKind);
1462 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001463}
1464
Alexey Bataev758e55e2013-09-06 18:03:48 +00001465namespace {
1466class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1467 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001468 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001469 bool ErrorFound;
1470 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001471 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001472 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001473
Alexey Bataev758e55e2013-09-06 18:03:48 +00001474public:
1475 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001476 if (E->isTypeDependent() || E->isValueDependent() ||
1477 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1478 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001479 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001480 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001481 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1482 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001483
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001484 auto DVar = Stack->getTopDSA(VD, false);
1485 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001486 if (DVar.RefExpr)
1487 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001488
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 auto ELoc = E->getExprLoc();
1490 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001491 // The default(none) clause requires that each variable that is referenced
1492 // in the construct, and does not have a predetermined data-sharing
1493 // attribute, must have its data-sharing attribute explicitly determined
1494 // by being listed in a data-sharing attribute clause.
1495 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001496 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001497 VarsWithInheritedDSA.count(VD) == 0) {
1498 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001499 return;
1500 }
1501
1502 // OpenMP [2.9.3.6, Restrictions, p.2]
1503 // A list item that appears in a reduction clause of the innermost
1504 // enclosing worksharing or parallel construct may not be accessed in an
1505 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001506 DVar = Stack->hasInnermostDSA(
1507 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1508 [](OpenMPDirectiveKind K) -> bool {
1509 return isOpenMPParallelDirective(K) ||
1510 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1511 },
1512 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001513 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001514 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001515 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1516 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001517 return;
1518 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001519
1520 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001521 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001522 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1523 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001524 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001525 }
1526 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001527 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001528 if (E->isTypeDependent() || E->isValueDependent() ||
1529 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1530 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001531 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1532 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1533 auto DVar = Stack->getTopDSA(FD, false);
1534 // Check if the variable has explicit DSA set and stop analysis if it
1535 // so.
1536 if (DVar.RefExpr)
1537 return;
1538
1539 auto ELoc = E->getExprLoc();
1540 auto DKind = Stack->getCurrentDirective();
1541 // OpenMP [2.9.3.6, Restrictions, p.2]
1542 // A list item that appears in a reduction clause of the innermost
1543 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001544 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001545 DVar = Stack->hasInnermostDSA(
1546 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1547 [](OpenMPDirectiveKind K) -> bool {
1548 return isOpenMPParallelDirective(K) ||
1549 isOpenMPWorksharingDirective(K) ||
1550 isOpenMPTeamsDirective(K);
1551 },
1552 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001553 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001554 ErrorFound = true;
1555 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1556 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1557 return;
1558 }
1559
1560 // Define implicit data-sharing attributes for task.
1561 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001562 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1563 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001564 ImplicitFirstprivate.push_back(E);
1565 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001566 } else
1567 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001568 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001569 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001570 for (auto *C : S->clauses()) {
1571 // Skip analysis of arguments of implicitly defined firstprivate clause
1572 // for task directives.
1573 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1574 for (auto *CC : C->children()) {
1575 if (CC)
1576 Visit(CC);
1577 }
1578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579 }
1580 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001581 for (auto *C : S->children()) {
1582 if (C && !isa<OMPExecutableDirective>(C))
1583 Visit(C);
1584 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001585 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001586
1587 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001588 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001589 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001590 return VarsWithInheritedDSA;
1591 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001592
Alexey Bataev7ff55242014-06-19 09:13:45 +00001593 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1594 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001595};
Alexey Bataeved09d242014-05-28 05:53:51 +00001596} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001597
Alexey Bataevbae9a792014-06-27 10:37:06 +00001598void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001600 case OMPD_parallel:
1601 case OMPD_parallel_for:
1602 case OMPD_parallel_for_simd:
1603 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001604 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001606 QualType KmpInt32PtrTy =
1607 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001608 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001609 std::make_pair(".global_tid.", KmpInt32PtrTy),
1610 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1611 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001612 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001613 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1614 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001615 break;
1616 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001617 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001618 case OMPD_target_parallel: {
1619 Sema::CapturedParamNameType ParamsTarget[] = {
1620 std::make_pair(StringRef(), QualType()) // __context with shared vars
1621 };
1622 // Start a captured region for 'target' with no implicit parameters.
1623 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1624 ParamsTarget);
1625 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1626 QualType KmpInt32PtrTy =
1627 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001628 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001629 std::make_pair(".global_tid.", KmpInt32PtrTy),
1630 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1631 std::make_pair(StringRef(), QualType()) // __context with shared vars
1632 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001633 // Start a captured region for 'teams' or 'parallel'. Both regions have
1634 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001635 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001636 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001637 break;
1638 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001639 case OMPD_simd:
1640 case OMPD_for:
1641 case OMPD_for_simd:
1642 case OMPD_sections:
1643 case OMPD_section:
1644 case OMPD_single:
1645 case OMPD_master:
1646 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001647 case OMPD_taskgroup:
1648 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001649 case OMPD_ordered:
1650 case OMPD_atomic:
1651 case OMPD_target_data:
1652 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001653 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001654 case OMPD_target_parallel_for_simd:
1655 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001656 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001657 std::make_pair(StringRef(), QualType()) // __context with shared vars
1658 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001659 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1660 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001661 break;
1662 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001663 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001664 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001665 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1666 FunctionProtoType::ExtProtoInfo EPI;
1667 EPI.Variadic = true;
1668 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001669 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001670 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001671 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1672 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1673 std::make_pair(".copy_fn.",
1674 Context.getPointerType(CopyFnType).withConst()),
1675 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001676 std::make_pair(StringRef(), QualType()) // __context with shared vars
1677 };
1678 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1679 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001680 // Mark this captured region as inlined, because we don't use outlined
1681 // function directly.
1682 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1683 AlwaysInlineAttr::CreateImplicit(
1684 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001685 break;
1686 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001687 case OMPD_taskloop:
1688 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001689 QualType KmpInt32Ty =
1690 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1691 QualType KmpUInt64Ty =
1692 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1693 QualType KmpInt64Ty =
1694 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1695 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1696 FunctionProtoType::ExtProtoInfo EPI;
1697 EPI.Variadic = true;
1698 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001699 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001700 std::make_pair(".global_tid.", KmpInt32Ty),
1701 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1702 std::make_pair(".privates.",
1703 Context.VoidPtrTy.withConst().withRestrict()),
1704 std::make_pair(
1705 ".copy_fn.",
1706 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1707 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1708 std::make_pair(".lb.", KmpUInt64Ty),
1709 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1710 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001711 std::make_pair(StringRef(), QualType()) // __context with shared vars
1712 };
1713 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1714 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001715 // Mark this captured region as inlined, because we don't use outlined
1716 // function directly.
1717 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1718 AlwaysInlineAttr::CreateImplicit(
1719 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001720 break;
1721 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001722 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001723 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001724 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001725 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001726 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001727 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001728 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001729 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001730 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001731 case OMPD_target_teams_distribute_parallel_for_simd:
1732 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001733 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1734 QualType KmpInt32PtrTy =
1735 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1736 Sema::CapturedParamNameType Params[] = {
1737 std::make_pair(".global_tid.", KmpInt32PtrTy),
1738 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1739 std::make_pair(".previous.lb.", Context.getSizeType()),
1740 std::make_pair(".previous.ub.", Context.getSizeType()),
1741 std::make_pair(StringRef(), QualType()) // __context with shared vars
1742 };
1743 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1744 Params);
1745 break;
1746 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001747 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001748 case OMPD_taskyield:
1749 case OMPD_barrier:
1750 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001751 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001752 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001753 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001754 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001755 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001756 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001757 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001758 case OMPD_declare_target:
1759 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001760 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001761 llvm_unreachable("OpenMP Directive is not allowed");
1762 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001763 llvm_unreachable("Unknown OpenMP directive");
1764 }
1765}
1766
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001767int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1768 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1769 getOpenMPCaptureRegions(CaptureRegions, DKind);
1770 return CaptureRegions.size();
1771}
1772
Alexey Bataev3392d762016-02-16 11:18:12 +00001773static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001774 Expr *CaptureExpr, bool WithInit,
1775 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001776 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001777 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001778 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001779 QualType Ty = Init->getType();
1780 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1781 if (S.getLangOpts().CPlusPlus)
1782 Ty = C.getLValueReferenceType(Ty);
1783 else {
1784 Ty = C.getPointerType(Ty);
1785 ExprResult Res =
1786 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1787 if (!Res.isUsable())
1788 return nullptr;
1789 Init = Res.get();
1790 }
Alexey Bataev61205072016-03-02 04:57:40 +00001791 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001792 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001793 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1794 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001795 if (!WithInit)
1796 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001797 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001798 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001799 return CED;
1800}
1801
Alexey Bataev61205072016-03-02 04:57:40 +00001802static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1803 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001804 OMPCapturedExprDecl *CD;
1805 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1806 CD = cast<OMPCapturedExprDecl>(VD);
1807 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001808 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1809 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001810 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001811 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001812}
1813
Alexey Bataev5a3af132016-03-29 08:58:54 +00001814static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1815 if (!Ref) {
1816 auto *CD =
1817 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1818 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1819 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1820 CaptureExpr->getExprLoc());
1821 }
1822 ExprResult Res = Ref;
1823 if (!S.getLangOpts().CPlusPlus &&
1824 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1825 Ref->getType()->isPointerType())
1826 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1827 if (!Res.isUsable())
1828 return ExprError();
1829 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001830}
1831
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001832namespace {
1833// OpenMP directives parsed in this section are represented as a
1834// CapturedStatement with an associated statement. If a syntax error
1835// is detected during the parsing of the associated statement, the
1836// compiler must abort processing and close the CapturedStatement.
1837//
1838// Combined directives such as 'target parallel' have more than one
1839// nested CapturedStatements. This RAII ensures that we unwind out
1840// of all the nested CapturedStatements when an error is found.
1841class CaptureRegionUnwinderRAII {
1842private:
1843 Sema &S;
1844 bool &ErrorFound;
1845 OpenMPDirectiveKind DKind;
1846
1847public:
1848 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1849 OpenMPDirectiveKind DKind)
1850 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1851 ~CaptureRegionUnwinderRAII() {
1852 if (ErrorFound) {
1853 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1854 while (--ThisCaptureLevel >= 0)
1855 S.ActOnCapturedRegionError();
1856 }
1857 }
1858};
1859} // namespace
1860
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001861StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1862 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001863 bool ErrorFound = false;
1864 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1865 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001866 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001867 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001868 return StmtError();
1869 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001870
1871 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001872 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001873 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001874 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001875 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001876 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001877 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001878 Clause->getClauseKind() == OMPC_copyprivate ||
1879 (getLangOpts().OpenMPUseTLS &&
1880 getASTContext().getTargetInfo().isTLSSupported() &&
1881 Clause->getClauseKind() == OMPC_copyin)) {
1882 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001883 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001884 for (auto *VarRef : Clause->children()) {
1885 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001886 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001887 }
1888 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001889 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001890 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001891 if (auto *C = OMPClauseWithPreInit::get(Clause))
1892 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001893 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1894 if (auto *E = C->getPostUpdateExpr())
1895 MarkDeclarationsReferencedInExpr(E);
1896 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001897 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001898 if (Clause->getClauseKind() == OMPC_schedule)
1899 SC = cast<OMPScheduleClause>(Clause);
1900 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001901 OC = cast<OMPOrderedClause>(Clause);
1902 else if (Clause->getClauseKind() == OMPC_linear)
1903 LCs.push_back(cast<OMPLinearClause>(Clause));
1904 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001905 // OpenMP, 2.7.1 Loop Construct, Restrictions
1906 // The nonmonotonic modifier cannot be specified if an ordered clause is
1907 // specified.
1908 if (SC &&
1909 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1910 SC->getSecondScheduleModifier() ==
1911 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1912 OC) {
1913 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1914 ? SC->getFirstScheduleModifierLoc()
1915 : SC->getSecondScheduleModifierLoc(),
1916 diag::err_omp_schedule_nonmonotonic_ordered)
1917 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1918 ErrorFound = true;
1919 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001920 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1921 for (auto *C : LCs) {
1922 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1923 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1924 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001925 ErrorFound = true;
1926 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001927 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1928 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1929 OC->getNumForLoops()) {
1930 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1931 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1932 ErrorFound = true;
1933 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001934 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001935 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001936 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001937 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001938 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1939 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1940 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1941 // Mark all variables in private list clauses as used in inner region.
1942 // Required for proper codegen of combined directives.
1943 // TODO: add processing for other clauses.
1944 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1945 for (auto *C : PICs) {
1946 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1947 // Find the particular capture region for the clause if the
1948 // directive is a combined one with multiple capture regions.
1949 // If the directive is not a combined one, the capture region
1950 // associated with the clause is OMPD_unknown and is generated
1951 // only once.
1952 if (CaptureRegion == ThisCaptureRegion ||
1953 CaptureRegion == OMPD_unknown) {
1954 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1955 for (auto *D : DS->decls())
1956 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1957 }
1958 }
1959 }
1960 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001961 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001962 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001963 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001964}
1965
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00001966static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
1967 OpenMPDirectiveKind CancelRegion,
1968 SourceLocation StartLoc) {
1969 // CancelRegion is only needed for cancel and cancellation_point.
1970 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
1971 return false;
1972
1973 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
1974 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
1975 return false;
1976
1977 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
1978 << getOpenMPDirectiveName(CancelRegion);
1979 return true;
1980}
1981
1982static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001983 OpenMPDirectiveKind CurrentRegion,
1984 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001985 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001986 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001987 if (Stack->getCurScope()) {
1988 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001989 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001990 bool NestingProhibited = false;
1991 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001992 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001993 enum {
1994 NoRecommend,
1995 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001996 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001997 ShouldBeInTargetRegion,
1998 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001999 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002000 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002001 // OpenMP [2.16, Nesting of Regions]
2002 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002003 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002004 // An ordered construct with the simd clause is the only OpenMP
2005 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002006 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002007 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2008 // message.
2009 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2010 ? diag::err_omp_prohibited_region_simd
2011 : diag::warn_omp_nesting_simd);
2012 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002013 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002014 if (ParentRegion == OMPD_atomic) {
2015 // OpenMP [2.16, Nesting of Regions]
2016 // OpenMP constructs may not be nested inside an atomic region.
2017 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2018 return true;
2019 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002020 if (CurrentRegion == OMPD_section) {
2021 // OpenMP [2.7.2, sections Construct, Restrictions]
2022 // Orphaned section directives are prohibited. That is, the section
2023 // directives must appear within the sections construct and must not be
2024 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002025 if (ParentRegion != OMPD_sections &&
2026 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002027 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2028 << (ParentRegion != OMPD_unknown)
2029 << getOpenMPDirectiveName(ParentRegion);
2030 return true;
2031 }
2032 return false;
2033 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002034 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002035 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002036 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002037 if (ParentRegion == OMPD_unknown &&
2038 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002039 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002040 if (CurrentRegion == OMPD_cancellation_point ||
2041 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002042 // OpenMP [2.16, Nesting of Regions]
2043 // A cancellation point construct for which construct-type-clause is
2044 // taskgroup must be nested inside a task construct. A cancellation
2045 // point construct for which construct-type-clause is not taskgroup must
2046 // be closely nested inside an OpenMP construct that matches the type
2047 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002048 // A cancel construct for which construct-type-clause is taskgroup must be
2049 // nested inside a task construct. A cancel construct for which
2050 // construct-type-clause is not taskgroup must be closely nested inside an
2051 // OpenMP construct that matches the type specified in
2052 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002053 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002054 !((CancelRegion == OMPD_parallel &&
2055 (ParentRegion == OMPD_parallel ||
2056 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002057 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002058 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2059 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002060 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2061 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002062 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2063 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002064 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002065 // OpenMP [2.16, Nesting of Regions]
2066 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002067 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002068 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002069 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002070 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2071 // OpenMP [2.16, Nesting of Regions]
2072 // A critical region may not be nested (closely or otherwise) inside a
2073 // critical region with the same name. Note that this restriction is not
2074 // sufficient to prevent deadlock.
2075 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002076 bool DeadLock = Stack->hasDirective(
2077 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2078 const DeclarationNameInfo &DNI,
2079 SourceLocation Loc) -> bool {
2080 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2081 PreviousCriticalLoc = Loc;
2082 return true;
2083 } else
2084 return false;
2085 },
2086 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002087 if (DeadLock) {
2088 SemaRef.Diag(StartLoc,
2089 diag::err_omp_prohibited_region_critical_same_name)
2090 << CurrentName.getName();
2091 if (PreviousCriticalLoc.isValid())
2092 SemaRef.Diag(PreviousCriticalLoc,
2093 diag::note_omp_previous_critical_region);
2094 return true;
2095 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002096 } else if (CurrentRegion == OMPD_barrier) {
2097 // OpenMP [2.16, Nesting of Regions]
2098 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002099 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002100 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2101 isOpenMPTaskingDirective(ParentRegion) ||
2102 ParentRegion == OMPD_master ||
2103 ParentRegion == OMPD_critical ||
2104 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002105 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002106 !isOpenMPParallelDirective(CurrentRegion) &&
2107 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002108 // OpenMP [2.16, Nesting of Regions]
2109 // A worksharing region may not be closely nested inside a worksharing,
2110 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002111 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2112 isOpenMPTaskingDirective(ParentRegion) ||
2113 ParentRegion == OMPD_master ||
2114 ParentRegion == OMPD_critical ||
2115 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002116 Recommend = ShouldBeInParallelRegion;
2117 } else if (CurrentRegion == OMPD_ordered) {
2118 // OpenMP [2.16, Nesting of Regions]
2119 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002120 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002121 // An ordered region must be closely nested inside a loop region (or
2122 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002123 // OpenMP [2.8.1,simd Construct, Restrictions]
2124 // An ordered construct with the simd clause is the only OpenMP construct
2125 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002126 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002127 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002128 !(isOpenMPSimdDirective(ParentRegion) ||
2129 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002130 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002131 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002132 // OpenMP [2.16, Nesting of Regions]
2133 // If specified, a teams construct must be contained within a target
2134 // construct.
2135 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002136 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002137 Recommend = ShouldBeInTargetRegion;
2138 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2139 }
Kelvin Libf594a52016-12-17 05:48:59 +00002140 if (!NestingProhibited &&
2141 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2142 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2143 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002144 // OpenMP [2.16, Nesting of Regions]
2145 // distribute, parallel, parallel sections, parallel workshare, and the
2146 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2147 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002148 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2149 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002150 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002151 }
David Majnemer9d168222016-08-05 17:44:54 +00002152 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002153 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002154 // OpenMP 4.5 [2.17 Nesting of Regions]
2155 // The region associated with the distribute construct must be strictly
2156 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002157 NestingProhibited =
2158 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002159 Recommend = ShouldBeInTeamsRegion;
2160 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002161 if (!NestingProhibited &&
2162 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2163 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2164 // OpenMP 4.5 [2.17 Nesting of Regions]
2165 // If a target, target update, target data, target enter data, or
2166 // target exit data construct is encountered during execution of a
2167 // target region, the behavior is unspecified.
2168 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002169 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2170 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002171 if (isOpenMPTargetExecutionDirective(K)) {
2172 OffendingRegion = K;
2173 return true;
2174 } else
2175 return false;
2176 },
2177 false /* don't skip top directive */);
2178 CloseNesting = false;
2179 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002180 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002181 if (OrphanSeen) {
2182 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2183 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2184 } else {
2185 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2186 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2187 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2188 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002189 return true;
2190 }
2191 }
2192 return false;
2193}
2194
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002195static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2196 ArrayRef<OMPClause *> Clauses,
2197 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2198 bool ErrorFound = false;
2199 unsigned NamedModifiersNumber = 0;
2200 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2201 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002202 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002203 for (const auto *C : Clauses) {
2204 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2205 // At most one if clause without a directive-name-modifier can appear on
2206 // the directive.
2207 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2208 if (FoundNameModifiers[CurNM]) {
2209 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2210 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2211 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2212 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002213 } else if (CurNM != OMPD_unknown) {
2214 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002215 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002216 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002217 FoundNameModifiers[CurNM] = IC;
2218 if (CurNM == OMPD_unknown)
2219 continue;
2220 // Check if the specified name modifier is allowed for the current
2221 // directive.
2222 // At most one if clause with the particular directive-name-modifier can
2223 // appear on the directive.
2224 bool MatchFound = false;
2225 for (auto NM : AllowedNameModifiers) {
2226 if (CurNM == NM) {
2227 MatchFound = true;
2228 break;
2229 }
2230 }
2231 if (!MatchFound) {
2232 S.Diag(IC->getNameModifierLoc(),
2233 diag::err_omp_wrong_if_directive_name_modifier)
2234 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2235 ErrorFound = true;
2236 }
2237 }
2238 }
2239 // If any if clause on the directive includes a directive-name-modifier then
2240 // all if clauses on the directive must include a directive-name-modifier.
2241 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2242 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2243 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2244 diag::err_omp_no_more_if_clause);
2245 } else {
2246 std::string Values;
2247 std::string Sep(", ");
2248 unsigned AllowedCnt = 0;
2249 unsigned TotalAllowedNum =
2250 AllowedNameModifiers.size() - NamedModifiersNumber;
2251 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2252 ++Cnt) {
2253 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2254 if (!FoundNameModifiers[NM]) {
2255 Values += "'";
2256 Values += getOpenMPDirectiveName(NM);
2257 Values += "'";
2258 if (AllowedCnt + 2 == TotalAllowedNum)
2259 Values += " or ";
2260 else if (AllowedCnt + 1 != TotalAllowedNum)
2261 Values += Sep;
2262 ++AllowedCnt;
2263 }
2264 }
2265 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2266 diag::err_omp_unnamed_if_clause)
2267 << (TotalAllowedNum > 1) << Values;
2268 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002269 for (auto Loc : NameModifierLoc) {
2270 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2271 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002272 ErrorFound = true;
2273 }
2274 return ErrorFound;
2275}
2276
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002277StmtResult Sema::ActOnOpenMPExecutableDirective(
2278 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2279 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2280 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002281 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002282 // First check CancelRegion which is then used in checkNestingOfRegions.
2283 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2284 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002285 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002286 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002287
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002288 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002289 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002290 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002291 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002292 if (AStmt) {
2293 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2294
2295 // Check default data sharing attributes for referenced variables.
2296 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002297 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2298 Stmt *S = AStmt;
2299 while (--ThisCaptureLevel >= 0)
2300 S = cast<CapturedStmt>(S)->getCapturedStmt();
2301 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002302 if (DSAChecker.isErrorFound())
2303 return StmtError();
2304 // Generate list of implicitly defined firstprivate variables.
2305 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002306
2307 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2308 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2309 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2310 SourceLocation(), SourceLocation())) {
2311 ClausesWithImplicit.push_back(Implicit);
2312 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2313 DSAChecker.getImplicitFirstprivate().size();
2314 } else
2315 ErrorFound = true;
2316 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002317 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002318
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002319 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002320 switch (Kind) {
2321 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002322 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2323 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002324 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002325 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002326 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002327 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2328 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002329 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002330 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002331 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2332 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002333 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002334 case OMPD_for_simd:
2335 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2336 EndLoc, VarsWithInheritedDSA);
2337 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002338 case OMPD_sections:
2339 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2340 EndLoc);
2341 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002342 case OMPD_section:
2343 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002344 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002345 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2346 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002347 case OMPD_single:
2348 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2349 EndLoc);
2350 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002351 case OMPD_master:
2352 assert(ClausesWithImplicit.empty() &&
2353 "No clauses are allowed for 'omp master' directive");
2354 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2355 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002356 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002357 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2358 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002359 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002360 case OMPD_parallel_for:
2361 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2362 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002363 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002364 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002365 case OMPD_parallel_for_simd:
2366 Res = ActOnOpenMPParallelForSimdDirective(
2367 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002368 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002369 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002370 case OMPD_parallel_sections:
2371 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2372 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002373 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002374 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002375 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002376 Res =
2377 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002378 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002379 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002380 case OMPD_taskyield:
2381 assert(ClausesWithImplicit.empty() &&
2382 "No clauses are allowed for 'omp taskyield' directive");
2383 assert(AStmt == nullptr &&
2384 "No associated statement allowed for 'omp taskyield' directive");
2385 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2386 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002387 case OMPD_barrier:
2388 assert(ClausesWithImplicit.empty() &&
2389 "No clauses are allowed for 'omp barrier' directive");
2390 assert(AStmt == nullptr &&
2391 "No associated statement allowed for 'omp barrier' directive");
2392 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2393 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002394 case OMPD_taskwait:
2395 assert(ClausesWithImplicit.empty() &&
2396 "No clauses are allowed for 'omp taskwait' directive");
2397 assert(AStmt == nullptr &&
2398 "No associated statement allowed for 'omp taskwait' directive");
2399 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2400 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002401 case OMPD_taskgroup:
2402 assert(ClausesWithImplicit.empty() &&
2403 "No clauses are allowed for 'omp taskgroup' directive");
2404 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2405 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002406 case OMPD_flush:
2407 assert(AStmt == nullptr &&
2408 "No associated statement allowed for 'omp flush' directive");
2409 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2410 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002411 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002412 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2413 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002414 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002415 case OMPD_atomic:
2416 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2417 EndLoc);
2418 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002419 case OMPD_teams:
2420 Res =
2421 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2422 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002423 case OMPD_target:
2424 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2425 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002426 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002427 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002428 case OMPD_target_parallel:
2429 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2430 StartLoc, EndLoc);
2431 AllowedNameModifiers.push_back(OMPD_target);
2432 AllowedNameModifiers.push_back(OMPD_parallel);
2433 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002434 case OMPD_target_parallel_for:
2435 Res = ActOnOpenMPTargetParallelForDirective(
2436 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2437 AllowedNameModifiers.push_back(OMPD_target);
2438 AllowedNameModifiers.push_back(OMPD_parallel);
2439 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002440 case OMPD_cancellation_point:
2441 assert(ClausesWithImplicit.empty() &&
2442 "No clauses are allowed for 'omp cancellation point' directive");
2443 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2444 "cancellation point' directive");
2445 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2446 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002447 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002448 assert(AStmt == nullptr &&
2449 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002450 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2451 CancelRegion);
2452 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002453 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002454 case OMPD_target_data:
2455 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2456 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002457 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002458 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002459 case OMPD_target_enter_data:
2460 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2461 EndLoc);
2462 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2463 break;
Samuel Antao72590762016-01-19 20:04:50 +00002464 case OMPD_target_exit_data:
2465 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2466 EndLoc);
2467 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2468 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002469 case OMPD_taskloop:
2470 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2471 EndLoc, VarsWithInheritedDSA);
2472 AllowedNameModifiers.push_back(OMPD_taskloop);
2473 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002474 case OMPD_taskloop_simd:
2475 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2476 EndLoc, VarsWithInheritedDSA);
2477 AllowedNameModifiers.push_back(OMPD_taskloop);
2478 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002479 case OMPD_distribute:
2480 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2481 EndLoc, VarsWithInheritedDSA);
2482 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002483 case OMPD_target_update:
2484 assert(!AStmt && "Statement is not allowed for target update");
2485 Res =
2486 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2487 AllowedNameModifiers.push_back(OMPD_target_update);
2488 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002489 case OMPD_distribute_parallel_for:
2490 Res = ActOnOpenMPDistributeParallelForDirective(
2491 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2492 AllowedNameModifiers.push_back(OMPD_parallel);
2493 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002494 case OMPD_distribute_parallel_for_simd:
2495 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2496 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2497 AllowedNameModifiers.push_back(OMPD_parallel);
2498 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002499 case OMPD_distribute_simd:
2500 Res = ActOnOpenMPDistributeSimdDirective(
2501 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2502 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002503 case OMPD_target_parallel_for_simd:
2504 Res = ActOnOpenMPTargetParallelForSimdDirective(
2505 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2506 AllowedNameModifiers.push_back(OMPD_target);
2507 AllowedNameModifiers.push_back(OMPD_parallel);
2508 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002509 case OMPD_target_simd:
2510 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2511 EndLoc, VarsWithInheritedDSA);
2512 AllowedNameModifiers.push_back(OMPD_target);
2513 break;
Kelvin Li02532872016-08-05 14:37:37 +00002514 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002515 Res = ActOnOpenMPTeamsDistributeDirective(
2516 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002517 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002518 case OMPD_teams_distribute_simd:
2519 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2520 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2521 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002522 case OMPD_teams_distribute_parallel_for_simd:
2523 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2524 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2525 AllowedNameModifiers.push_back(OMPD_parallel);
2526 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002527 case OMPD_teams_distribute_parallel_for:
2528 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2529 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2530 AllowedNameModifiers.push_back(OMPD_parallel);
2531 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002532 case OMPD_target_teams:
2533 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2534 EndLoc);
2535 AllowedNameModifiers.push_back(OMPD_target);
2536 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002537 case OMPD_target_teams_distribute:
2538 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2539 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2540 AllowedNameModifiers.push_back(OMPD_target);
2541 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002542 case OMPD_target_teams_distribute_parallel_for:
2543 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2544 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2545 AllowedNameModifiers.push_back(OMPD_target);
2546 AllowedNameModifiers.push_back(OMPD_parallel);
2547 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002548 case OMPD_target_teams_distribute_parallel_for_simd:
2549 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2550 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2551 AllowedNameModifiers.push_back(OMPD_target);
2552 AllowedNameModifiers.push_back(OMPD_parallel);
2553 break;
Kelvin Lida681182017-01-10 18:08:18 +00002554 case OMPD_target_teams_distribute_simd:
2555 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2556 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2557 AllowedNameModifiers.push_back(OMPD_target);
2558 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002559 case OMPD_declare_target:
2560 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002561 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002562 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002563 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002564 llvm_unreachable("OpenMP Directive is not allowed");
2565 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002566 llvm_unreachable("Unknown OpenMP directive");
2567 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002568
Alexey Bataev4acb8592014-07-07 13:01:15 +00002569 for (auto P : VarsWithInheritedDSA) {
2570 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2571 << P.first << P.second->getSourceRange();
2572 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002573 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2574
2575 if (!AllowedNameModifiers.empty())
2576 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2577 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002578
Alexey Bataeved09d242014-05-28 05:53:51 +00002579 if (ErrorFound)
2580 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002581 return Res;
2582}
2583
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002584Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2585 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002586 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002587 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2588 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002589 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002590 assert(Linears.size() == LinModifiers.size());
2591 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002592 if (!DG || DG.get().isNull())
2593 return DeclGroupPtrTy();
2594
2595 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002596 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002597 return DG;
2598 }
2599 auto *ADecl = DG.get().getSingleDecl();
2600 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2601 ADecl = FTD->getTemplatedDecl();
2602
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002603 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2604 if (!FD) {
2605 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002606 return DeclGroupPtrTy();
2607 }
2608
Alexey Bataev2af33e32016-04-07 12:45:37 +00002609 // OpenMP [2.8.2, declare simd construct, Description]
2610 // The parameter of the simdlen clause must be a constant positive integer
2611 // expression.
2612 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002613 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002614 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002615 // OpenMP [2.8.2, declare simd construct, Description]
2616 // The special this pointer can be used as if was one of the arguments to the
2617 // function in any of the linear, aligned, or uniform clauses.
2618 // The uniform clause declares one or more arguments to have an invariant
2619 // value for all concurrent invocations of the function in the execution of a
2620 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002621 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2622 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002623 for (auto *E : Uniforms) {
2624 E = E->IgnoreParenImpCasts();
2625 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2626 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2627 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2628 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002629 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2630 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002631 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002632 }
2633 if (isa<CXXThisExpr>(E)) {
2634 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002635 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002636 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002637 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2638 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002639 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002640 // OpenMP [2.8.2, declare simd construct, Description]
2641 // The aligned clause declares that the object to which each list item points
2642 // is aligned to the number of bytes expressed in the optional parameter of
2643 // the aligned clause.
2644 // The special this pointer can be used as if was one of the arguments to the
2645 // function in any of the linear, aligned, or uniform clauses.
2646 // The type of list items appearing in the aligned clause must be array,
2647 // pointer, reference to array, or reference to pointer.
2648 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2649 Expr *AlignedThis = nullptr;
2650 for (auto *E : Aligneds) {
2651 E = E->IgnoreParenImpCasts();
2652 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2653 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2654 auto *CanonPVD = PVD->getCanonicalDecl();
2655 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2656 FD->getParamDecl(PVD->getFunctionScopeIndex())
2657 ->getCanonicalDecl() == CanonPVD) {
2658 // OpenMP [2.8.1, simd construct, Restrictions]
2659 // A list-item cannot appear in more than one aligned clause.
2660 if (AlignedArgs.count(CanonPVD) > 0) {
2661 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2662 << 1 << E->getSourceRange();
2663 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2664 diag::note_omp_explicit_dsa)
2665 << getOpenMPClauseName(OMPC_aligned);
2666 continue;
2667 }
2668 AlignedArgs[CanonPVD] = E;
2669 QualType QTy = PVD->getType()
2670 .getNonReferenceType()
2671 .getUnqualifiedType()
2672 .getCanonicalType();
2673 const Type *Ty = QTy.getTypePtrOrNull();
2674 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2675 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2676 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2677 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2678 }
2679 continue;
2680 }
2681 }
2682 if (isa<CXXThisExpr>(E)) {
2683 if (AlignedThis) {
2684 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2685 << 2 << E->getSourceRange();
2686 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2687 << getOpenMPClauseName(OMPC_aligned);
2688 }
2689 AlignedThis = E;
2690 continue;
2691 }
2692 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2693 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2694 }
2695 // The optional parameter of the aligned clause, alignment, must be a constant
2696 // positive integer expression. If no optional parameter is specified,
2697 // implementation-defined default alignments for SIMD instructions on the
2698 // target platforms are assumed.
2699 SmallVector<Expr *, 4> NewAligns;
2700 for (auto *E : Alignments) {
2701 ExprResult Align;
2702 if (E)
2703 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2704 NewAligns.push_back(Align.get());
2705 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002706 // OpenMP [2.8.2, declare simd construct, Description]
2707 // The linear clause declares one or more list items to be private to a SIMD
2708 // lane and to have a linear relationship with respect to the iteration space
2709 // of a loop.
2710 // The special this pointer can be used as if was one of the arguments to the
2711 // function in any of the linear, aligned, or uniform clauses.
2712 // When a linear-step expression is specified in a linear clause it must be
2713 // either a constant integer expression or an integer-typed parameter that is
2714 // specified in a uniform clause on the directive.
2715 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2716 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2717 auto MI = LinModifiers.begin();
2718 for (auto *E : Linears) {
2719 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2720 ++MI;
2721 E = E->IgnoreParenImpCasts();
2722 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2723 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2724 auto *CanonPVD = PVD->getCanonicalDecl();
2725 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2726 FD->getParamDecl(PVD->getFunctionScopeIndex())
2727 ->getCanonicalDecl() == CanonPVD) {
2728 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2729 // A list-item cannot appear in more than one linear clause.
2730 if (LinearArgs.count(CanonPVD) > 0) {
2731 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2732 << getOpenMPClauseName(OMPC_linear)
2733 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2734 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2735 diag::note_omp_explicit_dsa)
2736 << getOpenMPClauseName(OMPC_linear);
2737 continue;
2738 }
2739 // Each argument can appear in at most one uniform or linear clause.
2740 if (UniformedArgs.count(CanonPVD) > 0) {
2741 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2742 << getOpenMPClauseName(OMPC_linear)
2743 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2744 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2745 diag::note_omp_explicit_dsa)
2746 << getOpenMPClauseName(OMPC_uniform);
2747 continue;
2748 }
2749 LinearArgs[CanonPVD] = E;
2750 if (E->isValueDependent() || E->isTypeDependent() ||
2751 E->isInstantiationDependent() ||
2752 E->containsUnexpandedParameterPack())
2753 continue;
2754 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2755 PVD->getOriginalType());
2756 continue;
2757 }
2758 }
2759 if (isa<CXXThisExpr>(E)) {
2760 if (UniformedLinearThis) {
2761 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2762 << getOpenMPClauseName(OMPC_linear)
2763 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2764 << E->getSourceRange();
2765 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2766 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2767 : OMPC_linear);
2768 continue;
2769 }
2770 UniformedLinearThis = E;
2771 if (E->isValueDependent() || E->isTypeDependent() ||
2772 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2773 continue;
2774 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2775 E->getType());
2776 continue;
2777 }
2778 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2779 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2780 }
2781 Expr *Step = nullptr;
2782 Expr *NewStep = nullptr;
2783 SmallVector<Expr *, 4> NewSteps;
2784 for (auto *E : Steps) {
2785 // Skip the same step expression, it was checked already.
2786 if (Step == E || !E) {
2787 NewSteps.push_back(E ? NewStep : nullptr);
2788 continue;
2789 }
2790 Step = E;
2791 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2792 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2793 auto *CanonPVD = PVD->getCanonicalDecl();
2794 if (UniformedArgs.count(CanonPVD) == 0) {
2795 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2796 << Step->getSourceRange();
2797 } else if (E->isValueDependent() || E->isTypeDependent() ||
2798 E->isInstantiationDependent() ||
2799 E->containsUnexpandedParameterPack() ||
2800 CanonPVD->getType()->hasIntegerRepresentation())
2801 NewSteps.push_back(Step);
2802 else {
2803 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2804 << Step->getSourceRange();
2805 }
2806 continue;
2807 }
2808 NewStep = Step;
2809 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2810 !Step->isInstantiationDependent() &&
2811 !Step->containsUnexpandedParameterPack()) {
2812 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2813 .get();
2814 if (NewStep)
2815 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2816 }
2817 NewSteps.push_back(NewStep);
2818 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002819 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2820 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002821 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002822 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2823 const_cast<Expr **>(Linears.data()), Linears.size(),
2824 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2825 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002826 ADecl->addAttr(NewAttr);
2827 return ConvertDeclToDeclGroup(ADecl);
2828}
2829
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002830StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2831 Stmt *AStmt,
2832 SourceLocation StartLoc,
2833 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002834 if (!AStmt)
2835 return StmtError();
2836
Alexey Bataev9959db52014-05-06 10:08:46 +00002837 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2838 // 1.2.2 OpenMP Language Terminology
2839 // Structured block - An executable statement with a single entry at the
2840 // top and a single exit at the bottom.
2841 // The point of exit cannot be a branch out of the structured block.
2842 // longjmp() and throw() must not violate the entry/exit criteria.
2843 CS->getCapturedDecl()->setNothrow();
2844
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002845 getCurFunction()->setHasBranchProtectedScope();
2846
Alexey Bataev25e5b442015-09-15 12:52:43 +00002847 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2848 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002849}
2850
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002851namespace {
2852/// \brief Helper class for checking canonical form of the OpenMP loops and
2853/// extracting iteration space of each loop in the loop nest, that will be used
2854/// for IR generation.
2855class OpenMPIterationSpaceChecker {
2856 /// \brief Reference to Sema.
2857 Sema &SemaRef;
2858 /// \brief A location for diagnostics (when there is no some better location).
2859 SourceLocation DefaultLoc;
2860 /// \brief A location for diagnostics (when increment is not compatible).
2861 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002862 /// \brief A source location for referring to loop init later.
2863 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002864 /// \brief A source location for referring to condition later.
2865 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002866 /// \brief A source location for referring to increment later.
2867 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002868 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002869 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002870 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002871 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002872 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002873 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002874 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002875 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002876 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002877 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002878 /// \brief This flag is true when condition is one of:
2879 /// Var < UB
2880 /// Var <= UB
2881 /// UB > Var
2882 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002883 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002884 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002885 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002886 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002887 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002888
2889public:
2890 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002891 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002892 /// \brief Check init-expr for canonical loop form and save loop counter
2893 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002894 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002895 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2896 /// for less/greater and for strict/non-strict comparison.
2897 bool CheckCond(Expr *S);
2898 /// \brief Check incr-expr for canonical loop form and return true if it
2899 /// does not conform, otherwise save loop step (#Step).
2900 bool CheckInc(Expr *S);
2901 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002902 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002903 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002904 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002905 /// \brief Source range of the loop init.
2906 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2907 /// \brief Source range of the loop condition.
2908 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2909 /// \brief Source range of the loop increment.
2910 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2911 /// \brief True if the step should be subtracted.
2912 bool ShouldSubtractStep() const { return SubtractStep; }
2913 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002914 Expr *
2915 BuildNumIterations(Scope *S, const bool LimitedType,
2916 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002917 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002918 Expr *BuildPreCond(Scope *S, Expr *Cond,
2919 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002920 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002921 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2922 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002923 /// \brief Build reference expression to the private counter be used for
2924 /// codegen.
2925 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002926 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002927 Expr *BuildCounterInit() const;
2928 /// \brief Build step of the counter be used for codegen.
2929 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002930 /// \brief Return true if any expression is dependent.
2931 bool Dependent() const;
2932
2933private:
2934 /// \brief Check the right-hand side of an assignment in the increment
2935 /// expression.
2936 bool CheckIncRHS(Expr *RHS);
2937 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002938 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002939 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002940 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002941 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002942 /// \brief Helper to set loop increment.
2943 bool SetStep(Expr *NewStep, bool Subtract);
2944};
2945
2946bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002947 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002948 assert(!LB && !UB && !Step);
2949 return false;
2950 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002951 return LCDecl->getType()->isDependentType() ||
2952 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2953 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002954}
2955
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002956static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002957 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2958 E = ExprTemp->getSubExpr();
2959
2960 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2961 E = MTE->GetTemporaryExpr();
2962
2963 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2964 E = Binder->getSubExpr();
2965
2966 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2967 E = ICE->getSubExprAsWritten();
2968 return E->IgnoreParens();
2969}
2970
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002971bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2972 Expr *NewLCRefExpr,
2973 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002974 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002975 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002976 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002977 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002978 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002979 LCDecl = getCanonicalDecl(NewLCDecl);
2980 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002981 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2982 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002983 if ((Ctor->isCopyOrMoveConstructor() ||
2984 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2985 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002986 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002987 LB = NewLB;
2988 return false;
2989}
2990
2991bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002992 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002993 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002994 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2995 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002996 if (!NewUB)
2997 return true;
2998 UB = NewUB;
2999 TestIsLessOp = LessOp;
3000 TestIsStrictOp = StrictOp;
3001 ConditionSrcRange = SR;
3002 ConditionLoc = SL;
3003 return false;
3004}
3005
3006bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3007 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003008 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003009 if (!NewStep)
3010 return true;
3011 if (!NewStep->isValueDependent()) {
3012 // Check that the step is integer expression.
3013 SourceLocation StepLoc = NewStep->getLocStart();
3014 ExprResult Val =
3015 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3016 if (Val.isInvalid())
3017 return true;
3018 NewStep = Val.get();
3019
3020 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3021 // If test-expr is of form var relational-op b and relational-op is < or
3022 // <= then incr-expr must cause var to increase on each iteration of the
3023 // loop. If test-expr is of form var relational-op b and relational-op is
3024 // > or >= then incr-expr must cause var to decrease on each iteration of
3025 // the loop.
3026 // If test-expr is of form b relational-op var and relational-op is < or
3027 // <= then incr-expr must cause var to decrease on each iteration of the
3028 // loop. If test-expr is of form b relational-op var and relational-op is
3029 // > or >= then incr-expr must cause var to increase on each iteration of
3030 // the loop.
3031 llvm::APSInt Result;
3032 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3033 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3034 bool IsConstNeg =
3035 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003036 bool IsConstPos =
3037 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003038 bool IsConstZero = IsConstant && !Result.getBoolValue();
3039 if (UB && (IsConstZero ||
3040 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003041 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003042 SemaRef.Diag(NewStep->getExprLoc(),
3043 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003044 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003045 SemaRef.Diag(ConditionLoc,
3046 diag::note_omp_loop_cond_requres_compatible_incr)
3047 << TestIsLessOp << ConditionSrcRange;
3048 return true;
3049 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003050 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003051 NewStep =
3052 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3053 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003054 Subtract = !Subtract;
3055 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003056 }
3057
3058 Step = NewStep;
3059 SubtractStep = Subtract;
3060 return false;
3061}
3062
Alexey Bataev9c821032015-04-30 04:23:23 +00003063bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003064 // Check init-expr for canonical loop form and save loop counter
3065 // variable - #Var and its initialization value - #LB.
3066 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3067 // var = lb
3068 // integer-type var = lb
3069 // random-access-iterator-type var = lb
3070 // pointer-type var = lb
3071 //
3072 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003073 if (EmitDiags) {
3074 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3075 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003076 return true;
3077 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003078 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3079 if (!ExprTemp->cleanupsHaveSideEffects())
3080 S = ExprTemp->getSubExpr();
3081
Alexander Musmana5f070a2014-10-01 06:03:56 +00003082 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003083 if (Expr *E = dyn_cast<Expr>(S))
3084 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003085 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003086 if (BO->getOpcode() == BO_Assign) {
3087 auto *LHS = BO->getLHS()->IgnoreParens();
3088 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3089 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3090 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3091 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3092 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3093 }
3094 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3095 if (ME->isArrow() &&
3096 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3097 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3098 }
3099 }
David Majnemer9d168222016-08-05 17:44:54 +00003100 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003101 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003102 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003103 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003104 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003105 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003106 SemaRef.Diag(S->getLocStart(),
3107 diag::ext_omp_loop_not_canonical_init)
3108 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003109 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003110 }
3111 }
3112 }
David Majnemer9d168222016-08-05 17:44:54 +00003113 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003114 if (CE->getOperator() == OO_Equal) {
3115 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003116 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003117 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3118 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3119 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3120 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3121 }
3122 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3123 if (ME->isArrow() &&
3124 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3125 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3126 }
3127 }
3128 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003130 if (Dependent() || SemaRef.CurContext->isDependentContext())
3131 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003132 if (EmitDiags) {
3133 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3134 << S->getSourceRange();
3135 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003136 return true;
3137}
3138
Alexey Bataev23b69422014-06-18 07:08:49 +00003139/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003140/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003141static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003142 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003143 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003144 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003145 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3146 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003147 if ((Ctor->isCopyOrMoveConstructor() ||
3148 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3149 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003150 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003151 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3152 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3153 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3154 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3155 return getCanonicalDecl(ME->getMemberDecl());
3156 return getCanonicalDecl(VD);
3157 }
3158 }
3159 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3160 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3161 return getCanonicalDecl(ME->getMemberDecl());
3162 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003163}
3164
3165bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3166 // Check test-expr for canonical form, save upper-bound UB, flags for
3167 // less/greater and for strict/non-strict comparison.
3168 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3169 // var relational-op b
3170 // b relational-op var
3171 //
3172 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003173 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003174 return true;
3175 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003176 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003177 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003178 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003179 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003180 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003181 return SetUB(BO->getRHS(),
3182 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3183 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3184 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003185 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 return SetUB(BO->getLHS(),
3187 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3188 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3189 BO->getSourceRange(), BO->getOperatorLoc());
3190 }
David Majnemer9d168222016-08-05 17:44:54 +00003191 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003192 if (CE->getNumArgs() == 2) {
3193 auto Op = CE->getOperator();
3194 switch (Op) {
3195 case OO_Greater:
3196 case OO_GreaterEqual:
3197 case OO_Less:
3198 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003199 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003200 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3201 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3202 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003203 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003204 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3205 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3206 CE->getOperatorLoc());
3207 break;
3208 default:
3209 break;
3210 }
3211 }
3212 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003213 if (Dependent() || SemaRef.CurContext->isDependentContext())
3214 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003215 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003216 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003217 return true;
3218}
3219
3220bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3221 // RHS of canonical loop form increment can be:
3222 // var + incr
3223 // incr + var
3224 // var - incr
3225 //
3226 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003227 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003228 if (BO->isAdditiveOp()) {
3229 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003230 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003231 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003232 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003233 return SetStep(BO->getLHS(), false);
3234 }
David Majnemer9d168222016-08-05 17:44:54 +00003235 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003236 bool IsAdd = CE->getOperator() == OO_Plus;
3237 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003238 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003239 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003240 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003241 return SetStep(CE->getArg(0), false);
3242 }
3243 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003244 if (Dependent() || SemaRef.CurContext->isDependentContext())
3245 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003246 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003247 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003248 return true;
3249}
3250
3251bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3252 // Check incr-expr for canonical loop form and return true if it
3253 // does not conform.
3254 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3255 // ++var
3256 // var++
3257 // --var
3258 // var--
3259 // var += incr
3260 // var -= incr
3261 // var = var + incr
3262 // var = incr + var
3263 // var = var - incr
3264 //
3265 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003266 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003267 return true;
3268 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003269 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3270 if (!ExprTemp->cleanupsHaveSideEffects())
3271 S = ExprTemp->getSubExpr();
3272
Alexander Musmana5f070a2014-10-01 06:03:56 +00003273 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003274 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003275 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003276 if (UO->isIncrementDecrementOp() &&
3277 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003278 return SetStep(SemaRef
3279 .ActOnIntegerConstant(UO->getLocStart(),
3280 (UO->isDecrementOp() ? -1 : 1))
3281 .get(),
3282 false);
3283 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003284 switch (BO->getOpcode()) {
3285 case BO_AddAssign:
3286 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003287 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003288 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3289 break;
3290 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003291 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003292 return CheckIncRHS(BO->getRHS());
3293 break;
3294 default:
3295 break;
3296 }
David Majnemer9d168222016-08-05 17:44:54 +00003297 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003298 switch (CE->getOperator()) {
3299 case OO_PlusPlus:
3300 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003301 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003302 return SetStep(SemaRef
3303 .ActOnIntegerConstant(
3304 CE->getLocStart(),
3305 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3306 .get(),
3307 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003308 break;
3309 case OO_PlusEqual:
3310 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003311 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003312 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3313 break;
3314 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003315 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003316 return CheckIncRHS(CE->getArg(1));
3317 break;
3318 default:
3319 break;
3320 }
3321 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003322 if (Dependent() || SemaRef.CurContext->isDependentContext())
3323 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003324 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003325 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003326 return true;
3327}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003328
Alexey Bataev5a3af132016-03-29 08:58:54 +00003329static ExprResult
3330tryBuildCapture(Sema &SemaRef, Expr *Capture,
3331 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003332 if (SemaRef.CurContext->isDependentContext())
3333 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003334 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3335 return SemaRef.PerformImplicitConversion(
3336 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3337 /*AllowExplicit=*/true);
3338 auto I = Captures.find(Capture);
3339 if (I != Captures.end())
3340 return buildCapture(SemaRef, Capture, I->second);
3341 DeclRefExpr *Ref = nullptr;
3342 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3343 Captures[Capture] = Ref;
3344 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003345}
3346
Alexander Musmana5f070a2014-10-01 06:03:56 +00003347/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003348Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3349 Scope *S, const bool LimitedType,
3350 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003351 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003352 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003353 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003354 SemaRef.getLangOpts().CPlusPlus) {
3355 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003356 auto *UBExpr = TestIsLessOp ? UB : LB;
3357 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003358 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3359 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003360 if (!Upper || !Lower)
3361 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003362
3363 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3364
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003365 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003366 // BuildBinOp already emitted error, this one is to point user to upper
3367 // and lower bound, and to tell what is passed to 'operator-'.
3368 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3369 << Upper->getSourceRange() << Lower->getSourceRange();
3370 return nullptr;
3371 }
3372 }
3373
3374 if (!Diff.isUsable())
3375 return nullptr;
3376
3377 // Upper - Lower [- 1]
3378 if (TestIsStrictOp)
3379 Diff = SemaRef.BuildBinOp(
3380 S, DefaultLoc, BO_Sub, Diff.get(),
3381 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3382 if (!Diff.isUsable())
3383 return nullptr;
3384
3385 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003386 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3387 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003388 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003389 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003390 if (!Diff.isUsable())
3391 return nullptr;
3392
3393 // Parentheses (for dumping/debugging purposes only).
3394 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3395 if (!Diff.isUsable())
3396 return nullptr;
3397
3398 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003399 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003400 if (!Diff.isUsable())
3401 return nullptr;
3402
Alexander Musman174b3ca2014-10-06 11:16:29 +00003403 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003404 QualType Type = Diff.get()->getType();
3405 auto &C = SemaRef.Context;
3406 bool UseVarType = VarType->hasIntegerRepresentation() &&
3407 C.getTypeSize(Type) > C.getTypeSize(VarType);
3408 if (!Type->isIntegerType() || UseVarType) {
3409 unsigned NewSize =
3410 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3411 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3412 : Type->hasSignedIntegerRepresentation();
3413 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003414 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3415 Diff = SemaRef.PerformImplicitConversion(
3416 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3417 if (!Diff.isUsable())
3418 return nullptr;
3419 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003420 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003421 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003422 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3423 if (NewSize != C.getTypeSize(Type)) {
3424 if (NewSize < C.getTypeSize(Type)) {
3425 assert(NewSize == 64 && "incorrect loop var size");
3426 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3427 << InitSrcRange << ConditionSrcRange;
3428 }
3429 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003430 NewSize, Type->hasSignedIntegerRepresentation() ||
3431 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003432 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3433 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3434 Sema::AA_Converting, true);
3435 if (!Diff.isUsable())
3436 return nullptr;
3437 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003438 }
3439 }
3440
Alexander Musmana5f070a2014-10-01 06:03:56 +00003441 return Diff.get();
3442}
3443
Alexey Bataev5a3af132016-03-29 08:58:54 +00003444Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3445 Scope *S, Expr *Cond,
3446 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003447 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3448 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3449 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003450
Alexey Bataev5a3af132016-03-29 08:58:54 +00003451 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3452 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3453 if (!NewLB.isUsable() || !NewUB.isUsable())
3454 return nullptr;
3455
Alexey Bataev62dbb972015-04-22 11:59:37 +00003456 auto CondExpr = SemaRef.BuildBinOp(
3457 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3458 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003459 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003460 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003461 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3462 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003463 CondExpr = SemaRef.PerformImplicitConversion(
3464 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3465 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003466 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003467 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3468 // Otherwise use original loop conditon and evaluate it in runtime.
3469 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3470}
3471
Alexander Musmana5f070a2014-10-01 06:03:56 +00003472/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003473DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003474 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003475 auto *VD = dyn_cast<VarDecl>(LCDecl);
3476 if (!VD) {
3477 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3478 auto *Ref = buildDeclRefExpr(
3479 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003480 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3481 // If the loop control decl is explicitly marked as private, do not mark it
3482 // as captured again.
3483 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3484 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003485 return Ref;
3486 }
3487 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003488 DefaultLoc);
3489}
3490
3491Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003492 if (LCDecl && !LCDecl->isInvalidDecl()) {
3493 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003494 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003495 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3496 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003497 if (PrivateVar->isInvalidDecl())
3498 return nullptr;
3499 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3500 }
3501 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003502}
3503
Samuel Antao4c8035b2016-12-12 18:00:20 +00003504/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003505Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3506
3507/// \brief Build step of the counter be used for codegen.
3508Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3509
3510/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003511struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003512 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003513 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003514 /// \brief This expression calculates the number of iterations in the loop.
3515 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003516 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003517 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003518 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003519 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003520 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003521 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003522 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003523 /// \brief This is step for the #CounterVar used to generate its update:
3524 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003525 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003526 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003527 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003528 /// \brief Source range of the loop init.
3529 SourceRange InitSrcRange;
3530 /// \brief Source range of the loop condition.
3531 SourceRange CondSrcRange;
3532 /// \brief Source range of the loop increment.
3533 SourceRange IncSrcRange;
3534};
3535
Alexey Bataev23b69422014-06-18 07:08:49 +00003536} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003537
Alexey Bataev9c821032015-04-30 04:23:23 +00003538void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3539 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3540 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003541 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3542 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003543 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3544 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003545 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3546 if (auto *D = ISC.GetLoopDecl()) {
3547 auto *VD = dyn_cast<VarDecl>(D);
3548 if (!VD) {
3549 if (auto *Private = IsOpenMPCapturedDecl(D))
3550 VD = Private;
3551 else {
3552 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3553 /*WithInit=*/false);
3554 VD = cast<VarDecl>(Ref->getDecl());
3555 }
3556 }
3557 DSAStack->addLoopControlVariable(D, VD);
3558 }
3559 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003560 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003561 }
3562}
3563
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003564/// \brief Called on a for stmt to check and extract its iteration space
3565/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003566static bool CheckOpenMPIterationSpace(
3567 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3568 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003569 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003570 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003571 LoopIterationSpace &ResultIterSpace,
3572 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003573 // OpenMP [2.6, Canonical Loop Form]
3574 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003575 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003576 if (!For) {
3577 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003578 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3579 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3580 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3581 if (NestedLoopCount > 1) {
3582 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3583 SemaRef.Diag(DSA.getConstructLoc(),
3584 diag::note_omp_collapse_ordered_expr)
3585 << 2 << CollapseLoopCountExpr->getSourceRange()
3586 << OrderedLoopCountExpr->getSourceRange();
3587 else if (CollapseLoopCountExpr)
3588 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3589 diag::note_omp_collapse_ordered_expr)
3590 << 0 << CollapseLoopCountExpr->getSourceRange();
3591 else
3592 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3593 diag::note_omp_collapse_ordered_expr)
3594 << 1 << OrderedLoopCountExpr->getSourceRange();
3595 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003596 return true;
3597 }
3598 assert(For->getBody());
3599
3600 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3601
3602 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003603 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003604 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003605 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003606
3607 bool HasErrors = false;
3608
3609 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003610 if (auto *LCDecl = ISC.GetLoopDecl()) {
3611 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003612
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003613 // OpenMP [2.6, Canonical Loop Form]
3614 // Var is one of the following:
3615 // A variable of signed or unsigned integer type.
3616 // For C++, a variable of a random access iterator type.
3617 // For C, a variable of a pointer type.
3618 auto VarType = LCDecl->getType().getNonReferenceType();
3619 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3620 !VarType->isPointerType() &&
3621 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3622 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3623 << SemaRef.getLangOpts().CPlusPlus;
3624 HasErrors = true;
3625 }
3626
3627 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3628 // a Construct
3629 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3630 // parallel for construct is (are) private.
3631 // The loop iteration variable in the associated for-loop of a simd
3632 // construct with just one associated for-loop is linear with a
3633 // constant-linear-step that is the increment of the associated for-loop.
3634 // Exclude loop var from the list of variables with implicitly defined data
3635 // sharing attributes.
3636 VarsWithImplicitDSA.erase(LCDecl);
3637
3638 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3639 // in a Construct, C/C++].
3640 // The loop iteration variable in the associated for-loop of a simd
3641 // construct with just one associated for-loop may be listed in a linear
3642 // clause with a constant-linear-step that is the increment of the
3643 // associated for-loop.
3644 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3645 // parallel for construct may be listed in a private or lastprivate clause.
3646 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3647 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3648 // declared in the loop and it is predetermined as a private.
3649 auto PredeterminedCKind =
3650 isOpenMPSimdDirective(DKind)
3651 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3652 : OMPC_private;
3653 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3654 DVar.CKind != PredeterminedCKind) ||
3655 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3656 isOpenMPDistributeDirective(DKind)) &&
3657 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3658 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3659 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3660 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3661 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3662 << getOpenMPClauseName(PredeterminedCKind);
3663 if (DVar.RefExpr == nullptr)
3664 DVar.CKind = PredeterminedCKind;
3665 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3666 HasErrors = true;
3667 } else if (LoopDeclRefExpr != nullptr) {
3668 // Make the loop iteration variable private (for worksharing constructs),
3669 // linear (for simd directives with the only one associated loop) or
3670 // lastprivate (for simd directives with several collapsed or ordered
3671 // loops).
3672 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003673 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3674 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003675 /*FromParent=*/false);
3676 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3677 }
3678
3679 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3680
3681 // Check test-expr.
3682 HasErrors |= ISC.CheckCond(For->getCond());
3683
3684 // Check incr-expr.
3685 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003686 }
3687
Alexander Musmana5f070a2014-10-01 06:03:56 +00003688 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003689 return HasErrors;
3690
Alexander Musmana5f070a2014-10-01 06:03:56 +00003691 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003692 ResultIterSpace.PreCond =
3693 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003694 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003695 DSA.getCurScope(),
3696 (isOpenMPWorksharingDirective(DKind) ||
3697 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3698 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003699 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003700 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003701 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3702 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3703 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3704 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3705 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3706 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3707
Alexey Bataev62dbb972015-04-22 11:59:37 +00003708 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3709 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003710 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003711 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003712 ResultIterSpace.CounterInit == nullptr ||
3713 ResultIterSpace.CounterStep == nullptr);
3714
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 return HasErrors;
3716}
3717
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003718/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003719static ExprResult
3720BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3721 ExprResult Start,
3722 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003723 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003724 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3725 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003726 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003727 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003728 VarRef.get()->getType())) {
3729 NewStart = SemaRef.PerformImplicitConversion(
3730 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3731 /*AllowExplicit=*/true);
3732 if (!NewStart.isUsable())
3733 return ExprError();
3734 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003735
3736 auto Init =
3737 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3738 return Init;
3739}
3740
Alexander Musmana5f070a2014-10-01 06:03:56 +00003741/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003742static ExprResult
3743BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3744 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3745 ExprResult Step, bool Subtract,
3746 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003747 // Add parentheses (for debugging purposes only).
3748 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3749 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3750 !Step.isUsable())
3751 return ExprError();
3752
Alexey Bataev5a3af132016-03-29 08:58:54 +00003753 ExprResult NewStep = Step;
3754 if (Captures)
3755 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003756 if (NewStep.isInvalid())
3757 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003758 ExprResult Update =
3759 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003760 if (!Update.isUsable())
3761 return ExprError();
3762
Alexey Bataevc0214e02016-02-16 12:13:49 +00003763 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3764 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003765 ExprResult NewStart = Start;
3766 if (Captures)
3767 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003768 if (NewStart.isInvalid())
3769 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003770
Alexey Bataevc0214e02016-02-16 12:13:49 +00003771 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3772 ExprResult SavedUpdate = Update;
3773 ExprResult UpdateVal;
3774 if (VarRef.get()->getType()->isOverloadableType() ||
3775 NewStart.get()->getType()->isOverloadableType() ||
3776 Update.get()->getType()->isOverloadableType()) {
3777 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3778 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3779 Update =
3780 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3781 if (Update.isUsable()) {
3782 UpdateVal =
3783 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3784 VarRef.get(), SavedUpdate.get());
3785 if (UpdateVal.isUsable()) {
3786 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3787 UpdateVal.get());
3788 }
3789 }
3790 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3791 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003792
Alexey Bataevc0214e02016-02-16 12:13:49 +00003793 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3794 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3795 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3796 NewStart.get(), SavedUpdate.get());
3797 if (!Update.isUsable())
3798 return ExprError();
3799
Alexey Bataev11481f52016-02-17 10:29:05 +00003800 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3801 VarRef.get()->getType())) {
3802 Update = SemaRef.PerformImplicitConversion(
3803 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3804 if (!Update.isUsable())
3805 return ExprError();
3806 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003807
3808 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3809 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003810 return Update;
3811}
3812
3813/// \brief Convert integer expression \a E to make it have at least \a Bits
3814/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003815static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003816 if (E == nullptr)
3817 return ExprError();
3818 auto &C = SemaRef.Context;
3819 QualType OldType = E->getType();
3820 unsigned HasBits = C.getTypeSize(OldType);
3821 if (HasBits >= Bits)
3822 return ExprResult(E);
3823 // OK to convert to signed, because new type has more bits than old.
3824 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3825 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3826 true);
3827}
3828
3829/// \brief Check if the given expression \a E is a constant integer that fits
3830/// into \a Bits bits.
3831static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3832 if (E == nullptr)
3833 return false;
3834 llvm::APSInt Result;
3835 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3836 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3837 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003838}
3839
Alexey Bataev5a3af132016-03-29 08:58:54 +00003840/// Build preinits statement for the given declarations.
3841static Stmt *buildPreInits(ASTContext &Context,
3842 SmallVectorImpl<Decl *> &PreInits) {
3843 if (!PreInits.empty()) {
3844 return new (Context) DeclStmt(
3845 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3846 SourceLocation(), SourceLocation());
3847 }
3848 return nullptr;
3849}
3850
3851/// Build preinits statement for the given declarations.
3852static Stmt *buildPreInits(ASTContext &Context,
3853 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3854 if (!Captures.empty()) {
3855 SmallVector<Decl *, 16> PreInits;
3856 for (auto &Pair : Captures)
3857 PreInits.push_back(Pair.second->getDecl());
3858 return buildPreInits(Context, PreInits);
3859 }
3860 return nullptr;
3861}
3862
3863/// Build postupdate expression for the given list of postupdates expressions.
3864static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3865 Expr *PostUpdate = nullptr;
3866 if (!PostUpdates.empty()) {
3867 for (auto *E : PostUpdates) {
3868 Expr *ConvE = S.BuildCStyleCastExpr(
3869 E->getExprLoc(),
3870 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3871 E->getExprLoc(), E)
3872 .get();
3873 PostUpdate = PostUpdate
3874 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3875 PostUpdate, ConvE)
3876 .get()
3877 : ConvE;
3878 }
3879 }
3880 return PostUpdate;
3881}
3882
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003883/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003884/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3885/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003886static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003887CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3888 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3889 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003891 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003892 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003893 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003894 // Found 'collapse' clause - calculate collapse number.
3895 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003896 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003897 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003898 }
3899 if (OrderedLoopCountExpr) {
3900 // Found 'ordered' clause - calculate collapse number.
3901 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003902 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3903 if (Result.getLimitedValue() < NestedLoopCount) {
3904 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3905 diag::err_omp_wrong_ordered_loop_count)
3906 << OrderedLoopCountExpr->getSourceRange();
3907 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3908 diag::note_collapse_loop_count)
3909 << CollapseLoopCountExpr->getSourceRange();
3910 }
3911 NestedLoopCount = Result.getLimitedValue();
3912 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003913 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003914 // This is helper routine for loop directives (e.g., 'for', 'simd',
3915 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003916 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003917 SmallVector<LoopIterationSpace, 4> IterSpaces;
3918 IterSpaces.resize(NestedLoopCount);
3919 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003920 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003921 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003922 NestedLoopCount, CollapseLoopCountExpr,
3923 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003924 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003925 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003926 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003927 // OpenMP [2.8.1, simd construct, Restrictions]
3928 // All loops associated with the construct must be perfectly nested; that
3929 // is, there must be no intervening code nor any OpenMP directive between
3930 // any two loops.
3931 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003932 }
3933
Alexander Musmana5f070a2014-10-01 06:03:56 +00003934 Built.clear(/* size */ NestedLoopCount);
3935
3936 if (SemaRef.CurContext->isDependentContext())
3937 return NestedLoopCount;
3938
3939 // An example of what is generated for the following code:
3940 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003941 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003942 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003943 // for (k = 0; k < NK; ++k)
3944 // for (j = J0; j < NJ; j+=2) {
3945 // <loop body>
3946 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003947 //
3948 // We generate the code below.
3949 // Note: the loop body may be outlined in CodeGen.
3950 // Note: some counters may be C++ classes, operator- is used to find number of
3951 // iterations and operator+= to calculate counter value.
3952 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3953 // or i64 is currently supported).
3954 //
3955 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3956 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3957 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3958 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3959 // // similar updates for vars in clauses (e.g. 'linear')
3960 // <loop body (using local i and j)>
3961 // }
3962 // i = NI; // assign final values of counters
3963 // j = NJ;
3964 //
3965
3966 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3967 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003968 // Precondition tests if there is at least one iteration (all conditions are
3969 // true).
3970 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003971 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003972 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003973 32 /* Bits */, SemaRef
3974 .PerformImplicitConversion(
3975 N0->IgnoreImpCasts(), N0->getType(),
3976 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003977 .get(),
3978 SemaRef);
3979 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003980 64 /* Bits */, SemaRef
3981 .PerformImplicitConversion(
3982 N0->IgnoreImpCasts(), N0->getType(),
3983 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003984 .get(),
3985 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003986
3987 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3988 return NestedLoopCount;
3989
3990 auto &C = SemaRef.Context;
3991 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3992
3993 Scope *CurScope = DSA.getCurScope();
3994 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003995 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003996 PreCond =
3997 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3998 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003999 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004000 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004001 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004002 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4003 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004004 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004005 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004006 SemaRef
4007 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4008 Sema::AA_Converting,
4009 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004010 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004011 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004012 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004013 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004014 SemaRef
4015 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4016 Sema::AA_Converting,
4017 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004018 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004019 }
4020
4021 // Choose either the 32-bit or 64-bit version.
4022 ExprResult LastIteration = LastIteration64;
4023 if (LastIteration32.isUsable() &&
4024 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4025 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4026 FitsInto(
4027 32 /* Bits */,
4028 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4029 LastIteration64.get(), SemaRef)))
4030 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004031 QualType VType = LastIteration.get()->getType();
4032 QualType RealVType = VType;
4033 QualType StrideVType = VType;
4034 if (isOpenMPTaskLoopDirective(DKind)) {
4035 VType =
4036 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4037 StrideVType =
4038 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4039 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004040
4041 if (!LastIteration.isUsable())
4042 return 0;
4043
4044 // Save the number of iterations.
4045 ExprResult NumIterations = LastIteration;
4046 {
4047 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004048 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4049 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004050 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4051 if (!LastIteration.isUsable())
4052 return 0;
4053 }
4054
4055 // Calculate the last iteration number beforehand instead of doing this on
4056 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4057 llvm::APSInt Result;
4058 bool IsConstant =
4059 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4060 ExprResult CalcLastIteration;
4061 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004062 ExprResult SaveRef =
4063 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004064 LastIteration = SaveRef;
4065
4066 // Prepare SaveRef + 1.
4067 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004068 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004069 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4070 if (!NumIterations.isUsable())
4071 return 0;
4072 }
4073
4074 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4075
David Majnemer9d168222016-08-05 17:44:54 +00004076 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004077 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004078 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4079 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004080 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004081 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4082 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004083 SemaRef.AddInitializerToDecl(LBDecl,
4084 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4085 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004086
4087 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004088 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4089 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004090 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004091 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004092
4093 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4094 // This will be used to implement clause 'lastprivate'.
4095 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004096 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4097 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004098 SemaRef.AddInitializerToDecl(ILDecl,
4099 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4100 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004101
4102 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004103 VarDecl *STDecl =
4104 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4105 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004106 SemaRef.AddInitializerToDecl(STDecl,
4107 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4108 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004109
4110 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004111 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004112 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4113 UB.get(), LastIteration.get());
4114 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4115 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4116 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4117 CondOp.get());
4118 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004119
4120 // If we have a combined directive that combines 'distribute', 'for' or
4121 // 'simd' we need to be able to access the bounds of the schedule of the
4122 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4123 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4124 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004125
Carlo Bertolliffafe102017-04-20 00:39:39 +00004126 // Lower bound variable, initialized with zero.
4127 VarDecl *CombLBDecl =
4128 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4129 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4130 SemaRef.AddInitializerToDecl(
4131 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4132 /*DirectInit*/ false);
4133
4134 // Upper bound variable, initialized with last iteration number.
4135 VarDecl *CombUBDecl =
4136 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4137 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4138 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4139 /*DirectInit*/ false);
4140
4141 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4142 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4143 ExprResult CombCondOp =
4144 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4145 LastIteration.get(), CombUB.get());
4146 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4147 CombCondOp.get());
4148 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4149
4150 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004151 // We expect to have at least 2 more parameters than the 'parallel'
4152 // directive does - the lower and upper bounds of the previous schedule.
4153 assert(CD->getNumParams() >= 4 &&
4154 "Unexpected number of parameters in loop combined directive");
4155
4156 // Set the proper type for the bounds given what we learned from the
4157 // enclosed loops.
4158 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4159 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4160
4161 // Previous lower and upper bounds are obtained from the region
4162 // parameters.
4163 PrevLB =
4164 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4165 PrevUB =
4166 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4167 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004168 }
4169
4170 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004171 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004172 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004173 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004174 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4175 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004176 Expr *RHS =
4177 (isOpenMPWorksharingDirective(DKind) ||
4178 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4179 ? LB.get()
4180 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004181 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4182 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004183
4184 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4185 Expr *CombRHS =
4186 (isOpenMPWorksharingDirective(DKind) ||
4187 isOpenMPTaskLoopDirective(DKind) ||
4188 isOpenMPDistributeDirective(DKind))
4189 ? CombLB.get()
4190 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4191 CombInit =
4192 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4193 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4194 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004195 }
4196
Alexander Musmanc6388682014-12-15 07:07:06 +00004197 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004198 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004199 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004200 (isOpenMPWorksharingDirective(DKind) ||
4201 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004202 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4203 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4204 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004205 ExprResult CombCond;
4206 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4207 CombCond =
4208 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4209 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004210 // Loop increment (IV = IV + 1)
4211 SourceLocation IncLoc;
4212 ExprResult Inc =
4213 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4214 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4215 if (!Inc.isUsable())
4216 return 0;
4217 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004218 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4219 if (!Inc.isUsable())
4220 return 0;
4221
4222 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4223 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004224 // In combined construct, add combined version that use CombLB and CombUB
4225 // base variables for the update
4226 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004227 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4228 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004229 // LB + ST
4230 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4231 if (!NextLB.isUsable())
4232 return 0;
4233 // LB = LB + ST
4234 NextLB =
4235 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4236 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4237 if (!NextLB.isUsable())
4238 return 0;
4239 // UB + ST
4240 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4241 if (!NextUB.isUsable())
4242 return 0;
4243 // UB = UB + ST
4244 NextUB =
4245 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4246 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4247 if (!NextUB.isUsable())
4248 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004249 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4250 CombNextLB =
4251 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4252 if (!NextLB.isUsable())
4253 return 0;
4254 // LB = LB + ST
4255 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4256 CombNextLB.get());
4257 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4258 if (!CombNextLB.isUsable())
4259 return 0;
4260 // UB + ST
4261 CombNextUB =
4262 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4263 if (!CombNextUB.isUsable())
4264 return 0;
4265 // UB = UB + ST
4266 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4267 CombNextUB.get());
4268 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4269 if (!CombNextUB.isUsable())
4270 return 0;
4271 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004272 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004273
Carlo Bertolliffafe102017-04-20 00:39:39 +00004274 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004275 // directive with for as IV = IV + ST; ensure upper bound expression based
4276 // on PrevUB instead of NumIterations - used to implement 'for' when found
4277 // in combination with 'distribute', like in 'distribute parallel for'
4278 SourceLocation DistIncLoc;
4279 ExprResult DistCond, DistInc, PrevEUB;
4280 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4281 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4282 assert(DistCond.isUsable() && "distribute cond expr was not built");
4283
4284 DistInc =
4285 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4286 assert(DistInc.isUsable() && "distribute inc expr was not built");
4287 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4288 DistInc.get());
4289 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4290 assert(DistInc.isUsable() && "distribute inc expr was not built");
4291
4292 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4293 // construct
4294 SourceLocation DistEUBLoc;
4295 ExprResult IsUBGreater =
4296 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4297 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4298 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4299 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4300 CondOp.get());
4301 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4302 }
4303
Alexander Musmana5f070a2014-10-01 06:03:56 +00004304 // Build updates and final values of the loop counters.
4305 bool HasErrors = false;
4306 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004307 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004308 Built.Updates.resize(NestedLoopCount);
4309 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004310 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004311 {
4312 ExprResult Div;
4313 // Go from inner nested loop to outer.
4314 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4315 LoopIterationSpace &IS = IterSpaces[Cnt];
4316 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4317 // Build: Iter = (IV / Div) % IS.NumIters
4318 // where Div is product of previous iterations' IS.NumIters.
4319 ExprResult Iter;
4320 if (Div.isUsable()) {
4321 Iter =
4322 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4323 } else {
4324 Iter = IV;
4325 assert((Cnt == (int)NestedLoopCount - 1) &&
4326 "unusable div expected on first iteration only");
4327 }
4328
4329 if (Cnt != 0 && Iter.isUsable())
4330 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4331 IS.NumIterations);
4332 if (!Iter.isUsable()) {
4333 HasErrors = true;
4334 break;
4335 }
4336
Alexey Bataev39f915b82015-05-08 10:41:21 +00004337 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004338 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4339 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4340 IS.CounterVar->getExprLoc(),
4341 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004342 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004343 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004344 if (!Init.isUsable()) {
4345 HasErrors = true;
4346 break;
4347 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004348 ExprResult Update = BuildCounterUpdate(
4349 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4350 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004351 if (!Update.isUsable()) {
4352 HasErrors = true;
4353 break;
4354 }
4355
4356 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4357 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004358 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004359 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004360 if (!Final.isUsable()) {
4361 HasErrors = true;
4362 break;
4363 }
4364
4365 // Build Div for the next iteration: Div <- Div * IS.NumIters
4366 if (Cnt != 0) {
4367 if (Div.isUnset())
4368 Div = IS.NumIterations;
4369 else
4370 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4371 IS.NumIterations);
4372
4373 // Add parentheses (for debugging purposes only).
4374 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004375 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004376 if (!Div.isUsable()) {
4377 HasErrors = true;
4378 break;
4379 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004380 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004381 }
4382 if (!Update.isUsable() || !Final.isUsable()) {
4383 HasErrors = true;
4384 break;
4385 }
4386 // Save results
4387 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004388 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004389 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004390 Built.Updates[Cnt] = Update.get();
4391 Built.Finals[Cnt] = Final.get();
4392 }
4393 }
4394
4395 if (HasErrors)
4396 return 0;
4397
4398 // Save results
4399 Built.IterationVarRef = IV.get();
4400 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004401 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004402 Built.CalcLastIteration =
4403 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004404 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004405 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004406 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004407 Built.Init = Init.get();
4408 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004409 Built.LB = LB.get();
4410 Built.UB = UB.get();
4411 Built.IL = IL.get();
4412 Built.ST = ST.get();
4413 Built.EUB = EUB.get();
4414 Built.NLB = NextLB.get();
4415 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004416 Built.PrevLB = PrevLB.get();
4417 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004418 Built.DistInc = DistInc.get();
4419 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004420 Built.DistCombinedFields.LB = CombLB.get();
4421 Built.DistCombinedFields.UB = CombUB.get();
4422 Built.DistCombinedFields.EUB = CombEUB.get();
4423 Built.DistCombinedFields.Init = CombInit.get();
4424 Built.DistCombinedFields.Cond = CombCond.get();
4425 Built.DistCombinedFields.NLB = CombNextLB.get();
4426 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004427
Alexey Bataev8b427062016-05-25 12:36:08 +00004428 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4429 // Fill data for doacross depend clauses.
4430 for (auto Pair : DSA.getDoacrossDependClauses()) {
4431 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4432 Pair.first->setCounterValue(CounterVal);
4433 else {
4434 if (NestedLoopCount != Pair.second.size() ||
4435 NestedLoopCount != LoopMultipliers.size() + 1) {
4436 // Erroneous case - clause has some problems.
4437 Pair.first->setCounterValue(CounterVal);
4438 continue;
4439 }
4440 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4441 auto I = Pair.second.rbegin();
4442 auto IS = IterSpaces.rbegin();
4443 auto ILM = LoopMultipliers.rbegin();
4444 Expr *UpCounterVal = CounterVal;
4445 Expr *Multiplier = nullptr;
4446 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4447 if (I->first) {
4448 assert(IS->CounterStep);
4449 Expr *NormalizedOffset =
4450 SemaRef
4451 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4452 I->first, IS->CounterStep)
4453 .get();
4454 if (Multiplier) {
4455 NormalizedOffset =
4456 SemaRef
4457 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4458 NormalizedOffset, Multiplier)
4459 .get();
4460 }
4461 assert(I->second == OO_Plus || I->second == OO_Minus);
4462 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004463 UpCounterVal = SemaRef
4464 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4465 UpCounterVal, NormalizedOffset)
4466 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004467 }
4468 Multiplier = *ILM;
4469 ++I;
4470 ++IS;
4471 ++ILM;
4472 }
4473 Pair.first->setCounterValue(UpCounterVal);
4474 }
4475 }
4476
Alexey Bataevabfc0692014-06-25 06:52:00 +00004477 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004478}
4479
Alexey Bataev10e775f2015-07-30 11:36:16 +00004480static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004481 auto CollapseClauses =
4482 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4483 if (CollapseClauses.begin() != CollapseClauses.end())
4484 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004485 return nullptr;
4486}
4487
Alexey Bataev10e775f2015-07-30 11:36:16 +00004488static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004489 auto OrderedClauses =
4490 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4491 if (OrderedClauses.begin() != OrderedClauses.end())
4492 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004493 return nullptr;
4494}
4495
Kelvin Lic5609492016-07-15 04:39:07 +00004496static bool checkSimdlenSafelenSpecified(Sema &S,
4497 const ArrayRef<OMPClause *> Clauses) {
4498 OMPSafelenClause *Safelen = nullptr;
4499 OMPSimdlenClause *Simdlen = nullptr;
4500
4501 for (auto *Clause : Clauses) {
4502 if (Clause->getClauseKind() == OMPC_safelen)
4503 Safelen = cast<OMPSafelenClause>(Clause);
4504 else if (Clause->getClauseKind() == OMPC_simdlen)
4505 Simdlen = cast<OMPSimdlenClause>(Clause);
4506 if (Safelen && Simdlen)
4507 break;
4508 }
4509
4510 if (Simdlen && Safelen) {
4511 llvm::APSInt SimdlenRes, SafelenRes;
4512 auto SimdlenLength = Simdlen->getSimdlen();
4513 auto SafelenLength = Safelen->getSafelen();
4514 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4515 SimdlenLength->isInstantiationDependent() ||
4516 SimdlenLength->containsUnexpandedParameterPack())
4517 return false;
4518 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4519 SafelenLength->isInstantiationDependent() ||
4520 SafelenLength->containsUnexpandedParameterPack())
4521 return false;
4522 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4523 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4524 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4525 // If both simdlen and safelen clauses are specified, the value of the
4526 // simdlen parameter must be less than or equal to the value of the safelen
4527 // parameter.
4528 if (SimdlenRes > SafelenRes) {
4529 S.Diag(SimdlenLength->getExprLoc(),
4530 diag::err_omp_wrong_simdlen_safelen_values)
4531 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4532 return true;
4533 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004534 }
4535 return false;
4536}
4537
Alexey Bataev4acb8592014-07-07 13:01:15 +00004538StmtResult Sema::ActOnOpenMPSimdDirective(
4539 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4540 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004541 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004542 if (!AStmt)
4543 return StmtError();
4544
4545 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004546 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004547 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4548 // define the nested loops number.
4549 unsigned NestedLoopCount = CheckOpenMPLoop(
4550 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4551 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004552 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004553 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004554
Alexander Musmana5f070a2014-10-01 06:03:56 +00004555 assert((CurContext->isDependentContext() || B.builtAll()) &&
4556 "omp simd loop exprs were not built");
4557
Alexander Musman3276a272015-03-21 10:12:56 +00004558 if (!CurContext->isDependentContext()) {
4559 // Finalize the clauses that need pre-built expressions for CodeGen.
4560 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004561 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004562 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004563 B.NumIterations, *this, CurScope,
4564 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004565 return StmtError();
4566 }
4567 }
4568
Kelvin Lic5609492016-07-15 04:39:07 +00004569 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004570 return StmtError();
4571
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004572 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004573 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4574 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004575}
4576
Alexey Bataev4acb8592014-07-07 13:01:15 +00004577StmtResult Sema::ActOnOpenMPForDirective(
4578 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4579 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004580 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004581 if (!AStmt)
4582 return StmtError();
4583
4584 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004585 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004586 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4587 // define the nested loops number.
4588 unsigned NestedLoopCount = CheckOpenMPLoop(
4589 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4590 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004591 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004592 return StmtError();
4593
Alexander Musmana5f070a2014-10-01 06:03:56 +00004594 assert((CurContext->isDependentContext() || B.builtAll()) &&
4595 "omp for loop exprs were not built");
4596
Alexey Bataev54acd402015-08-04 11:18:19 +00004597 if (!CurContext->isDependentContext()) {
4598 // Finalize the clauses that need pre-built expressions for CodeGen.
4599 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004600 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004601 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004602 B.NumIterations, *this, CurScope,
4603 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004604 return StmtError();
4605 }
4606 }
4607
Alexey Bataevf29276e2014-06-18 04:14:57 +00004608 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004609 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004610 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004611}
4612
Alexander Musmanf82886e2014-09-18 05:12:34 +00004613StmtResult Sema::ActOnOpenMPForSimdDirective(
4614 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4615 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004616 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004617 if (!AStmt)
4618 return StmtError();
4619
4620 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004621 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004622 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4623 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004624 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004625 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4626 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4627 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004628 if (NestedLoopCount == 0)
4629 return StmtError();
4630
Alexander Musmanc6388682014-12-15 07:07:06 +00004631 assert((CurContext->isDependentContext() || B.builtAll()) &&
4632 "omp for simd loop exprs were not built");
4633
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004634 if (!CurContext->isDependentContext()) {
4635 // Finalize the clauses that need pre-built expressions for CodeGen.
4636 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004637 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004638 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004639 B.NumIterations, *this, CurScope,
4640 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004641 return StmtError();
4642 }
4643 }
4644
Kelvin Lic5609492016-07-15 04:39:07 +00004645 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004646 return StmtError();
4647
Alexander Musmanf82886e2014-09-18 05:12:34 +00004648 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004649 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4650 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004651}
4652
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004653StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4654 Stmt *AStmt,
4655 SourceLocation StartLoc,
4656 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004657 if (!AStmt)
4658 return StmtError();
4659
4660 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004661 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004662 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004663 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004664 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004665 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004666 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004667 return StmtError();
4668 // All associated statements must be '#pragma omp section' except for
4669 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004670 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004671 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4672 if (SectionStmt)
4673 Diag(SectionStmt->getLocStart(),
4674 diag::err_omp_sections_substmt_not_section);
4675 return StmtError();
4676 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004677 cast<OMPSectionDirective>(SectionStmt)
4678 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004679 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004680 } else {
4681 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4682 return StmtError();
4683 }
4684
4685 getCurFunction()->setHasBranchProtectedScope();
4686
Alexey Bataev25e5b442015-09-15 12:52:43 +00004687 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4688 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004689}
4690
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004691StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4692 SourceLocation StartLoc,
4693 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004694 if (!AStmt)
4695 return StmtError();
4696
4697 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004698
4699 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004700 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004701
Alexey Bataev25e5b442015-09-15 12:52:43 +00004702 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4703 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004704}
4705
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004706StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4707 Stmt *AStmt,
4708 SourceLocation StartLoc,
4709 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004710 if (!AStmt)
4711 return StmtError();
4712
4713 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004714
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004715 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004716
Alexey Bataev3255bf32015-01-19 05:20:46 +00004717 // OpenMP [2.7.3, single Construct, Restrictions]
4718 // The copyprivate clause must not be used with the nowait clause.
4719 OMPClause *Nowait = nullptr;
4720 OMPClause *Copyprivate = nullptr;
4721 for (auto *Clause : Clauses) {
4722 if (Clause->getClauseKind() == OMPC_nowait)
4723 Nowait = Clause;
4724 else if (Clause->getClauseKind() == OMPC_copyprivate)
4725 Copyprivate = Clause;
4726 if (Copyprivate && Nowait) {
4727 Diag(Copyprivate->getLocStart(),
4728 diag::err_omp_single_copyprivate_with_nowait);
4729 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4730 return StmtError();
4731 }
4732 }
4733
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004734 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4735}
4736
Alexander Musman80c22892014-07-17 08:54:58 +00004737StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4738 SourceLocation StartLoc,
4739 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004740 if (!AStmt)
4741 return StmtError();
4742
4743 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004744
4745 getCurFunction()->setHasBranchProtectedScope();
4746
4747 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4748}
4749
Alexey Bataev28c75412015-12-15 08:19:24 +00004750StmtResult Sema::ActOnOpenMPCriticalDirective(
4751 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4752 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004753 if (!AStmt)
4754 return StmtError();
4755
4756 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004757
Alexey Bataev28c75412015-12-15 08:19:24 +00004758 bool ErrorFound = false;
4759 llvm::APSInt Hint;
4760 SourceLocation HintLoc;
4761 bool DependentHint = false;
4762 for (auto *C : Clauses) {
4763 if (C->getClauseKind() == OMPC_hint) {
4764 if (!DirName.getName()) {
4765 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4766 ErrorFound = true;
4767 }
4768 Expr *E = cast<OMPHintClause>(C)->getHint();
4769 if (E->isTypeDependent() || E->isValueDependent() ||
4770 E->isInstantiationDependent())
4771 DependentHint = true;
4772 else {
4773 Hint = E->EvaluateKnownConstInt(Context);
4774 HintLoc = C->getLocStart();
4775 }
4776 }
4777 }
4778 if (ErrorFound)
4779 return StmtError();
4780 auto Pair = DSAStack->getCriticalWithHint(DirName);
4781 if (Pair.first && DirName.getName() && !DependentHint) {
4782 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4783 Diag(StartLoc, diag::err_omp_critical_with_hint);
4784 if (HintLoc.isValid()) {
4785 Diag(HintLoc, diag::note_omp_critical_hint_here)
4786 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4787 } else
4788 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4789 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4790 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4791 << 1
4792 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4793 /*Radix=*/10, /*Signed=*/false);
4794 } else
4795 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4796 }
4797 }
4798
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004799 getCurFunction()->setHasBranchProtectedScope();
4800
Alexey Bataev28c75412015-12-15 08:19:24 +00004801 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4802 Clauses, AStmt);
4803 if (!Pair.first && DirName.getName() && !DependentHint)
4804 DSAStack->addCriticalWithHint(Dir, Hint);
4805 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004806}
4807
Alexey Bataev4acb8592014-07-07 13:01:15 +00004808StmtResult Sema::ActOnOpenMPParallelForDirective(
4809 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4810 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004811 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004812 if (!AStmt)
4813 return StmtError();
4814
Alexey Bataev4acb8592014-07-07 13:01:15 +00004815 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4816 // 1.2.2 OpenMP Language Terminology
4817 // Structured block - An executable statement with a single entry at the
4818 // top and a single exit at the bottom.
4819 // The point of exit cannot be a branch out of the structured block.
4820 // longjmp() and throw() must not violate the entry/exit criteria.
4821 CS->getCapturedDecl()->setNothrow();
4822
Alexander Musmanc6388682014-12-15 07:07:06 +00004823 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004824 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4825 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004826 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004827 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4828 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4829 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004830 if (NestedLoopCount == 0)
4831 return StmtError();
4832
Alexander Musmana5f070a2014-10-01 06:03:56 +00004833 assert((CurContext->isDependentContext() || B.builtAll()) &&
4834 "omp parallel for loop exprs were not built");
4835
Alexey Bataev54acd402015-08-04 11:18:19 +00004836 if (!CurContext->isDependentContext()) {
4837 // Finalize the clauses that need pre-built expressions for CodeGen.
4838 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004839 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004840 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004841 B.NumIterations, *this, CurScope,
4842 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004843 return StmtError();
4844 }
4845 }
4846
Alexey Bataev4acb8592014-07-07 13:01:15 +00004847 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004848 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004849 NestedLoopCount, Clauses, AStmt, B,
4850 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004851}
4852
Alexander Musmane4e893b2014-09-23 09:33:00 +00004853StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4854 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4855 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004856 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004857 if (!AStmt)
4858 return StmtError();
4859
Alexander Musmane4e893b2014-09-23 09:33:00 +00004860 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4861 // 1.2.2 OpenMP Language Terminology
4862 // Structured block - An executable statement with a single entry at the
4863 // top and a single exit at the bottom.
4864 // The point of exit cannot be a branch out of the structured block.
4865 // longjmp() and throw() must not violate the entry/exit criteria.
4866 CS->getCapturedDecl()->setNothrow();
4867
Alexander Musmanc6388682014-12-15 07:07:06 +00004868 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004869 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4870 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004871 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004872 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4873 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4874 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004875 if (NestedLoopCount == 0)
4876 return StmtError();
4877
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004878 if (!CurContext->isDependentContext()) {
4879 // Finalize the clauses that need pre-built expressions for CodeGen.
4880 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004881 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004882 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004883 B.NumIterations, *this, CurScope,
4884 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004885 return StmtError();
4886 }
4887 }
4888
Kelvin Lic5609492016-07-15 04:39:07 +00004889 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004890 return StmtError();
4891
Alexander Musmane4e893b2014-09-23 09:33:00 +00004892 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004893 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004894 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004895}
4896
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004897StmtResult
4898Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4899 Stmt *AStmt, SourceLocation StartLoc,
4900 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004901 if (!AStmt)
4902 return StmtError();
4903
4904 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004905 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004906 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004907 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004908 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004909 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004910 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004911 return StmtError();
4912 // All associated statements must be '#pragma omp section' except for
4913 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004914 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004915 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4916 if (SectionStmt)
4917 Diag(SectionStmt->getLocStart(),
4918 diag::err_omp_parallel_sections_substmt_not_section);
4919 return StmtError();
4920 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004921 cast<OMPSectionDirective>(SectionStmt)
4922 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004923 }
4924 } else {
4925 Diag(AStmt->getLocStart(),
4926 diag::err_omp_parallel_sections_not_compound_stmt);
4927 return StmtError();
4928 }
4929
4930 getCurFunction()->setHasBranchProtectedScope();
4931
Alexey Bataev25e5b442015-09-15 12:52:43 +00004932 return OMPParallelSectionsDirective::Create(
4933 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004934}
4935
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004936StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4937 Stmt *AStmt, SourceLocation StartLoc,
4938 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004939 if (!AStmt)
4940 return StmtError();
4941
David Majnemer9d168222016-08-05 17:44:54 +00004942 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004943 // 1.2.2 OpenMP Language Terminology
4944 // Structured block - An executable statement with a single entry at the
4945 // top and a single exit at the bottom.
4946 // The point of exit cannot be a branch out of the structured block.
4947 // longjmp() and throw() must not violate the entry/exit criteria.
4948 CS->getCapturedDecl()->setNothrow();
4949
4950 getCurFunction()->setHasBranchProtectedScope();
4951
Alexey Bataev25e5b442015-09-15 12:52:43 +00004952 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4953 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004954}
4955
Alexey Bataev68446b72014-07-18 07:47:19 +00004956StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4957 SourceLocation EndLoc) {
4958 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4959}
4960
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004961StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4962 SourceLocation EndLoc) {
4963 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4964}
4965
Alexey Bataev2df347a2014-07-18 10:17:07 +00004966StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4967 SourceLocation EndLoc) {
4968 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4969}
4970
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004971StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4972 SourceLocation StartLoc,
4973 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004974 if (!AStmt)
4975 return StmtError();
4976
4977 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004978
4979 getCurFunction()->setHasBranchProtectedScope();
4980
4981 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4982}
4983
Alexey Bataev6125da92014-07-21 11:26:11 +00004984StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4985 SourceLocation StartLoc,
4986 SourceLocation EndLoc) {
4987 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4988 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4989}
4990
Alexey Bataev346265e2015-09-25 10:37:12 +00004991StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4992 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004993 SourceLocation StartLoc,
4994 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004995 OMPClause *DependFound = nullptr;
4996 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004997 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004998 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004999 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005000 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005001 for (auto *C : Clauses) {
5002 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5003 DependFound = C;
5004 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5005 if (DependSourceClause) {
5006 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5007 << getOpenMPDirectiveName(OMPD_ordered)
5008 << getOpenMPClauseName(OMPC_depend) << 2;
5009 ErrorFound = true;
5010 } else
5011 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005012 if (DependSinkClause) {
5013 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5014 << 0;
5015 ErrorFound = true;
5016 }
5017 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5018 if (DependSourceClause) {
5019 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5020 << 1;
5021 ErrorFound = true;
5022 }
5023 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005024 }
5025 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005026 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005027 else if (C->getClauseKind() == OMPC_simd)
5028 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005029 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005030 if (!ErrorFound && !SC &&
5031 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005032 // OpenMP [2.8.1,simd Construct, Restrictions]
5033 // An ordered construct with the simd clause is the only OpenMP construct
5034 // that can appear in the simd region.
5035 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005036 ErrorFound = true;
5037 } else if (DependFound && (TC || SC)) {
5038 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5039 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5040 ErrorFound = true;
5041 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5042 Diag(DependFound->getLocStart(),
5043 diag::err_omp_ordered_directive_without_param);
5044 ErrorFound = true;
5045 } else if (TC || Clauses.empty()) {
5046 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5047 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5048 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5049 << (TC != nullptr);
5050 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5051 ErrorFound = true;
5052 }
5053 }
5054 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005055 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005056
5057 if (AStmt) {
5058 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5059
5060 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005061 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005062
5063 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005064}
5065
Alexey Bataev1d160b12015-03-13 12:27:31 +00005066namespace {
5067/// \brief Helper class for checking expression in 'omp atomic [update]'
5068/// construct.
5069class OpenMPAtomicUpdateChecker {
5070 /// \brief Error results for atomic update expressions.
5071 enum ExprAnalysisErrorCode {
5072 /// \brief A statement is not an expression statement.
5073 NotAnExpression,
5074 /// \brief Expression is not builtin binary or unary operation.
5075 NotABinaryOrUnaryExpression,
5076 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5077 NotAnUnaryIncDecExpression,
5078 /// \brief An expression is not of scalar type.
5079 NotAScalarType,
5080 /// \brief A binary operation is not an assignment operation.
5081 NotAnAssignmentOp,
5082 /// \brief RHS part of the binary operation is not a binary expression.
5083 NotABinaryExpression,
5084 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5085 /// expression.
5086 NotABinaryOperator,
5087 /// \brief RHS binary operation does not have reference to the updated LHS
5088 /// part.
5089 NotAnUpdateExpression,
5090 /// \brief No errors is found.
5091 NoError
5092 };
5093 /// \brief Reference to Sema.
5094 Sema &SemaRef;
5095 /// \brief A location for note diagnostics (when error is found).
5096 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005097 /// \brief 'x' lvalue part of the source atomic expression.
5098 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005099 /// \brief 'expr' rvalue part of the source atomic expression.
5100 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005101 /// \brief Helper expression of the form
5102 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5103 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5104 Expr *UpdateExpr;
5105 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5106 /// important for non-associative operations.
5107 bool IsXLHSInRHSPart;
5108 BinaryOperatorKind Op;
5109 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005110 /// \brief true if the source expression is a postfix unary operation, false
5111 /// if it is a prefix unary operation.
5112 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005113
5114public:
5115 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005116 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005117 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005118 /// \brief Check specified statement that it is suitable for 'atomic update'
5119 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005120 /// expression. If DiagId and NoteId == 0, then only check is performed
5121 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005122 /// \param DiagId Diagnostic which should be emitted if error is found.
5123 /// \param NoteId Diagnostic note for the main error message.
5124 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005125 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005126 /// \brief Return the 'x' lvalue part of the source atomic expression.
5127 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005128 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5129 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005130 /// \brief Return the update expression used in calculation of the updated
5131 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5132 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5133 Expr *getUpdateExpr() const { return UpdateExpr; }
5134 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5135 /// false otherwise.
5136 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5137
Alexey Bataevb78ca832015-04-01 03:33:17 +00005138 /// \brief true if the source expression is a postfix unary operation, false
5139 /// if it is a prefix unary operation.
5140 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5141
Alexey Bataev1d160b12015-03-13 12:27:31 +00005142private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005143 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5144 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005145};
5146} // namespace
5147
5148bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5149 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5150 ExprAnalysisErrorCode ErrorFound = NoError;
5151 SourceLocation ErrorLoc, NoteLoc;
5152 SourceRange ErrorRange, NoteRange;
5153 // Allowed constructs are:
5154 // x = x binop expr;
5155 // x = expr binop x;
5156 if (AtomicBinOp->getOpcode() == BO_Assign) {
5157 X = AtomicBinOp->getLHS();
5158 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5159 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5160 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5161 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5162 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005163 Op = AtomicInnerBinOp->getOpcode();
5164 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005165 auto *LHS = AtomicInnerBinOp->getLHS();
5166 auto *RHS = AtomicInnerBinOp->getRHS();
5167 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5168 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5169 /*Canonical=*/true);
5170 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5171 /*Canonical=*/true);
5172 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5173 /*Canonical=*/true);
5174 if (XId == LHSId) {
5175 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005176 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005177 } else if (XId == RHSId) {
5178 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005179 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005180 } else {
5181 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5182 ErrorRange = AtomicInnerBinOp->getSourceRange();
5183 NoteLoc = X->getExprLoc();
5184 NoteRange = X->getSourceRange();
5185 ErrorFound = NotAnUpdateExpression;
5186 }
5187 } else {
5188 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5189 ErrorRange = AtomicInnerBinOp->getSourceRange();
5190 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5191 NoteRange = SourceRange(NoteLoc, NoteLoc);
5192 ErrorFound = NotABinaryOperator;
5193 }
5194 } else {
5195 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5196 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5197 ErrorFound = NotABinaryExpression;
5198 }
5199 } else {
5200 ErrorLoc = AtomicBinOp->getExprLoc();
5201 ErrorRange = AtomicBinOp->getSourceRange();
5202 NoteLoc = AtomicBinOp->getOperatorLoc();
5203 NoteRange = SourceRange(NoteLoc, NoteLoc);
5204 ErrorFound = NotAnAssignmentOp;
5205 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005206 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005207 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5208 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5209 return true;
5210 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005211 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005212 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005213}
5214
5215bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5216 unsigned NoteId) {
5217 ExprAnalysisErrorCode ErrorFound = NoError;
5218 SourceLocation ErrorLoc, NoteLoc;
5219 SourceRange ErrorRange, NoteRange;
5220 // Allowed constructs are:
5221 // x++;
5222 // x--;
5223 // ++x;
5224 // --x;
5225 // x binop= expr;
5226 // x = x binop expr;
5227 // x = expr binop x;
5228 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5229 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5230 if (AtomicBody->getType()->isScalarType() ||
5231 AtomicBody->isInstantiationDependent()) {
5232 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5233 AtomicBody->IgnoreParenImpCasts())) {
5234 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005235 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005236 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005237 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005238 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005239 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005240 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005241 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5242 AtomicBody->IgnoreParenImpCasts())) {
5243 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005244 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005245 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005246 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5247 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005248 // Check for Unary Operation
5249 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005250 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005251 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5252 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005253 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005254 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5255 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005256 } else {
5257 ErrorFound = NotAnUnaryIncDecExpression;
5258 ErrorLoc = AtomicUnaryOp->getExprLoc();
5259 ErrorRange = AtomicUnaryOp->getSourceRange();
5260 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5261 NoteRange = SourceRange(NoteLoc, NoteLoc);
5262 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005263 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005264 ErrorFound = NotABinaryOrUnaryExpression;
5265 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5266 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5267 }
5268 } else {
5269 ErrorFound = NotAScalarType;
5270 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5271 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5272 }
5273 } else {
5274 ErrorFound = NotAnExpression;
5275 NoteLoc = ErrorLoc = S->getLocStart();
5276 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5277 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005278 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005279 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5280 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5281 return true;
5282 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005283 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005284 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005285 // Build an update expression of form 'OpaqueValueExpr(x) binop
5286 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5287 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5288 auto *OVEX = new (SemaRef.getASTContext())
5289 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5290 auto *OVEExpr = new (SemaRef.getASTContext())
5291 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5292 auto Update =
5293 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5294 IsXLHSInRHSPart ? OVEExpr : OVEX);
5295 if (Update.isInvalid())
5296 return true;
5297 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5298 Sema::AA_Casting);
5299 if (Update.isInvalid())
5300 return true;
5301 UpdateExpr = Update.get();
5302 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005303 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005304}
5305
Alexey Bataev0162e452014-07-22 10:10:35 +00005306StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5307 Stmt *AStmt,
5308 SourceLocation StartLoc,
5309 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005310 if (!AStmt)
5311 return StmtError();
5312
David Majnemer9d168222016-08-05 17:44:54 +00005313 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005314 // 1.2.2 OpenMP Language Terminology
5315 // Structured block - An executable statement with a single entry at the
5316 // top and a single exit at the bottom.
5317 // The point of exit cannot be a branch out of the structured block.
5318 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005319 OpenMPClauseKind AtomicKind = OMPC_unknown;
5320 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005321 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005322 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005323 C->getClauseKind() == OMPC_update ||
5324 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005325 if (AtomicKind != OMPC_unknown) {
5326 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5327 << SourceRange(C->getLocStart(), C->getLocEnd());
5328 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5329 << getOpenMPClauseName(AtomicKind);
5330 } else {
5331 AtomicKind = C->getClauseKind();
5332 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005333 }
5334 }
5335 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005336
Alexey Bataev459dec02014-07-24 06:46:57 +00005337 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005338 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5339 Body = EWC->getSubExpr();
5340
Alexey Bataev62cec442014-11-18 10:14:22 +00005341 Expr *X = nullptr;
5342 Expr *V = nullptr;
5343 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005344 Expr *UE = nullptr;
5345 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005346 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005347 // OpenMP [2.12.6, atomic Construct]
5348 // In the next expressions:
5349 // * x and v (as applicable) are both l-value expressions with scalar type.
5350 // * During the execution of an atomic region, multiple syntactic
5351 // occurrences of x must designate the same storage location.
5352 // * Neither of v and expr (as applicable) may access the storage location
5353 // designated by x.
5354 // * Neither of x and expr (as applicable) may access the storage location
5355 // designated by v.
5356 // * expr is an expression with scalar type.
5357 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5358 // * binop, binop=, ++, and -- are not overloaded operators.
5359 // * The expression x binop expr must be numerically equivalent to x binop
5360 // (expr). This requirement is satisfied if the operators in expr have
5361 // precedence greater than binop, or by using parentheses around expr or
5362 // subexpressions of expr.
5363 // * The expression expr binop x must be numerically equivalent to (expr)
5364 // binop x. This requirement is satisfied if the operators in expr have
5365 // precedence equal to or greater than binop, or by using parentheses around
5366 // expr or subexpressions of expr.
5367 // * For forms that allow multiple occurrences of x, the number of times
5368 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005369 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005370 enum {
5371 NotAnExpression,
5372 NotAnAssignmentOp,
5373 NotAScalarType,
5374 NotAnLValue,
5375 NoError
5376 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005377 SourceLocation ErrorLoc, NoteLoc;
5378 SourceRange ErrorRange, NoteRange;
5379 // If clause is read:
5380 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005381 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5382 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005383 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5384 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5385 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5386 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5387 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5388 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5389 if (!X->isLValue() || !V->isLValue()) {
5390 auto NotLValueExpr = X->isLValue() ? V : X;
5391 ErrorFound = NotAnLValue;
5392 ErrorLoc = AtomicBinOp->getExprLoc();
5393 ErrorRange = AtomicBinOp->getSourceRange();
5394 NoteLoc = NotLValueExpr->getExprLoc();
5395 NoteRange = NotLValueExpr->getSourceRange();
5396 }
5397 } else if (!X->isInstantiationDependent() ||
5398 !V->isInstantiationDependent()) {
5399 auto NotScalarExpr =
5400 (X->isInstantiationDependent() || X->getType()->isScalarType())
5401 ? V
5402 : X;
5403 ErrorFound = NotAScalarType;
5404 ErrorLoc = AtomicBinOp->getExprLoc();
5405 ErrorRange = AtomicBinOp->getSourceRange();
5406 NoteLoc = NotScalarExpr->getExprLoc();
5407 NoteRange = NotScalarExpr->getSourceRange();
5408 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005409 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005410 ErrorFound = NotAnAssignmentOp;
5411 ErrorLoc = AtomicBody->getExprLoc();
5412 ErrorRange = AtomicBody->getSourceRange();
5413 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5414 : AtomicBody->getExprLoc();
5415 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5416 : AtomicBody->getSourceRange();
5417 }
5418 } else {
5419 ErrorFound = NotAnExpression;
5420 NoteLoc = ErrorLoc = Body->getLocStart();
5421 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005422 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005423 if (ErrorFound != NoError) {
5424 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5425 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005426 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5427 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005428 return StmtError();
5429 } else if (CurContext->isDependentContext())
5430 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005431 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005432 enum {
5433 NotAnExpression,
5434 NotAnAssignmentOp,
5435 NotAScalarType,
5436 NotAnLValue,
5437 NoError
5438 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005439 SourceLocation ErrorLoc, NoteLoc;
5440 SourceRange ErrorRange, NoteRange;
5441 // If clause is write:
5442 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005443 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5444 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005445 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5446 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005447 X = AtomicBinOp->getLHS();
5448 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005449 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5450 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5451 if (!X->isLValue()) {
5452 ErrorFound = NotAnLValue;
5453 ErrorLoc = AtomicBinOp->getExprLoc();
5454 ErrorRange = AtomicBinOp->getSourceRange();
5455 NoteLoc = X->getExprLoc();
5456 NoteRange = X->getSourceRange();
5457 }
5458 } else if (!X->isInstantiationDependent() ||
5459 !E->isInstantiationDependent()) {
5460 auto NotScalarExpr =
5461 (X->isInstantiationDependent() || X->getType()->isScalarType())
5462 ? E
5463 : X;
5464 ErrorFound = NotAScalarType;
5465 ErrorLoc = AtomicBinOp->getExprLoc();
5466 ErrorRange = AtomicBinOp->getSourceRange();
5467 NoteLoc = NotScalarExpr->getExprLoc();
5468 NoteRange = NotScalarExpr->getSourceRange();
5469 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005470 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005471 ErrorFound = NotAnAssignmentOp;
5472 ErrorLoc = AtomicBody->getExprLoc();
5473 ErrorRange = AtomicBody->getSourceRange();
5474 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5475 : AtomicBody->getExprLoc();
5476 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5477 : AtomicBody->getSourceRange();
5478 }
5479 } else {
5480 ErrorFound = NotAnExpression;
5481 NoteLoc = ErrorLoc = Body->getLocStart();
5482 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005483 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005484 if (ErrorFound != NoError) {
5485 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5486 << ErrorRange;
5487 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5488 << NoteRange;
5489 return StmtError();
5490 } else if (CurContext->isDependentContext())
5491 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005492 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005493 // If clause is update:
5494 // x++;
5495 // x--;
5496 // ++x;
5497 // --x;
5498 // x binop= expr;
5499 // x = x binop expr;
5500 // x = expr binop x;
5501 OpenMPAtomicUpdateChecker Checker(*this);
5502 if (Checker.checkStatement(
5503 Body, (AtomicKind == OMPC_update)
5504 ? diag::err_omp_atomic_update_not_expression_statement
5505 : diag::err_omp_atomic_not_expression_statement,
5506 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005507 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005508 if (!CurContext->isDependentContext()) {
5509 E = Checker.getExpr();
5510 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005511 UE = Checker.getUpdateExpr();
5512 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005513 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005514 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005515 enum {
5516 NotAnAssignmentOp,
5517 NotACompoundStatement,
5518 NotTwoSubstatements,
5519 NotASpecificExpression,
5520 NoError
5521 } ErrorFound = NoError;
5522 SourceLocation ErrorLoc, NoteLoc;
5523 SourceRange ErrorRange, NoteRange;
5524 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5525 // If clause is a capture:
5526 // v = x++;
5527 // v = x--;
5528 // v = ++x;
5529 // v = --x;
5530 // v = x binop= expr;
5531 // v = x = x binop expr;
5532 // v = x = expr binop x;
5533 auto *AtomicBinOp =
5534 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5535 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5536 V = AtomicBinOp->getLHS();
5537 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5538 OpenMPAtomicUpdateChecker Checker(*this);
5539 if (Checker.checkStatement(
5540 Body, diag::err_omp_atomic_capture_not_expression_statement,
5541 diag::note_omp_atomic_update))
5542 return StmtError();
5543 E = Checker.getExpr();
5544 X = Checker.getX();
5545 UE = Checker.getUpdateExpr();
5546 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5547 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005548 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005549 ErrorLoc = AtomicBody->getExprLoc();
5550 ErrorRange = AtomicBody->getSourceRange();
5551 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5552 : AtomicBody->getExprLoc();
5553 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5554 : AtomicBody->getSourceRange();
5555 ErrorFound = NotAnAssignmentOp;
5556 }
5557 if (ErrorFound != NoError) {
5558 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5559 << ErrorRange;
5560 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5561 return StmtError();
5562 } else if (CurContext->isDependentContext()) {
5563 UE = V = E = X = nullptr;
5564 }
5565 } else {
5566 // If clause is a capture:
5567 // { v = x; x = expr; }
5568 // { v = x; x++; }
5569 // { v = x; x--; }
5570 // { v = x; ++x; }
5571 // { v = x; --x; }
5572 // { v = x; x binop= expr; }
5573 // { v = x; x = x binop expr; }
5574 // { v = x; x = expr binop x; }
5575 // { x++; v = x; }
5576 // { x--; v = x; }
5577 // { ++x; v = x; }
5578 // { --x; v = x; }
5579 // { x binop= expr; v = x; }
5580 // { x = x binop expr; v = x; }
5581 // { x = expr binop x; v = x; }
5582 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5583 // Check that this is { expr1; expr2; }
5584 if (CS->size() == 2) {
5585 auto *First = CS->body_front();
5586 auto *Second = CS->body_back();
5587 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5588 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5589 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5590 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5591 // Need to find what subexpression is 'v' and what is 'x'.
5592 OpenMPAtomicUpdateChecker Checker(*this);
5593 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5594 BinaryOperator *BinOp = nullptr;
5595 if (IsUpdateExprFound) {
5596 BinOp = dyn_cast<BinaryOperator>(First);
5597 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5598 }
5599 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5600 // { v = x; x++; }
5601 // { v = x; x--; }
5602 // { v = x; ++x; }
5603 // { v = x; --x; }
5604 // { v = x; x binop= expr; }
5605 // { v = x; x = x binop expr; }
5606 // { v = x; x = expr binop x; }
5607 // Check that the first expression has form v = x.
5608 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5609 llvm::FoldingSetNodeID XId, PossibleXId;
5610 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5611 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5612 IsUpdateExprFound = XId == PossibleXId;
5613 if (IsUpdateExprFound) {
5614 V = BinOp->getLHS();
5615 X = Checker.getX();
5616 E = Checker.getExpr();
5617 UE = Checker.getUpdateExpr();
5618 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005619 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005620 }
5621 }
5622 if (!IsUpdateExprFound) {
5623 IsUpdateExprFound = !Checker.checkStatement(First);
5624 BinOp = nullptr;
5625 if (IsUpdateExprFound) {
5626 BinOp = dyn_cast<BinaryOperator>(Second);
5627 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5628 }
5629 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5630 // { x++; v = x; }
5631 // { x--; v = x; }
5632 // { ++x; v = x; }
5633 // { --x; v = x; }
5634 // { x binop= expr; v = x; }
5635 // { x = x binop expr; v = x; }
5636 // { x = expr binop x; v = x; }
5637 // Check that the second expression has form v = x.
5638 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5639 llvm::FoldingSetNodeID XId, PossibleXId;
5640 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5641 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5642 IsUpdateExprFound = XId == PossibleXId;
5643 if (IsUpdateExprFound) {
5644 V = BinOp->getLHS();
5645 X = Checker.getX();
5646 E = Checker.getExpr();
5647 UE = Checker.getUpdateExpr();
5648 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005649 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005650 }
5651 }
5652 }
5653 if (!IsUpdateExprFound) {
5654 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005655 auto *FirstExpr = dyn_cast<Expr>(First);
5656 auto *SecondExpr = dyn_cast<Expr>(Second);
5657 if (!FirstExpr || !SecondExpr ||
5658 !(FirstExpr->isInstantiationDependent() ||
5659 SecondExpr->isInstantiationDependent())) {
5660 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5661 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005662 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005663 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5664 : First->getLocStart();
5665 NoteRange = ErrorRange = FirstBinOp
5666 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005667 : SourceRange(ErrorLoc, ErrorLoc);
5668 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005669 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5670 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5671 ErrorFound = NotAnAssignmentOp;
5672 NoteLoc = ErrorLoc = SecondBinOp
5673 ? SecondBinOp->getOperatorLoc()
5674 : Second->getLocStart();
5675 NoteRange = ErrorRange =
5676 SecondBinOp ? SecondBinOp->getSourceRange()
5677 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005678 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005679 auto *PossibleXRHSInFirst =
5680 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5681 auto *PossibleXLHSInSecond =
5682 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5683 llvm::FoldingSetNodeID X1Id, X2Id;
5684 PossibleXRHSInFirst->Profile(X1Id, Context,
5685 /*Canonical=*/true);
5686 PossibleXLHSInSecond->Profile(X2Id, Context,
5687 /*Canonical=*/true);
5688 IsUpdateExprFound = X1Id == X2Id;
5689 if (IsUpdateExprFound) {
5690 V = FirstBinOp->getLHS();
5691 X = SecondBinOp->getLHS();
5692 E = SecondBinOp->getRHS();
5693 UE = nullptr;
5694 IsXLHSInRHSPart = false;
5695 IsPostfixUpdate = true;
5696 } else {
5697 ErrorFound = NotASpecificExpression;
5698 ErrorLoc = FirstBinOp->getExprLoc();
5699 ErrorRange = FirstBinOp->getSourceRange();
5700 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5701 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5702 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005703 }
5704 }
5705 }
5706 }
5707 } else {
5708 NoteLoc = ErrorLoc = Body->getLocStart();
5709 NoteRange = ErrorRange =
5710 SourceRange(Body->getLocStart(), Body->getLocStart());
5711 ErrorFound = NotTwoSubstatements;
5712 }
5713 } else {
5714 NoteLoc = ErrorLoc = Body->getLocStart();
5715 NoteRange = ErrorRange =
5716 SourceRange(Body->getLocStart(), Body->getLocStart());
5717 ErrorFound = NotACompoundStatement;
5718 }
5719 if (ErrorFound != NoError) {
5720 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5721 << ErrorRange;
5722 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5723 return StmtError();
5724 } else if (CurContext->isDependentContext()) {
5725 UE = V = E = X = nullptr;
5726 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005727 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005728 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005729
5730 getCurFunction()->setHasBranchProtectedScope();
5731
Alexey Bataev62cec442014-11-18 10:14:22 +00005732 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005733 X, V, E, UE, IsXLHSInRHSPart,
5734 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005735}
5736
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005737StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5738 Stmt *AStmt,
5739 SourceLocation StartLoc,
5740 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005741 if (!AStmt)
5742 return StmtError();
5743
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005744 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5745 // 1.2.2 OpenMP Language Terminology
5746 // Structured block - An executable statement with a single entry at the
5747 // top and a single exit at the bottom.
5748 // The point of exit cannot be a branch out of the structured block.
5749 // longjmp() and throw() must not violate the entry/exit criteria.
5750 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005751
Alexey Bataev13314bf2014-10-09 04:18:56 +00005752 // OpenMP [2.16, Nesting of Regions]
5753 // If specified, a teams construct must be contained within a target
5754 // construct. That target construct must contain no statements or directives
5755 // outside of the teams construct.
5756 if (DSAStack->hasInnerTeamsRegion()) {
5757 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5758 bool OMPTeamsFound = true;
5759 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5760 auto I = CS->body_begin();
5761 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005762 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005763 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5764 OMPTeamsFound = false;
5765 break;
5766 }
5767 ++I;
5768 }
5769 assert(I != CS->body_end() && "Not found statement");
5770 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005771 } else {
5772 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5773 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005774 }
5775 if (!OMPTeamsFound) {
5776 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5777 Diag(DSAStack->getInnerTeamsRegionLoc(),
5778 diag::note_omp_nested_teams_construct_here);
5779 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5780 << isa<OMPExecutableDirective>(S);
5781 return StmtError();
5782 }
5783 }
5784
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005785 getCurFunction()->setHasBranchProtectedScope();
5786
5787 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5788}
5789
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005790StmtResult
5791Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5792 Stmt *AStmt, SourceLocation StartLoc,
5793 SourceLocation EndLoc) {
5794 if (!AStmt)
5795 return StmtError();
5796
5797 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5798 // 1.2.2 OpenMP Language Terminology
5799 // Structured block - An executable statement with a single entry at the
5800 // top and a single exit at the bottom.
5801 // The point of exit cannot be a branch out of the structured block.
5802 // longjmp() and throw() must not violate the entry/exit criteria.
5803 CS->getCapturedDecl()->setNothrow();
5804
5805 getCurFunction()->setHasBranchProtectedScope();
5806
5807 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5808 AStmt);
5809}
5810
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005811StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5812 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5813 SourceLocation EndLoc,
5814 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5815 if (!AStmt)
5816 return StmtError();
5817
5818 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5819 // 1.2.2 OpenMP Language Terminology
5820 // Structured block - An executable statement with a single entry at the
5821 // top and a single exit at the bottom.
5822 // The point of exit cannot be a branch out of the structured block.
5823 // longjmp() and throw() must not violate the entry/exit criteria.
5824 CS->getCapturedDecl()->setNothrow();
5825
5826 OMPLoopDirective::HelperExprs B;
5827 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5828 // define the nested loops number.
5829 unsigned NestedLoopCount =
5830 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5831 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5832 VarsWithImplicitDSA, B);
5833 if (NestedLoopCount == 0)
5834 return StmtError();
5835
5836 assert((CurContext->isDependentContext() || B.builtAll()) &&
5837 "omp target parallel for loop exprs were not built");
5838
5839 if (!CurContext->isDependentContext()) {
5840 // Finalize the clauses that need pre-built expressions for CodeGen.
5841 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005842 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005843 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005844 B.NumIterations, *this, CurScope,
5845 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005846 return StmtError();
5847 }
5848 }
5849
5850 getCurFunction()->setHasBranchProtectedScope();
5851 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5852 NestedLoopCount, Clauses, AStmt,
5853 B, DSAStack->isCancelRegion());
5854}
5855
Samuel Antaodf67fc42016-01-19 19:15:56 +00005856/// \brief Check for existence of a map clause in the list of clauses.
5857static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5858 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5859 I != E; ++I) {
5860 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5861 return true;
5862 }
5863 }
5864
5865 return false;
5866}
5867
Michael Wong65f367f2015-07-21 13:44:28 +00005868StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5869 Stmt *AStmt,
5870 SourceLocation StartLoc,
5871 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005872 if (!AStmt)
5873 return StmtError();
5874
5875 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5876
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005877 // OpenMP [2.10.1, Restrictions, p. 97]
5878 // At least one map clause must appear on the directive.
5879 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005880 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5881 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005882 return StmtError();
5883 }
5884
Michael Wong65f367f2015-07-21 13:44:28 +00005885 getCurFunction()->setHasBranchProtectedScope();
5886
5887 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5888 AStmt);
5889}
5890
Samuel Antaodf67fc42016-01-19 19:15:56 +00005891StmtResult
5892Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5893 SourceLocation StartLoc,
5894 SourceLocation EndLoc) {
5895 // OpenMP [2.10.2, Restrictions, p. 99]
5896 // At least one map clause must appear on the directive.
5897 if (!HasMapClause(Clauses)) {
5898 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5899 << getOpenMPDirectiveName(OMPD_target_enter_data);
5900 return StmtError();
5901 }
5902
5903 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5904 Clauses);
5905}
5906
Samuel Antao72590762016-01-19 20:04:50 +00005907StmtResult
5908Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5909 SourceLocation StartLoc,
5910 SourceLocation EndLoc) {
5911 // OpenMP [2.10.3, Restrictions, p. 102]
5912 // At least one map clause must appear on the directive.
5913 if (!HasMapClause(Clauses)) {
5914 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5915 << getOpenMPDirectiveName(OMPD_target_exit_data);
5916 return StmtError();
5917 }
5918
5919 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5920}
5921
Samuel Antao686c70c2016-05-26 17:30:50 +00005922StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5923 SourceLocation StartLoc,
5924 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005925 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005926 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005927 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005928 seenMotionClause = true;
5929 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005930 if (!seenMotionClause) {
5931 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5932 return StmtError();
5933 }
5934 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5935}
5936
Alexey Bataev13314bf2014-10-09 04:18:56 +00005937StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5938 Stmt *AStmt, SourceLocation StartLoc,
5939 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005940 if (!AStmt)
5941 return StmtError();
5942
Alexey Bataev13314bf2014-10-09 04:18:56 +00005943 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5944 // 1.2.2 OpenMP Language Terminology
5945 // Structured block - An executable statement with a single entry at the
5946 // top and a single exit at the bottom.
5947 // The point of exit cannot be a branch out of the structured block.
5948 // longjmp() and throw() must not violate the entry/exit criteria.
5949 CS->getCapturedDecl()->setNothrow();
5950
5951 getCurFunction()->setHasBranchProtectedScope();
5952
5953 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5954}
5955
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005956StmtResult
5957Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5958 SourceLocation EndLoc,
5959 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005960 if (DSAStack->isParentNowaitRegion()) {
5961 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5962 return StmtError();
5963 }
5964 if (DSAStack->isParentOrderedRegion()) {
5965 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5966 return StmtError();
5967 }
5968 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5969 CancelRegion);
5970}
5971
Alexey Bataev87933c72015-09-18 08:07:34 +00005972StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5973 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005974 SourceLocation EndLoc,
5975 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00005976 if (DSAStack->isParentNowaitRegion()) {
5977 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5978 return StmtError();
5979 }
5980 if (DSAStack->isParentOrderedRegion()) {
5981 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5982 return StmtError();
5983 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005984 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005985 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5986 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005987}
5988
Alexey Bataev382967a2015-12-08 12:06:20 +00005989static bool checkGrainsizeNumTasksClauses(Sema &S,
5990 ArrayRef<OMPClause *> Clauses) {
5991 OMPClause *PrevClause = nullptr;
5992 bool ErrorFound = false;
5993 for (auto *C : Clauses) {
5994 if (C->getClauseKind() == OMPC_grainsize ||
5995 C->getClauseKind() == OMPC_num_tasks) {
5996 if (!PrevClause)
5997 PrevClause = C;
5998 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5999 S.Diag(C->getLocStart(),
6000 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6001 << getOpenMPClauseName(C->getClauseKind())
6002 << getOpenMPClauseName(PrevClause->getClauseKind());
6003 S.Diag(PrevClause->getLocStart(),
6004 diag::note_omp_previous_grainsize_num_tasks)
6005 << getOpenMPClauseName(PrevClause->getClauseKind());
6006 ErrorFound = true;
6007 }
6008 }
6009 }
6010 return ErrorFound;
6011}
6012
Alexey Bataev49f6e782015-12-01 04:18:41 +00006013StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6014 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6015 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006016 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006017 if (!AStmt)
6018 return StmtError();
6019
6020 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6021 OMPLoopDirective::HelperExprs B;
6022 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6023 // define the nested loops number.
6024 unsigned NestedLoopCount =
6025 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006026 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006027 VarsWithImplicitDSA, B);
6028 if (NestedLoopCount == 0)
6029 return StmtError();
6030
6031 assert((CurContext->isDependentContext() || B.builtAll()) &&
6032 "omp for loop exprs were not built");
6033
Alexey Bataev382967a2015-12-08 12:06:20 +00006034 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6035 // The grainsize clause and num_tasks clause are mutually exclusive and may
6036 // not appear on the same taskloop directive.
6037 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6038 return StmtError();
6039
Alexey Bataev49f6e782015-12-01 04:18:41 +00006040 getCurFunction()->setHasBranchProtectedScope();
6041 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6042 NestedLoopCount, Clauses, AStmt, B);
6043}
6044
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006045StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6046 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6047 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006048 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006049 if (!AStmt)
6050 return StmtError();
6051
6052 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6053 OMPLoopDirective::HelperExprs B;
6054 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6055 // define the nested loops number.
6056 unsigned NestedLoopCount =
6057 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6058 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6059 VarsWithImplicitDSA, B);
6060 if (NestedLoopCount == 0)
6061 return StmtError();
6062
6063 assert((CurContext->isDependentContext() || B.builtAll()) &&
6064 "omp for loop exprs were not built");
6065
Alexey Bataev5a3af132016-03-29 08:58:54 +00006066 if (!CurContext->isDependentContext()) {
6067 // Finalize the clauses that need pre-built expressions for CodeGen.
6068 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006069 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006070 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006071 B.NumIterations, *this, CurScope,
6072 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006073 return StmtError();
6074 }
6075 }
6076
Alexey Bataev382967a2015-12-08 12:06:20 +00006077 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6078 // The grainsize clause and num_tasks clause are mutually exclusive and may
6079 // not appear on the same taskloop directive.
6080 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6081 return StmtError();
6082
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006083 getCurFunction()->setHasBranchProtectedScope();
6084 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6085 NestedLoopCount, Clauses, AStmt, B);
6086}
6087
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006088StmtResult Sema::ActOnOpenMPDistributeDirective(
6089 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6090 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006091 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006092 if (!AStmt)
6093 return StmtError();
6094
6095 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6096 OMPLoopDirective::HelperExprs B;
6097 // In presence of clause 'collapse' with number of loops, it will
6098 // define the nested loops number.
6099 unsigned NestedLoopCount =
6100 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6101 nullptr /*ordered not a clause on distribute*/, AStmt,
6102 *this, *DSAStack, VarsWithImplicitDSA, B);
6103 if (NestedLoopCount == 0)
6104 return StmtError();
6105
6106 assert((CurContext->isDependentContext() || B.builtAll()) &&
6107 "omp for loop exprs were not built");
6108
6109 getCurFunction()->setHasBranchProtectedScope();
6110 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6111 NestedLoopCount, Clauses, AStmt, B);
6112}
6113
Carlo Bertolli9925f152016-06-27 14:55:37 +00006114StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6115 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6116 SourceLocation EndLoc,
6117 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6118 if (!AStmt)
6119 return StmtError();
6120
6121 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6122 // 1.2.2 OpenMP Language Terminology
6123 // Structured block - An executable statement with a single entry at the
6124 // top and a single exit at the bottom.
6125 // The point of exit cannot be a branch out of the structured block.
6126 // longjmp() and throw() must not violate the entry/exit criteria.
6127 CS->getCapturedDecl()->setNothrow();
6128
6129 OMPLoopDirective::HelperExprs B;
6130 // In presence of clause 'collapse' with number of loops, it will
6131 // define the nested loops number.
6132 unsigned NestedLoopCount = CheckOpenMPLoop(
6133 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6134 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6135 VarsWithImplicitDSA, B);
6136 if (NestedLoopCount == 0)
6137 return StmtError();
6138
6139 assert((CurContext->isDependentContext() || B.builtAll()) &&
6140 "omp for loop exprs were not built");
6141
6142 getCurFunction()->setHasBranchProtectedScope();
6143 return OMPDistributeParallelForDirective::Create(
6144 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6145}
6146
Kelvin Li4a39add2016-07-05 05:00:15 +00006147StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6148 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6149 SourceLocation EndLoc,
6150 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6151 if (!AStmt)
6152 return StmtError();
6153
6154 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6155 // 1.2.2 OpenMP Language Terminology
6156 // Structured block - An executable statement with a single entry at the
6157 // top and a single exit at the bottom.
6158 // The point of exit cannot be a branch out of the structured block.
6159 // longjmp() and throw() must not violate the entry/exit criteria.
6160 CS->getCapturedDecl()->setNothrow();
6161
6162 OMPLoopDirective::HelperExprs B;
6163 // In presence of clause 'collapse' with number of loops, it will
6164 // define the nested loops number.
6165 unsigned NestedLoopCount = CheckOpenMPLoop(
6166 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6167 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6168 VarsWithImplicitDSA, B);
6169 if (NestedLoopCount == 0)
6170 return StmtError();
6171
6172 assert((CurContext->isDependentContext() || B.builtAll()) &&
6173 "omp for loop exprs were not built");
6174
Kelvin Lic5609492016-07-15 04:39:07 +00006175 if (checkSimdlenSafelenSpecified(*this, Clauses))
6176 return StmtError();
6177
Kelvin Li4a39add2016-07-05 05:00:15 +00006178 getCurFunction()->setHasBranchProtectedScope();
6179 return OMPDistributeParallelForSimdDirective::Create(
6180 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6181}
6182
Kelvin Li787f3fc2016-07-06 04:45:38 +00006183StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6184 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6185 SourceLocation EndLoc,
6186 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6187 if (!AStmt)
6188 return StmtError();
6189
6190 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6191 // 1.2.2 OpenMP Language Terminology
6192 // Structured block - An executable statement with a single entry at the
6193 // top and a single exit at the bottom.
6194 // The point of exit cannot be a branch out of the structured block.
6195 // longjmp() and throw() must not violate the entry/exit criteria.
6196 CS->getCapturedDecl()->setNothrow();
6197
6198 OMPLoopDirective::HelperExprs B;
6199 // In presence of clause 'collapse' with number of loops, it will
6200 // define the nested loops number.
6201 unsigned NestedLoopCount =
6202 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6203 nullptr /*ordered not a clause on distribute*/, AStmt,
6204 *this, *DSAStack, VarsWithImplicitDSA, B);
6205 if (NestedLoopCount == 0)
6206 return StmtError();
6207
6208 assert((CurContext->isDependentContext() || B.builtAll()) &&
6209 "omp for loop exprs were not built");
6210
Kelvin Lic5609492016-07-15 04:39:07 +00006211 if (checkSimdlenSafelenSpecified(*this, Clauses))
6212 return StmtError();
6213
Kelvin Li787f3fc2016-07-06 04:45:38 +00006214 getCurFunction()->setHasBranchProtectedScope();
6215 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6216 NestedLoopCount, Clauses, AStmt, B);
6217}
6218
Kelvin Lia579b912016-07-14 02:54:56 +00006219StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6220 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6221 SourceLocation EndLoc,
6222 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6223 if (!AStmt)
6224 return StmtError();
6225
6226 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6227 // 1.2.2 OpenMP Language Terminology
6228 // Structured block - An executable statement with a single entry at the
6229 // top and a single exit at the bottom.
6230 // The point of exit cannot be a branch out of the structured block.
6231 // longjmp() and throw() must not violate the entry/exit criteria.
6232 CS->getCapturedDecl()->setNothrow();
6233
6234 OMPLoopDirective::HelperExprs B;
6235 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6236 // define the nested loops number.
6237 unsigned NestedLoopCount = CheckOpenMPLoop(
6238 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6239 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6240 VarsWithImplicitDSA, B);
6241 if (NestedLoopCount == 0)
6242 return StmtError();
6243
6244 assert((CurContext->isDependentContext() || B.builtAll()) &&
6245 "omp target parallel for simd loop exprs were not built");
6246
6247 if (!CurContext->isDependentContext()) {
6248 // Finalize the clauses that need pre-built expressions for CodeGen.
6249 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006250 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006251 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6252 B.NumIterations, *this, CurScope,
6253 DSAStack))
6254 return StmtError();
6255 }
6256 }
Kelvin Lic5609492016-07-15 04:39:07 +00006257 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006258 return StmtError();
6259
6260 getCurFunction()->setHasBranchProtectedScope();
6261 return OMPTargetParallelForSimdDirective::Create(
6262 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6263}
6264
Kelvin Li986330c2016-07-20 22:57:10 +00006265StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6266 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6267 SourceLocation EndLoc,
6268 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6269 if (!AStmt)
6270 return StmtError();
6271
6272 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6273 // 1.2.2 OpenMP Language Terminology
6274 // Structured block - An executable statement with a single entry at the
6275 // top and a single exit at the bottom.
6276 // The point of exit cannot be a branch out of the structured block.
6277 // longjmp() and throw() must not violate the entry/exit criteria.
6278 CS->getCapturedDecl()->setNothrow();
6279
6280 OMPLoopDirective::HelperExprs B;
6281 // In presence of clause 'collapse' with number of loops, it will define the
6282 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006283 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006284 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6285 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6286 VarsWithImplicitDSA, B);
6287 if (NestedLoopCount == 0)
6288 return StmtError();
6289
6290 assert((CurContext->isDependentContext() || B.builtAll()) &&
6291 "omp target simd loop exprs were not built");
6292
6293 if (!CurContext->isDependentContext()) {
6294 // Finalize the clauses that need pre-built expressions for CodeGen.
6295 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006296 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006297 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6298 B.NumIterations, *this, CurScope,
6299 DSAStack))
6300 return StmtError();
6301 }
6302 }
6303
6304 if (checkSimdlenSafelenSpecified(*this, Clauses))
6305 return StmtError();
6306
6307 getCurFunction()->setHasBranchProtectedScope();
6308 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6309 NestedLoopCount, Clauses, AStmt, B);
6310}
6311
Kelvin Li02532872016-08-05 14:37:37 +00006312StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6313 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6314 SourceLocation EndLoc,
6315 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6316 if (!AStmt)
6317 return StmtError();
6318
6319 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6320 // 1.2.2 OpenMP Language Terminology
6321 // Structured block - An executable statement with a single entry at the
6322 // top and a single exit at the bottom.
6323 // The point of exit cannot be a branch out of the structured block.
6324 // longjmp() and throw() must not violate the entry/exit criteria.
6325 CS->getCapturedDecl()->setNothrow();
6326
6327 OMPLoopDirective::HelperExprs B;
6328 // In presence of clause 'collapse' with number of loops, it will
6329 // define the nested loops number.
6330 unsigned NestedLoopCount =
6331 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6332 nullptr /*ordered not a clause on distribute*/, AStmt,
6333 *this, *DSAStack, VarsWithImplicitDSA, B);
6334 if (NestedLoopCount == 0)
6335 return StmtError();
6336
6337 assert((CurContext->isDependentContext() || B.builtAll()) &&
6338 "omp teams distribute loop exprs were not built");
6339
6340 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006341 return OMPTeamsDistributeDirective::Create(
6342 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006343}
6344
Kelvin Li4e325f72016-10-25 12:50:55 +00006345StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6346 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6347 SourceLocation EndLoc,
6348 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6349 if (!AStmt)
6350 return StmtError();
6351
6352 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6353 // 1.2.2 OpenMP Language Terminology
6354 // Structured block - An executable statement with a single entry at the
6355 // top and a single exit at the bottom.
6356 // The point of exit cannot be a branch out of the structured block.
6357 // longjmp() and throw() must not violate the entry/exit criteria.
6358 CS->getCapturedDecl()->setNothrow();
6359
6360 OMPLoopDirective::HelperExprs B;
6361 // In presence of clause 'collapse' with number of loops, it will
6362 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006363 unsigned NestedLoopCount = CheckOpenMPLoop(
6364 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6365 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6366 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006367
6368 if (NestedLoopCount == 0)
6369 return StmtError();
6370
6371 assert((CurContext->isDependentContext() || B.builtAll()) &&
6372 "omp teams distribute simd loop exprs were not built");
6373
6374 if (!CurContext->isDependentContext()) {
6375 // Finalize the clauses that need pre-built expressions for CodeGen.
6376 for (auto C : Clauses) {
6377 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6378 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6379 B.NumIterations, *this, CurScope,
6380 DSAStack))
6381 return StmtError();
6382 }
6383 }
6384
6385 if (checkSimdlenSafelenSpecified(*this, Clauses))
6386 return StmtError();
6387
6388 getCurFunction()->setHasBranchProtectedScope();
6389 return OMPTeamsDistributeSimdDirective::Create(
6390 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6391}
6392
Kelvin Li579e41c2016-11-30 23:51:03 +00006393StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6395 SourceLocation EndLoc,
6396 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6397 if (!AStmt)
6398 return StmtError();
6399
6400 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6401 // 1.2.2 OpenMP Language Terminology
6402 // Structured block - An executable statement with a single entry at the
6403 // top and a single exit at the bottom.
6404 // The point of exit cannot be a branch out of the structured block.
6405 // longjmp() and throw() must not violate the entry/exit criteria.
6406 CS->getCapturedDecl()->setNothrow();
6407
6408 OMPLoopDirective::HelperExprs B;
6409 // In presence of clause 'collapse' with number of loops, it will
6410 // define the nested loops number.
6411 auto NestedLoopCount = CheckOpenMPLoop(
6412 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6413 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6414 VarsWithImplicitDSA, B);
6415
6416 if (NestedLoopCount == 0)
6417 return StmtError();
6418
6419 assert((CurContext->isDependentContext() || B.builtAll()) &&
6420 "omp for loop exprs were not built");
6421
6422 if (!CurContext->isDependentContext()) {
6423 // Finalize the clauses that need pre-built expressions for CodeGen.
6424 for (auto C : Clauses) {
6425 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6426 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6427 B.NumIterations, *this, CurScope,
6428 DSAStack))
6429 return StmtError();
6430 }
6431 }
6432
6433 if (checkSimdlenSafelenSpecified(*this, Clauses))
6434 return StmtError();
6435
6436 getCurFunction()->setHasBranchProtectedScope();
6437 return OMPTeamsDistributeParallelForSimdDirective::Create(
6438 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6439}
6440
Kelvin Li7ade93f2016-12-09 03:24:30 +00006441StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6442 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6443 SourceLocation EndLoc,
6444 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6445 if (!AStmt)
6446 return StmtError();
6447
6448 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6449 // 1.2.2 OpenMP Language Terminology
6450 // Structured block - An executable statement with a single entry at the
6451 // top and a single exit at the bottom.
6452 // The point of exit cannot be a branch out of the structured block.
6453 // longjmp() and throw() must not violate the entry/exit criteria.
6454 CS->getCapturedDecl()->setNothrow();
6455
6456 OMPLoopDirective::HelperExprs B;
6457 // In presence of clause 'collapse' with number of loops, it will
6458 // define the nested loops number.
6459 unsigned NestedLoopCount = CheckOpenMPLoop(
6460 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6461 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6462 VarsWithImplicitDSA, B);
6463
6464 if (NestedLoopCount == 0)
6465 return StmtError();
6466
6467 assert((CurContext->isDependentContext() || B.builtAll()) &&
6468 "omp for loop exprs were not built");
6469
6470 if (!CurContext->isDependentContext()) {
6471 // Finalize the clauses that need pre-built expressions for CodeGen.
6472 for (auto C : Clauses) {
6473 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6474 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6475 B.NumIterations, *this, CurScope,
6476 DSAStack))
6477 return StmtError();
6478 }
6479 }
6480
6481 getCurFunction()->setHasBranchProtectedScope();
6482 return OMPTeamsDistributeParallelForDirective::Create(
6483 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6484}
6485
Kelvin Libf594a52016-12-17 05:48:59 +00006486StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6487 Stmt *AStmt,
6488 SourceLocation StartLoc,
6489 SourceLocation EndLoc) {
6490 if (!AStmt)
6491 return StmtError();
6492
6493 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6494 // 1.2.2 OpenMP Language Terminology
6495 // Structured block - An executable statement with a single entry at the
6496 // top and a single exit at the bottom.
6497 // The point of exit cannot be a branch out of the structured block.
6498 // longjmp() and throw() must not violate the entry/exit criteria.
6499 CS->getCapturedDecl()->setNothrow();
6500
6501 getCurFunction()->setHasBranchProtectedScope();
6502
6503 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6504 AStmt);
6505}
6506
Kelvin Li83c451e2016-12-25 04:52:54 +00006507StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6508 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6509 SourceLocation EndLoc,
6510 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6511 if (!AStmt)
6512 return StmtError();
6513
6514 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6515 // 1.2.2 OpenMP Language Terminology
6516 // Structured block - An executable statement with a single entry at the
6517 // top and a single exit at the bottom.
6518 // The point of exit cannot be a branch out of the structured block.
6519 // longjmp() and throw() must not violate the entry/exit criteria.
6520 CS->getCapturedDecl()->setNothrow();
6521
6522 OMPLoopDirective::HelperExprs B;
6523 // In presence of clause 'collapse' with number of loops, it will
6524 // define the nested loops number.
6525 auto NestedLoopCount = CheckOpenMPLoop(
6526 OMPD_target_teams_distribute,
6527 getCollapseNumberExpr(Clauses),
6528 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6529 VarsWithImplicitDSA, B);
6530 if (NestedLoopCount == 0)
6531 return StmtError();
6532
6533 assert((CurContext->isDependentContext() || B.builtAll()) &&
6534 "omp target teams distribute loop exprs were not built");
6535
6536 getCurFunction()->setHasBranchProtectedScope();
6537 return OMPTargetTeamsDistributeDirective::Create(
6538 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6539}
6540
Kelvin Li80e8f562016-12-29 22:16:30 +00006541StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6542 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6543 SourceLocation EndLoc,
6544 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6545 if (!AStmt)
6546 return StmtError();
6547
6548 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6549 // 1.2.2 OpenMP Language Terminology
6550 // Structured block - An executable statement with a single entry at the
6551 // top and a single exit at the bottom.
6552 // The point of exit cannot be a branch out of the structured block.
6553 // longjmp() and throw() must not violate the entry/exit criteria.
6554 CS->getCapturedDecl()->setNothrow();
6555
6556 OMPLoopDirective::HelperExprs B;
6557 // In presence of clause 'collapse' with number of loops, it will
6558 // define the nested loops number.
6559 auto NestedLoopCount = CheckOpenMPLoop(
6560 OMPD_target_teams_distribute_parallel_for,
6561 getCollapseNumberExpr(Clauses),
6562 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6563 VarsWithImplicitDSA, B);
6564 if (NestedLoopCount == 0)
6565 return StmtError();
6566
6567 assert((CurContext->isDependentContext() || B.builtAll()) &&
6568 "omp target teams distribute parallel for loop exprs were not built");
6569
6570 if (!CurContext->isDependentContext()) {
6571 // Finalize the clauses that need pre-built expressions for CodeGen.
6572 for (auto C : Clauses) {
6573 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6574 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6575 B.NumIterations, *this, CurScope,
6576 DSAStack))
6577 return StmtError();
6578 }
6579 }
6580
6581 getCurFunction()->setHasBranchProtectedScope();
6582 return OMPTargetTeamsDistributeParallelForDirective::Create(
6583 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6584}
6585
Kelvin Li1851df52017-01-03 05:23:48 +00006586StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6588 SourceLocation EndLoc,
6589 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6590 if (!AStmt)
6591 return StmtError();
6592
6593 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6594 // 1.2.2 OpenMP Language Terminology
6595 // Structured block - An executable statement with a single entry at the
6596 // top and a single exit at the bottom.
6597 // The point of exit cannot be a branch out of the structured block.
6598 // longjmp() and throw() must not violate the entry/exit criteria.
6599 CS->getCapturedDecl()->setNothrow();
6600
6601 OMPLoopDirective::HelperExprs B;
6602 // In presence of clause 'collapse' with number of loops, it will
6603 // define the nested loops number.
6604 auto NestedLoopCount = CheckOpenMPLoop(
6605 OMPD_target_teams_distribute_parallel_for_simd,
6606 getCollapseNumberExpr(Clauses),
6607 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6608 VarsWithImplicitDSA, B);
6609 if (NestedLoopCount == 0)
6610 return StmtError();
6611
6612 assert((CurContext->isDependentContext() || B.builtAll()) &&
6613 "omp target teams distribute parallel for simd loop exprs were not "
6614 "built");
6615
6616 if (!CurContext->isDependentContext()) {
6617 // Finalize the clauses that need pre-built expressions for CodeGen.
6618 for (auto C : Clauses) {
6619 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6620 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6621 B.NumIterations, *this, CurScope,
6622 DSAStack))
6623 return StmtError();
6624 }
6625 }
6626
6627 getCurFunction()->setHasBranchProtectedScope();
6628 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6629 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6630}
6631
Kelvin Lida681182017-01-10 18:08:18 +00006632StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6633 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6634 SourceLocation EndLoc,
6635 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6636 if (!AStmt)
6637 return StmtError();
6638
6639 auto *CS = cast<CapturedStmt>(AStmt);
6640 // 1.2.2 OpenMP Language Terminology
6641 // Structured block - An executable statement with a single entry at the
6642 // top and a single exit at the bottom.
6643 // The point of exit cannot be a branch out of the structured block.
6644 // longjmp() and throw() must not violate the entry/exit criteria.
6645 CS->getCapturedDecl()->setNothrow();
6646
6647 OMPLoopDirective::HelperExprs B;
6648 // In presence of clause 'collapse' with number of loops, it will
6649 // define the nested loops number.
6650 auto NestedLoopCount = CheckOpenMPLoop(
6651 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6652 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6653 VarsWithImplicitDSA, B);
6654 if (NestedLoopCount == 0)
6655 return StmtError();
6656
6657 assert((CurContext->isDependentContext() || B.builtAll()) &&
6658 "omp target teams distribute simd loop exprs were not built");
6659
6660 getCurFunction()->setHasBranchProtectedScope();
6661 return OMPTargetTeamsDistributeSimdDirective::Create(
6662 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6663}
6664
Alexey Bataeved09d242014-05-28 05:53:51 +00006665OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006666 SourceLocation StartLoc,
6667 SourceLocation LParenLoc,
6668 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006669 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006670 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006671 case OMPC_final:
6672 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6673 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006674 case OMPC_num_threads:
6675 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6676 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006677 case OMPC_safelen:
6678 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6679 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006680 case OMPC_simdlen:
6681 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6682 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006683 case OMPC_collapse:
6684 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6685 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006686 case OMPC_ordered:
6687 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6688 break;
Michael Wonge710d542015-08-07 16:16:36 +00006689 case OMPC_device:
6690 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6691 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006692 case OMPC_num_teams:
6693 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6694 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006695 case OMPC_thread_limit:
6696 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6697 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006698 case OMPC_priority:
6699 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6700 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006701 case OMPC_grainsize:
6702 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6703 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006704 case OMPC_num_tasks:
6705 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6706 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006707 case OMPC_hint:
6708 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6709 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006710 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006711 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006712 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006713 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006714 case OMPC_private:
6715 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006716 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006717 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006718 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006719 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006720 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006721 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006722 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006723 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006724 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006725 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006726 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006727 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006728 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006729 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006730 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006731 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006732 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006733 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006734 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006735 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006736 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006737 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006738 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006739 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006740 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006741 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006742 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006743 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006744 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006745 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006746 llvm_unreachable("Clause is not allowed.");
6747 }
6748 return Res;
6749}
6750
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006751// An OpenMP directive such as 'target parallel' has two captured regions:
6752// for the 'target' and 'parallel' respectively. This function returns
6753// the region in which to capture expressions associated with a clause.
6754// A return value of OMPD_unknown signifies that the expression should not
6755// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006756static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6757 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6758 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006759 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6760
6761 switch (CKind) {
6762 case OMPC_if:
6763 switch (DKind) {
6764 case OMPD_target_parallel:
6765 // If this clause applies to the nested 'parallel' region, capture within
6766 // the 'target' region, otherwise do not capture.
6767 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6768 CaptureRegion = OMPD_target;
6769 break;
6770 case OMPD_cancel:
6771 case OMPD_parallel:
6772 case OMPD_parallel_sections:
6773 case OMPD_parallel_for:
6774 case OMPD_parallel_for_simd:
6775 case OMPD_target:
6776 case OMPD_target_simd:
6777 case OMPD_target_parallel_for:
6778 case OMPD_target_parallel_for_simd:
6779 case OMPD_target_teams:
6780 case OMPD_target_teams_distribute:
6781 case OMPD_target_teams_distribute_simd:
6782 case OMPD_target_teams_distribute_parallel_for:
6783 case OMPD_target_teams_distribute_parallel_for_simd:
6784 case OMPD_teams_distribute_parallel_for:
6785 case OMPD_teams_distribute_parallel_for_simd:
6786 case OMPD_distribute_parallel_for:
6787 case OMPD_distribute_parallel_for_simd:
6788 case OMPD_task:
6789 case OMPD_taskloop:
6790 case OMPD_taskloop_simd:
6791 case OMPD_target_data:
6792 case OMPD_target_enter_data:
6793 case OMPD_target_exit_data:
6794 case OMPD_target_update:
6795 // Do not capture if-clause expressions.
6796 break;
6797 case OMPD_threadprivate:
6798 case OMPD_taskyield:
6799 case OMPD_barrier:
6800 case OMPD_taskwait:
6801 case OMPD_cancellation_point:
6802 case OMPD_flush:
6803 case OMPD_declare_reduction:
6804 case OMPD_declare_simd:
6805 case OMPD_declare_target:
6806 case OMPD_end_declare_target:
6807 case OMPD_teams:
6808 case OMPD_simd:
6809 case OMPD_for:
6810 case OMPD_for_simd:
6811 case OMPD_sections:
6812 case OMPD_section:
6813 case OMPD_single:
6814 case OMPD_master:
6815 case OMPD_critical:
6816 case OMPD_taskgroup:
6817 case OMPD_distribute:
6818 case OMPD_ordered:
6819 case OMPD_atomic:
6820 case OMPD_distribute_simd:
6821 case OMPD_teams_distribute:
6822 case OMPD_teams_distribute_simd:
6823 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6824 case OMPD_unknown:
6825 llvm_unreachable("Unknown OpenMP directive");
6826 }
6827 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006828 case OMPC_num_threads:
6829 switch (DKind) {
6830 case OMPD_target_parallel:
6831 CaptureRegion = OMPD_target;
6832 break;
6833 case OMPD_cancel:
6834 case OMPD_parallel:
6835 case OMPD_parallel_sections:
6836 case OMPD_parallel_for:
6837 case OMPD_parallel_for_simd:
6838 case OMPD_target:
6839 case OMPD_target_simd:
6840 case OMPD_target_parallel_for:
6841 case OMPD_target_parallel_for_simd:
6842 case OMPD_target_teams:
6843 case OMPD_target_teams_distribute:
6844 case OMPD_target_teams_distribute_simd:
6845 case OMPD_target_teams_distribute_parallel_for:
6846 case OMPD_target_teams_distribute_parallel_for_simd:
6847 case OMPD_teams_distribute_parallel_for:
6848 case OMPD_teams_distribute_parallel_for_simd:
6849 case OMPD_distribute_parallel_for:
6850 case OMPD_distribute_parallel_for_simd:
6851 case OMPD_task:
6852 case OMPD_taskloop:
6853 case OMPD_taskloop_simd:
6854 case OMPD_target_data:
6855 case OMPD_target_enter_data:
6856 case OMPD_target_exit_data:
6857 case OMPD_target_update:
6858 // Do not capture num_threads-clause expressions.
6859 break;
6860 case OMPD_threadprivate:
6861 case OMPD_taskyield:
6862 case OMPD_barrier:
6863 case OMPD_taskwait:
6864 case OMPD_cancellation_point:
6865 case OMPD_flush:
6866 case OMPD_declare_reduction:
6867 case OMPD_declare_simd:
6868 case OMPD_declare_target:
6869 case OMPD_end_declare_target:
6870 case OMPD_teams:
6871 case OMPD_simd:
6872 case OMPD_for:
6873 case OMPD_for_simd:
6874 case OMPD_sections:
6875 case OMPD_section:
6876 case OMPD_single:
6877 case OMPD_master:
6878 case OMPD_critical:
6879 case OMPD_taskgroup:
6880 case OMPD_distribute:
6881 case OMPD_ordered:
6882 case OMPD_atomic:
6883 case OMPD_distribute_simd:
6884 case OMPD_teams_distribute:
6885 case OMPD_teams_distribute_simd:
6886 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6887 case OMPD_unknown:
6888 llvm_unreachable("Unknown OpenMP directive");
6889 }
6890 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00006891 case OMPC_num_teams:
6892 switch (DKind) {
6893 case OMPD_target_teams:
6894 CaptureRegion = OMPD_target;
6895 break;
6896 case OMPD_cancel:
6897 case OMPD_parallel:
6898 case OMPD_parallel_sections:
6899 case OMPD_parallel_for:
6900 case OMPD_parallel_for_simd:
6901 case OMPD_target:
6902 case OMPD_target_simd:
6903 case OMPD_target_parallel:
6904 case OMPD_target_parallel_for:
6905 case OMPD_target_parallel_for_simd:
6906 case OMPD_target_teams_distribute:
6907 case OMPD_target_teams_distribute_simd:
6908 case OMPD_target_teams_distribute_parallel_for:
6909 case OMPD_target_teams_distribute_parallel_for_simd:
6910 case OMPD_teams_distribute_parallel_for:
6911 case OMPD_teams_distribute_parallel_for_simd:
6912 case OMPD_distribute_parallel_for:
6913 case OMPD_distribute_parallel_for_simd:
6914 case OMPD_task:
6915 case OMPD_taskloop:
6916 case OMPD_taskloop_simd:
6917 case OMPD_target_data:
6918 case OMPD_target_enter_data:
6919 case OMPD_target_exit_data:
6920 case OMPD_target_update:
6921 case OMPD_teams:
6922 case OMPD_teams_distribute:
6923 case OMPD_teams_distribute_simd:
6924 // Do not capture num_teams-clause expressions.
6925 break;
6926 case OMPD_threadprivate:
6927 case OMPD_taskyield:
6928 case OMPD_barrier:
6929 case OMPD_taskwait:
6930 case OMPD_cancellation_point:
6931 case OMPD_flush:
6932 case OMPD_declare_reduction:
6933 case OMPD_declare_simd:
6934 case OMPD_declare_target:
6935 case OMPD_end_declare_target:
6936 case OMPD_simd:
6937 case OMPD_for:
6938 case OMPD_for_simd:
6939 case OMPD_sections:
6940 case OMPD_section:
6941 case OMPD_single:
6942 case OMPD_master:
6943 case OMPD_critical:
6944 case OMPD_taskgroup:
6945 case OMPD_distribute:
6946 case OMPD_ordered:
6947 case OMPD_atomic:
6948 case OMPD_distribute_simd:
6949 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
6950 case OMPD_unknown:
6951 llvm_unreachable("Unknown OpenMP directive");
6952 }
6953 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00006954 case OMPC_thread_limit:
6955 switch (DKind) {
6956 case OMPD_target_teams:
6957 CaptureRegion = OMPD_target;
6958 break;
6959 case OMPD_cancel:
6960 case OMPD_parallel:
6961 case OMPD_parallel_sections:
6962 case OMPD_parallel_for:
6963 case OMPD_parallel_for_simd:
6964 case OMPD_target:
6965 case OMPD_target_simd:
6966 case OMPD_target_parallel:
6967 case OMPD_target_parallel_for:
6968 case OMPD_target_parallel_for_simd:
6969 case OMPD_target_teams_distribute:
6970 case OMPD_target_teams_distribute_simd:
6971 case OMPD_target_teams_distribute_parallel_for:
6972 case OMPD_target_teams_distribute_parallel_for_simd:
6973 case OMPD_teams_distribute_parallel_for:
6974 case OMPD_teams_distribute_parallel_for_simd:
6975 case OMPD_distribute_parallel_for:
6976 case OMPD_distribute_parallel_for_simd:
6977 case OMPD_task:
6978 case OMPD_taskloop:
6979 case OMPD_taskloop_simd:
6980 case OMPD_target_data:
6981 case OMPD_target_enter_data:
6982 case OMPD_target_exit_data:
6983 case OMPD_target_update:
6984 case OMPD_teams:
6985 case OMPD_teams_distribute:
6986 case OMPD_teams_distribute_simd:
6987 // Do not capture thread_limit-clause expressions.
6988 break;
6989 case OMPD_threadprivate:
6990 case OMPD_taskyield:
6991 case OMPD_barrier:
6992 case OMPD_taskwait:
6993 case OMPD_cancellation_point:
6994 case OMPD_flush:
6995 case OMPD_declare_reduction:
6996 case OMPD_declare_simd:
6997 case OMPD_declare_target:
6998 case OMPD_end_declare_target:
6999 case OMPD_simd:
7000 case OMPD_for:
7001 case OMPD_for_simd:
7002 case OMPD_sections:
7003 case OMPD_section:
7004 case OMPD_single:
7005 case OMPD_master:
7006 case OMPD_critical:
7007 case OMPD_taskgroup:
7008 case OMPD_distribute:
7009 case OMPD_ordered:
7010 case OMPD_atomic:
7011 case OMPD_distribute_simd:
7012 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7013 case OMPD_unknown:
7014 llvm_unreachable("Unknown OpenMP directive");
7015 }
7016 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007017 case OMPC_schedule:
7018 case OMPC_dist_schedule:
7019 case OMPC_firstprivate:
7020 case OMPC_lastprivate:
7021 case OMPC_reduction:
7022 case OMPC_linear:
7023 case OMPC_default:
7024 case OMPC_proc_bind:
7025 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007026 case OMPC_safelen:
7027 case OMPC_simdlen:
7028 case OMPC_collapse:
7029 case OMPC_private:
7030 case OMPC_shared:
7031 case OMPC_aligned:
7032 case OMPC_copyin:
7033 case OMPC_copyprivate:
7034 case OMPC_ordered:
7035 case OMPC_nowait:
7036 case OMPC_untied:
7037 case OMPC_mergeable:
7038 case OMPC_threadprivate:
7039 case OMPC_flush:
7040 case OMPC_read:
7041 case OMPC_write:
7042 case OMPC_update:
7043 case OMPC_capture:
7044 case OMPC_seq_cst:
7045 case OMPC_depend:
7046 case OMPC_device:
7047 case OMPC_threads:
7048 case OMPC_simd:
7049 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007050 case OMPC_priority:
7051 case OMPC_grainsize:
7052 case OMPC_nogroup:
7053 case OMPC_num_tasks:
7054 case OMPC_hint:
7055 case OMPC_defaultmap:
7056 case OMPC_unknown:
7057 case OMPC_uniform:
7058 case OMPC_to:
7059 case OMPC_from:
7060 case OMPC_use_device_ptr:
7061 case OMPC_is_device_ptr:
7062 llvm_unreachable("Unexpected OpenMP clause.");
7063 }
7064 return CaptureRegion;
7065}
7066
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007067OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7068 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007069 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007070 SourceLocation NameModifierLoc,
7071 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007072 SourceLocation EndLoc) {
7073 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007074 Stmt *HelperValStmt = nullptr;
7075 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007076 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7077 !Condition->isInstantiationDependent() &&
7078 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007079 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007080 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007081 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007082
Richard Smith03a4aa32016-06-23 19:02:52 +00007083 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007084
7085 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7086 CaptureRegion =
7087 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7088 if (CaptureRegion != OMPD_unknown) {
7089 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7090 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7091 HelperValStmt = buildPreInits(Context, Captures);
7092 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007093 }
7094
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007095 return new (Context)
7096 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7097 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007098}
7099
Alexey Bataev3778b602014-07-17 07:32:53 +00007100OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7101 SourceLocation StartLoc,
7102 SourceLocation LParenLoc,
7103 SourceLocation EndLoc) {
7104 Expr *ValExpr = Condition;
7105 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7106 !Condition->isInstantiationDependent() &&
7107 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007108 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007109 if (Val.isInvalid())
7110 return nullptr;
7111
Richard Smith03a4aa32016-06-23 19:02:52 +00007112 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007113 }
7114
7115 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7116}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007117ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7118 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007119 if (!Op)
7120 return ExprError();
7121
7122 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7123 public:
7124 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007125 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007126 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7127 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007128 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7129 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007130 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7131 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007132 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7133 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007134 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7135 QualType T,
7136 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007137 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7138 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007139 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7140 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007141 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007142 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007143 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007144 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7145 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007146 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7147 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007148 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7149 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007150 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007151 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007152 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007153 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7154 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007155 llvm_unreachable("conversion functions are permitted");
7156 }
7157 } ConvertDiagnoser;
7158 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7159}
7160
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007161static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007162 OpenMPClauseKind CKind,
7163 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007164 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7165 !ValExpr->isInstantiationDependent()) {
7166 SourceLocation Loc = ValExpr->getExprLoc();
7167 ExprResult Value =
7168 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7169 if (Value.isInvalid())
7170 return false;
7171
7172 ValExpr = Value.get();
7173 // The expression must evaluate to a non-negative integer value.
7174 llvm::APSInt Result;
7175 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007176 Result.isSigned() &&
7177 !((!StrictlyPositive && Result.isNonNegative()) ||
7178 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007179 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007180 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7181 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007182 return false;
7183 }
7184 }
7185 return true;
7186}
7187
Alexey Bataev568a8332014-03-06 06:15:19 +00007188OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7189 SourceLocation StartLoc,
7190 SourceLocation LParenLoc,
7191 SourceLocation EndLoc) {
7192 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007193 Stmt *HelperValStmt = nullptr;
7194 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007195
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007196 // OpenMP [2.5, Restrictions]
7197 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007198 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7199 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007200 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007201
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007202 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7203 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7204 if (CaptureRegion != OMPD_unknown) {
7205 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7206 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7207 HelperValStmt = buildPreInits(Context, Captures);
7208 }
7209
7210 return new (Context) OMPNumThreadsClause(
7211 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007212}
7213
Alexey Bataev62c87d22014-03-21 04:51:18 +00007214ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007215 OpenMPClauseKind CKind,
7216 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007217 if (!E)
7218 return ExprError();
7219 if (E->isValueDependent() || E->isTypeDependent() ||
7220 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007221 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007222 llvm::APSInt Result;
7223 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7224 if (ICE.isInvalid())
7225 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007226 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7227 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007228 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007229 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7230 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007231 return ExprError();
7232 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007233 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7234 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7235 << E->getSourceRange();
7236 return ExprError();
7237 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007238 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7239 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007240 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007241 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007242 return ICE;
7243}
7244
7245OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7246 SourceLocation LParenLoc,
7247 SourceLocation EndLoc) {
7248 // OpenMP [2.8.1, simd construct, Description]
7249 // The parameter of the safelen clause must be a constant
7250 // positive integer expression.
7251 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7252 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007253 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007254 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007255 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007256}
7257
Alexey Bataev66b15b52015-08-21 11:14:16 +00007258OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7259 SourceLocation LParenLoc,
7260 SourceLocation EndLoc) {
7261 // OpenMP [2.8.1, simd construct, Description]
7262 // The parameter of the simdlen clause must be a constant
7263 // positive integer expression.
7264 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7265 if (Simdlen.isInvalid())
7266 return nullptr;
7267 return new (Context)
7268 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7269}
7270
Alexander Musman64d33f12014-06-04 07:53:32 +00007271OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7272 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007273 SourceLocation LParenLoc,
7274 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007275 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007276 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007277 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007278 // The parameter of the collapse clause must be a constant
7279 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007280 ExprResult NumForLoopsResult =
7281 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7282 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007283 return nullptr;
7284 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007285 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007286}
7287
Alexey Bataev10e775f2015-07-30 11:36:16 +00007288OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7289 SourceLocation EndLoc,
7290 SourceLocation LParenLoc,
7291 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007292 // OpenMP [2.7.1, loop construct, Description]
7293 // OpenMP [2.8.1, simd construct, Description]
7294 // OpenMP [2.9.6, distribute construct, Description]
7295 // The parameter of the ordered clause must be a constant
7296 // positive integer expression if any.
7297 if (NumForLoops && LParenLoc.isValid()) {
7298 ExprResult NumForLoopsResult =
7299 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7300 if (NumForLoopsResult.isInvalid())
7301 return nullptr;
7302 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007303 } else
7304 NumForLoops = nullptr;
7305 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007306 return new (Context)
7307 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7308}
7309
Alexey Bataeved09d242014-05-28 05:53:51 +00007310OMPClause *Sema::ActOnOpenMPSimpleClause(
7311 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7312 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007313 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007314 switch (Kind) {
7315 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007316 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007317 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7318 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007319 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007320 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007321 Res = ActOnOpenMPProcBindClause(
7322 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7323 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007324 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007325 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007326 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007327 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007328 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007329 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007330 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007331 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007332 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007333 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007334 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007335 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007336 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007337 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007338 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007339 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007340 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007341 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007342 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007343 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007344 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007345 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007346 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007347 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007348 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007349 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007350 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007351 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007352 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007353 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007354 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007355 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007356 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007357 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007358 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007359 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007360 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007361 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007362 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007363 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007364 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007365 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007366 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007367 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007368 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007369 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007370 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007371 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007372 llvm_unreachable("Clause is not allowed.");
7373 }
7374 return Res;
7375}
7376
Alexey Bataev6402bca2015-12-28 07:25:51 +00007377static std::string
7378getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7379 ArrayRef<unsigned> Exclude = llvm::None) {
7380 std::string Values;
7381 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7382 unsigned Skipped = Exclude.size();
7383 auto S = Exclude.begin(), E = Exclude.end();
7384 for (unsigned i = First; i < Last; ++i) {
7385 if (std::find(S, E, i) != E) {
7386 --Skipped;
7387 continue;
7388 }
7389 Values += "'";
7390 Values += getOpenMPSimpleClauseTypeName(K, i);
7391 Values += "'";
7392 if (i == Bound - Skipped)
7393 Values += " or ";
7394 else if (i != Bound + 1 - Skipped)
7395 Values += ", ";
7396 }
7397 return Values;
7398}
7399
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007400OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7401 SourceLocation KindKwLoc,
7402 SourceLocation StartLoc,
7403 SourceLocation LParenLoc,
7404 SourceLocation EndLoc) {
7405 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007406 static_assert(OMPC_DEFAULT_unknown > 0,
7407 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007408 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007409 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7410 /*Last=*/OMPC_DEFAULT_unknown)
7411 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007412 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007413 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007414 switch (Kind) {
7415 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007416 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007417 break;
7418 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007419 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007420 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007421 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007422 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007423 break;
7424 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007425 return new (Context)
7426 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007427}
7428
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007429OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7430 SourceLocation KindKwLoc,
7431 SourceLocation StartLoc,
7432 SourceLocation LParenLoc,
7433 SourceLocation EndLoc) {
7434 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007435 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007436 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7437 /*Last=*/OMPC_PROC_BIND_unknown)
7438 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007439 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007440 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007441 return new (Context)
7442 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007443}
7444
Alexey Bataev56dafe82014-06-20 07:16:17 +00007445OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007446 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007447 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007448 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007449 SourceLocation EndLoc) {
7450 OMPClause *Res = nullptr;
7451 switch (Kind) {
7452 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007453 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7454 assert(Argument.size() == NumberOfElements &&
7455 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007456 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007457 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7458 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7459 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7460 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7461 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007462 break;
7463 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007464 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7465 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7466 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7467 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007468 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007469 case OMPC_dist_schedule:
7470 Res = ActOnOpenMPDistScheduleClause(
7471 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7472 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7473 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007474 case OMPC_defaultmap:
7475 enum { Modifier, DefaultmapKind };
7476 Res = ActOnOpenMPDefaultmapClause(
7477 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7478 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007479 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7480 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007481 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007482 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007483 case OMPC_num_threads:
7484 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007485 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007486 case OMPC_collapse:
7487 case OMPC_default:
7488 case OMPC_proc_bind:
7489 case OMPC_private:
7490 case OMPC_firstprivate:
7491 case OMPC_lastprivate:
7492 case OMPC_shared:
7493 case OMPC_reduction:
7494 case OMPC_linear:
7495 case OMPC_aligned:
7496 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007497 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007498 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007499 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007500 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007501 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007502 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007503 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007504 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007505 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007506 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007507 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007508 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007509 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007510 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007511 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007512 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007513 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007514 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007515 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007516 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007517 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007518 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007519 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007520 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007521 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007522 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007523 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007524 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007525 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007526 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007527 llvm_unreachable("Clause is not allowed.");
7528 }
7529 return Res;
7530}
7531
Alexey Bataev6402bca2015-12-28 07:25:51 +00007532static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7533 OpenMPScheduleClauseModifier M2,
7534 SourceLocation M1Loc, SourceLocation M2Loc) {
7535 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7536 SmallVector<unsigned, 2> Excluded;
7537 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7538 Excluded.push_back(M2);
7539 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7540 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7541 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7542 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7543 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7544 << getListOfPossibleValues(OMPC_schedule,
7545 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7546 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7547 Excluded)
7548 << getOpenMPClauseName(OMPC_schedule);
7549 return true;
7550 }
7551 return false;
7552}
7553
Alexey Bataev56dafe82014-06-20 07:16:17 +00007554OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007555 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007556 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007557 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7558 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7559 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7560 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7561 return nullptr;
7562 // OpenMP, 2.7.1, Loop Construct, Restrictions
7563 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7564 // but not both.
7565 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7566 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7567 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7568 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7569 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7570 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7571 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7572 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7573 return nullptr;
7574 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007575 if (Kind == OMPC_SCHEDULE_unknown) {
7576 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007577 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7578 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7579 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7580 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7581 Exclude);
7582 } else {
7583 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7584 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007585 }
7586 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7587 << Values << getOpenMPClauseName(OMPC_schedule);
7588 return nullptr;
7589 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007590 // OpenMP, 2.7.1, Loop Construct, Restrictions
7591 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7592 // schedule(guided).
7593 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7594 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7595 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7596 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7597 diag::err_omp_schedule_nonmonotonic_static);
7598 return nullptr;
7599 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007600 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007601 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007602 if (ChunkSize) {
7603 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7604 !ChunkSize->isInstantiationDependent() &&
7605 !ChunkSize->containsUnexpandedParameterPack()) {
7606 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7607 ExprResult Val =
7608 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7609 if (Val.isInvalid())
7610 return nullptr;
7611
7612 ValExpr = Val.get();
7613
7614 // OpenMP [2.7.1, Restrictions]
7615 // chunk_size must be a loop invariant integer expression with a positive
7616 // value.
7617 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007618 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7619 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7620 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007621 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007622 return nullptr;
7623 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007624 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7625 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007626 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7627 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7628 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007629 }
7630 }
7631 }
7632
Alexey Bataev6402bca2015-12-28 07:25:51 +00007633 return new (Context)
7634 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007635 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007636}
7637
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007638OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7639 SourceLocation StartLoc,
7640 SourceLocation EndLoc) {
7641 OMPClause *Res = nullptr;
7642 switch (Kind) {
7643 case OMPC_ordered:
7644 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7645 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007646 case OMPC_nowait:
7647 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7648 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007649 case OMPC_untied:
7650 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7651 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007652 case OMPC_mergeable:
7653 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7654 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007655 case OMPC_read:
7656 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7657 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007658 case OMPC_write:
7659 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7660 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007661 case OMPC_update:
7662 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7663 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007664 case OMPC_capture:
7665 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7666 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007667 case OMPC_seq_cst:
7668 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7669 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007670 case OMPC_threads:
7671 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7672 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007673 case OMPC_simd:
7674 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7675 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007676 case OMPC_nogroup:
7677 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7678 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007679 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007680 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007681 case OMPC_num_threads:
7682 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007683 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007684 case OMPC_collapse:
7685 case OMPC_schedule:
7686 case OMPC_private:
7687 case OMPC_firstprivate:
7688 case OMPC_lastprivate:
7689 case OMPC_shared:
7690 case OMPC_reduction:
7691 case OMPC_linear:
7692 case OMPC_aligned:
7693 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007694 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007695 case OMPC_default:
7696 case OMPC_proc_bind:
7697 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007698 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007699 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007700 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007701 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007702 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007703 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007704 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007705 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007706 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007707 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007708 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007709 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007710 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007711 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007712 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007713 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007714 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007715 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007716 llvm_unreachable("Clause is not allowed.");
7717 }
7718 return Res;
7719}
7720
Alexey Bataev236070f2014-06-20 11:19:47 +00007721OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7722 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007723 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007724 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7725}
7726
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007727OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7728 SourceLocation EndLoc) {
7729 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7730}
7731
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007732OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7733 SourceLocation EndLoc) {
7734 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7735}
7736
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007737OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7738 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007739 return new (Context) OMPReadClause(StartLoc, EndLoc);
7740}
7741
Alexey Bataevdea47612014-07-23 07:46:59 +00007742OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7743 SourceLocation EndLoc) {
7744 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7745}
7746
Alexey Bataev67a4f222014-07-23 10:25:33 +00007747OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7748 SourceLocation EndLoc) {
7749 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7750}
7751
Alexey Bataev459dec02014-07-24 06:46:57 +00007752OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7753 SourceLocation EndLoc) {
7754 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7755}
7756
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007757OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7758 SourceLocation EndLoc) {
7759 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7760}
7761
Alexey Bataev346265e2015-09-25 10:37:12 +00007762OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7763 SourceLocation EndLoc) {
7764 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7765}
7766
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007767OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7768 SourceLocation EndLoc) {
7769 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7770}
7771
Alexey Bataevb825de12015-12-07 10:51:44 +00007772OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7773 SourceLocation EndLoc) {
7774 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7775}
7776
Alexey Bataevc5e02582014-06-16 07:08:35 +00007777OMPClause *Sema::ActOnOpenMPVarListClause(
7778 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7779 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7780 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007781 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007782 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7783 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7784 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007785 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007786 switch (Kind) {
7787 case OMPC_private:
7788 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7789 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007790 case OMPC_firstprivate:
7791 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7792 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007793 case OMPC_lastprivate:
7794 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7795 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007796 case OMPC_shared:
7797 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7798 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007799 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007800 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7801 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007802 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007803 case OMPC_linear:
7804 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007805 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007806 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007807 case OMPC_aligned:
7808 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7809 ColonLoc, EndLoc);
7810 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007811 case OMPC_copyin:
7812 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7813 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007814 case OMPC_copyprivate:
7815 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7816 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007817 case OMPC_flush:
7818 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7819 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007820 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007821 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007822 StartLoc, LParenLoc, EndLoc);
7823 break;
7824 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007825 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7826 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7827 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007828 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007829 case OMPC_to:
7830 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7831 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007832 case OMPC_from:
7833 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7834 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007835 case OMPC_use_device_ptr:
7836 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7837 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007838 case OMPC_is_device_ptr:
7839 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7840 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007841 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007842 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007843 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007844 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007845 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007846 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007847 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007848 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007849 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007850 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007851 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007852 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007853 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007854 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007855 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007856 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007857 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007858 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007859 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007860 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007861 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007862 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007863 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007864 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007865 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007866 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007867 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007868 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007869 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007870 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007871 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007872 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007873 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007874 llvm_unreachable("Clause is not allowed.");
7875 }
7876 return Res;
7877}
7878
Alexey Bataev90c228f2016-02-08 09:29:13 +00007879ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007880 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007881 ExprResult Res = BuildDeclRefExpr(
7882 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7883 if (!Res.isUsable())
7884 return ExprError();
7885 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7886 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7887 if (!Res.isUsable())
7888 return ExprError();
7889 }
7890 if (VK != VK_LValue && Res.get()->isGLValue()) {
7891 Res = DefaultLvalueConversion(Res.get());
7892 if (!Res.isUsable())
7893 return ExprError();
7894 }
7895 return Res;
7896}
7897
Alexey Bataev60da77e2016-02-29 05:54:20 +00007898static std::pair<ValueDecl *, bool>
7899getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7900 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007901 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7902 RefExpr->containsUnexpandedParameterPack())
7903 return std::make_pair(nullptr, true);
7904
Alexey Bataevd985eda2016-02-10 11:29:16 +00007905 // OpenMP [3.1, C/C++]
7906 // A list item is a variable name.
7907 // OpenMP [2.9.3.3, Restrictions, p.1]
7908 // A variable that is part of another variable (as an array or
7909 // structure element) cannot appear in a private clause.
7910 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007911 enum {
7912 NoArrayExpr = -1,
7913 ArraySubscript = 0,
7914 OMPArraySection = 1
7915 } IsArrayExpr = NoArrayExpr;
7916 if (AllowArraySection) {
7917 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7918 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7919 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7920 Base = TempASE->getBase()->IgnoreParenImpCasts();
7921 RefExpr = Base;
7922 IsArrayExpr = ArraySubscript;
7923 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7924 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7925 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7926 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7927 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7928 Base = TempASE->getBase()->IgnoreParenImpCasts();
7929 RefExpr = Base;
7930 IsArrayExpr = OMPArraySection;
7931 }
7932 }
7933 ELoc = RefExpr->getExprLoc();
7934 ERange = RefExpr->getSourceRange();
7935 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007936 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7937 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7938 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7939 (S.getCurrentThisType().isNull() || !ME ||
7940 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7941 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007942 if (IsArrayExpr != NoArrayExpr)
7943 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7944 << ERange;
7945 else {
7946 S.Diag(ELoc,
7947 AllowArraySection
7948 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7949 : diag::err_omp_expected_var_name_member_expr)
7950 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7951 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007952 return std::make_pair(nullptr, false);
7953 }
7954 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7955}
7956
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007957OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7958 SourceLocation StartLoc,
7959 SourceLocation LParenLoc,
7960 SourceLocation EndLoc) {
7961 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007962 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007963 for (auto &RefExpr : VarList) {
7964 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007965 SourceLocation ELoc;
7966 SourceRange ERange;
7967 Expr *SimpleRefExpr = RefExpr;
7968 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007969 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007970 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007971 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007972 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007973 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007974 ValueDecl *D = Res.first;
7975 if (!D)
7976 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007977
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007978 QualType Type = D->getType();
7979 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007980
7981 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7982 // A variable that appears in a private clause must not have an incomplete
7983 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007984 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007985 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007986 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007987
Alexey Bataev758e55e2013-09-06 18:03:48 +00007988 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7989 // in a Construct]
7990 // Variables with the predetermined data-sharing attributes may not be
7991 // listed in data-sharing attributes clauses, except for the cases
7992 // listed below. For these exceptions only, listing a predetermined
7993 // variable in a data-sharing attribute clause is allowed and overrides
7994 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007995 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007996 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007997 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7998 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007999 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008000 continue;
8001 }
8002
Kelvin Libf594a52016-12-17 05:48:59 +00008003 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008004 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008005 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008006 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008007 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8008 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008009 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008010 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008011 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008012 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008013 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008014 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008015 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008016 continue;
8017 }
8018
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008019 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8020 // A list item cannot appear in both a map clause and a data-sharing
8021 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008022 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008023 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008024 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008025 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008026 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008027 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008028 CurrDir == OMPD_target_parallel_for_simd ||
8029 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008030 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008031 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008032 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008033 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8034 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8035 ConflictKind = WhereFoundClauseKind;
8036 return true;
8037 })) {
8038 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008039 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008040 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008041 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008042 ReportOriginalDSA(*this, DSAStack, D, DVar);
8043 continue;
8044 }
8045 }
8046
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008047 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8048 // A variable of class type (or array thereof) that appears in a private
8049 // clause requires an accessible, unambiguous default constructor for the
8050 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008051 // Generate helper private variable and initialize it with the default
8052 // value. The address of the original variable is replaced by the address of
8053 // the new private variable in CodeGen. This new variable is not added to
8054 // IdResolver, so the code in the OpenMP region uses original variable for
8055 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008056 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008057 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8058 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008059 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008060 if (VDPrivate->isInvalidDecl())
8061 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008062 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008063 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008064
Alexey Bataev90c228f2016-02-08 09:29:13 +00008065 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008066 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008067 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008068 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008069 Vars.push_back((VD || CurContext->isDependentContext())
8070 ? RefExpr->IgnoreParens()
8071 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008072 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008073 }
8074
Alexey Bataeved09d242014-05-28 05:53:51 +00008075 if (Vars.empty())
8076 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008077
Alexey Bataev03b340a2014-10-21 03:16:40 +00008078 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8079 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008080}
8081
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008082namespace {
8083class DiagsUninitializedSeveretyRAII {
8084private:
8085 DiagnosticsEngine &Diags;
8086 SourceLocation SavedLoc;
8087 bool IsIgnored;
8088
8089public:
8090 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8091 bool IsIgnored)
8092 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8093 if (!IsIgnored) {
8094 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8095 /*Map*/ diag::Severity::Ignored, Loc);
8096 }
8097 }
8098 ~DiagsUninitializedSeveretyRAII() {
8099 if (!IsIgnored)
8100 Diags.popMappings(SavedLoc);
8101 }
8102};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008103}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008104
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008105OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8106 SourceLocation StartLoc,
8107 SourceLocation LParenLoc,
8108 SourceLocation EndLoc) {
8109 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008110 SmallVector<Expr *, 8> PrivateCopies;
8111 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008112 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008113 bool IsImplicitClause =
8114 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8115 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8116
Alexey Bataeved09d242014-05-28 05:53:51 +00008117 for (auto &RefExpr : VarList) {
8118 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008119 SourceLocation ELoc;
8120 SourceRange ERange;
8121 Expr *SimpleRefExpr = RefExpr;
8122 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008123 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008124 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008125 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008126 PrivateCopies.push_back(nullptr);
8127 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008128 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008129 ValueDecl *D = Res.first;
8130 if (!D)
8131 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008132
Alexey Bataev60da77e2016-02-29 05:54:20 +00008133 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008134 QualType Type = D->getType();
8135 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008136
8137 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8138 // A variable that appears in a private clause must not have an incomplete
8139 // type or a reference type.
8140 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008141 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008142 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008143 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008144
8145 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8146 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008147 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008148 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008149 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008150
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008151 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008152 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008153 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008154 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008155 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008156 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008157 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8158 // A list item that specifies a given variable may not appear in more
8159 // than one clause on the same directive, except that a variable may be
8160 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008161 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00008162 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008163 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008164 << getOpenMPClauseName(DVar.CKind)
8165 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008166 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008167 continue;
8168 }
8169
8170 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8171 // in a Construct]
8172 // Variables with the predetermined data-sharing attributes may not be
8173 // listed in data-sharing attributes clauses, except for the cases
8174 // listed below. For these exceptions only, listing a predetermined
8175 // variable in a data-sharing attribute clause is allowed and overrides
8176 // the variable's predetermined data-sharing attributes.
8177 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8178 // in a Construct, C/C++, p.2]
8179 // Variables with const-qualified type having no mutable member may be
8180 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008181 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008182 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8183 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008184 << getOpenMPClauseName(DVar.CKind)
8185 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008186 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008187 continue;
8188 }
8189
Alexey Bataevf29276e2014-06-18 04:14:57 +00008190 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008191 // OpenMP [2.9.3.4, Restrictions, p.2]
8192 // A list item that is private within a parallel region must not appear
8193 // in a firstprivate clause on a worksharing construct if any of the
8194 // worksharing regions arising from the worksharing construct ever bind
8195 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008196 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008197 !isOpenMPParallelDirective(CurrDir) &&
8198 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008199 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008200 if (DVar.CKind != OMPC_shared &&
8201 (isOpenMPParallelDirective(DVar.DKind) ||
8202 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008203 Diag(ELoc, diag::err_omp_required_access)
8204 << getOpenMPClauseName(OMPC_firstprivate)
8205 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008206 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008207 continue;
8208 }
8209 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008210 // OpenMP [2.9.3.4, Restrictions, p.3]
8211 // A list item that appears in a reduction clause of a parallel construct
8212 // must not appear in a firstprivate clause on a worksharing or task
8213 // construct if any of the worksharing or task regions arising from the
8214 // worksharing or task construct ever bind to any of the parallel regions
8215 // arising from the parallel construct.
8216 // OpenMP [2.9.3.4, Restrictions, p.4]
8217 // A list item that appears in a reduction clause in worksharing
8218 // construct must not appear in a firstprivate clause in a task construct
8219 // encountered during execution of any of the worksharing regions arising
8220 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008221 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008222 DVar = DSAStack->hasInnermostDSA(
8223 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8224 [](OpenMPDirectiveKind K) -> bool {
8225 return isOpenMPParallelDirective(K) ||
8226 isOpenMPWorksharingDirective(K);
8227 },
8228 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008229 if (DVar.CKind == OMPC_reduction &&
8230 (isOpenMPParallelDirective(DVar.DKind) ||
8231 isOpenMPWorksharingDirective(DVar.DKind))) {
8232 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8233 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008234 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008235 continue;
8236 }
8237 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008238
8239 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8240 // A list item that is private within a teams region must not appear in a
8241 // firstprivate clause on a distribute construct if any of the distribute
8242 // regions arising from the distribute construct ever bind to any of the
8243 // teams regions arising from the teams construct.
8244 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8245 // A list item that appears in a reduction clause of a teams construct
8246 // must not appear in a firstprivate clause on a distribute construct if
8247 // any of the distribute regions arising from the distribute construct
8248 // ever bind to any of the teams regions arising from the teams construct.
8249 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8250 // A list item may appear in a firstprivate or lastprivate clause but not
8251 // both.
8252 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008253 DVar = DSAStack->hasInnermostDSA(
8254 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8255 [](OpenMPDirectiveKind K) -> bool {
8256 return isOpenMPTeamsDirective(K);
8257 },
8258 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008259 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8260 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008261 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008262 continue;
8263 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008264 DVar = DSAStack->hasInnermostDSA(
8265 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8266 [](OpenMPDirectiveKind K) -> bool {
8267 return isOpenMPTeamsDirective(K);
8268 },
8269 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008270 if (DVar.CKind == OMPC_reduction &&
8271 isOpenMPTeamsDirective(DVar.DKind)) {
8272 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008273 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008274 continue;
8275 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008276 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008277 if (DVar.CKind == OMPC_lastprivate) {
8278 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008279 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008280 continue;
8281 }
8282 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008283 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8284 // A list item cannot appear in both a map clause and a data-sharing
8285 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008286 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008287 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008288 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008289 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008290 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008291 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008292 CurrDir == OMPD_target_parallel_for_simd ||
8293 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008294 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008295 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008296 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008297 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8298 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8299 ConflictKind = WhereFoundClauseKind;
8300 return true;
8301 })) {
8302 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008303 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008304 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008305 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8306 ReportOriginalDSA(*this, DSAStack, D, DVar);
8307 continue;
8308 }
8309 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008310 }
8311
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008312 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008313 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008314 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008315 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8316 << getOpenMPClauseName(OMPC_firstprivate) << Type
8317 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8318 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008319 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008320 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008321 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008322 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008323 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008324 continue;
8325 }
8326
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008327 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008328 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8329 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008330 // Generate helper private variable and initialize it with the value of the
8331 // original variable. The address of the original variable is replaced by
8332 // the address of the new private variable in the CodeGen. This new variable
8333 // is not added to IdResolver, so the code in the OpenMP region uses
8334 // original variable for proper diagnostics and variable capturing.
8335 Expr *VDInitRefExpr = nullptr;
8336 // For arrays generate initializer for single element and replace it by the
8337 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008338 if (Type->isArrayType()) {
8339 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008340 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008341 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008342 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008343 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008344 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008345 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008346 InitializedEntity Entity =
8347 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008348 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8349
8350 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8351 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8352 if (Result.isInvalid())
8353 VDPrivate->setInvalidDecl();
8354 else
8355 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008356 // Remove temp variable declaration.
8357 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008358 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008359 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8360 ".firstprivate.temp");
8361 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8362 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008363 AddInitializerToDecl(VDPrivate,
8364 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008365 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008366 }
8367 if (VDPrivate->isInvalidDecl()) {
8368 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008369 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008370 diag::note_omp_task_predetermined_firstprivate_here);
8371 }
8372 continue;
8373 }
8374 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008375 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008376 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8377 RefExpr->getExprLoc());
8378 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008379 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008380 if (TopDVar.CKind == OMPC_lastprivate)
8381 Ref = TopDVar.PrivateCopy;
8382 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008383 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008384 if (!IsOpenMPCapturedDecl(D))
8385 ExprCaptures.push_back(Ref->getDecl());
8386 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008387 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008388 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008389 Vars.push_back((VD || CurContext->isDependentContext())
8390 ? RefExpr->IgnoreParens()
8391 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008392 PrivateCopies.push_back(VDPrivateRefExpr);
8393 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008394 }
8395
Alexey Bataeved09d242014-05-28 05:53:51 +00008396 if (Vars.empty())
8397 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008398
8399 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008400 Vars, PrivateCopies, Inits,
8401 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008402}
8403
Alexander Musman1bb328c2014-06-04 13:06:39 +00008404OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8405 SourceLocation StartLoc,
8406 SourceLocation LParenLoc,
8407 SourceLocation EndLoc) {
8408 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008409 SmallVector<Expr *, 8> SrcExprs;
8410 SmallVector<Expr *, 8> DstExprs;
8411 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008412 SmallVector<Decl *, 4> ExprCaptures;
8413 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008414 for (auto &RefExpr : VarList) {
8415 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008416 SourceLocation ELoc;
8417 SourceRange ERange;
8418 Expr *SimpleRefExpr = RefExpr;
8419 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008420 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008421 // It will be analyzed later.
8422 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008423 SrcExprs.push_back(nullptr);
8424 DstExprs.push_back(nullptr);
8425 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008426 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008427 ValueDecl *D = Res.first;
8428 if (!D)
8429 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008430
Alexey Bataev74caaf22016-02-20 04:09:36 +00008431 QualType Type = D->getType();
8432 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008433
8434 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8435 // A variable that appears in a lastprivate clause must not have an
8436 // incomplete type or a reference type.
8437 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008438 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008439 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008440 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008441
8442 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8443 // in a Construct]
8444 // Variables with the predetermined data-sharing attributes may not be
8445 // listed in data-sharing attributes clauses, except for the cases
8446 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008447 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008448 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8449 DVar.CKind != OMPC_firstprivate &&
8450 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8451 Diag(ELoc, diag::err_omp_wrong_dsa)
8452 << getOpenMPClauseName(DVar.CKind)
8453 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008454 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008455 continue;
8456 }
8457
Alexey Bataevf29276e2014-06-18 04:14:57 +00008458 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8459 // OpenMP [2.14.3.5, Restrictions, p.2]
8460 // A list item that is private within a parallel region, or that appears in
8461 // the reduction clause of a parallel construct, must not appear in a
8462 // lastprivate clause on a worksharing construct if any of the corresponding
8463 // worksharing regions ever binds to any of the corresponding parallel
8464 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008465 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008466 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008467 !isOpenMPParallelDirective(CurrDir) &&
8468 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008469 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008470 if (DVar.CKind != OMPC_shared) {
8471 Diag(ELoc, diag::err_omp_required_access)
8472 << getOpenMPClauseName(OMPC_lastprivate)
8473 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008474 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008475 continue;
8476 }
8477 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008478
8479 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8480 // A list item may appear in a firstprivate or lastprivate clause but not
8481 // both.
8482 if (CurrDir == OMPD_distribute) {
8483 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8484 if (DVar.CKind == OMPC_firstprivate) {
8485 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8486 ReportOriginalDSA(*this, DSAStack, D, DVar);
8487 continue;
8488 }
8489 }
8490
Alexander Musman1bb328c2014-06-04 13:06:39 +00008491 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008492 // A variable of class type (or array thereof) that appears in a
8493 // lastprivate clause requires an accessible, unambiguous default
8494 // constructor for the class type, unless the list item is also specified
8495 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008496 // A variable of class type (or array thereof) that appears in a
8497 // lastprivate clause requires an accessible, unambiguous copy assignment
8498 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008499 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008500 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008501 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008502 D->hasAttrs() ? &D->getAttrs() : nullptr);
8503 auto *PseudoSrcExpr =
8504 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008505 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008506 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008507 D->hasAttrs() ? &D->getAttrs() : nullptr);
8508 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008509 // For arrays generate assignment operation for single element and replace
8510 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008511 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008512 PseudoDstExpr, PseudoSrcExpr);
8513 if (AssignmentOp.isInvalid())
8514 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008515 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008516 /*DiscardedValue=*/true);
8517 if (AssignmentOp.isInvalid())
8518 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008519
Alexey Bataev74caaf22016-02-20 04:09:36 +00008520 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008521 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008522 if (TopDVar.CKind == OMPC_firstprivate)
8523 Ref = TopDVar.PrivateCopy;
8524 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008525 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008526 if (!IsOpenMPCapturedDecl(D))
8527 ExprCaptures.push_back(Ref->getDecl());
8528 }
8529 if (TopDVar.CKind == OMPC_firstprivate ||
8530 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008531 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008532 ExprResult RefRes = DefaultLvalueConversion(Ref);
8533 if (!RefRes.isUsable())
8534 continue;
8535 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008536 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8537 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008538 if (!PostUpdateRes.isUsable())
8539 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008540 ExprPostUpdates.push_back(
8541 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008542 }
8543 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008544 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008545 Vars.push_back((VD || CurContext->isDependentContext())
8546 ? RefExpr->IgnoreParens()
8547 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008548 SrcExprs.push_back(PseudoSrcExpr);
8549 DstExprs.push_back(PseudoDstExpr);
8550 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008551 }
8552
8553 if (Vars.empty())
8554 return nullptr;
8555
8556 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008557 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008558 buildPreInits(Context, ExprCaptures),
8559 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008560}
8561
Alexey Bataev758e55e2013-09-06 18:03:48 +00008562OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8563 SourceLocation StartLoc,
8564 SourceLocation LParenLoc,
8565 SourceLocation EndLoc) {
8566 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008567 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008568 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008569 SourceLocation ELoc;
8570 SourceRange ERange;
8571 Expr *SimpleRefExpr = RefExpr;
8572 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008573 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008574 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008575 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008576 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008577 ValueDecl *D = Res.first;
8578 if (!D)
8579 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008580
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008581 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008582 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8583 // in a Construct]
8584 // Variables with the predetermined data-sharing attributes may not be
8585 // listed in data-sharing attributes clauses, except for the cases
8586 // listed below. For these exceptions only, listing a predetermined
8587 // variable in a data-sharing attribute clause is allowed and overrides
8588 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008589 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008590 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8591 DVar.RefExpr) {
8592 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8593 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008594 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008595 continue;
8596 }
8597
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008598 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008599 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008600 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008601 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008602 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8603 ? RefExpr->IgnoreParens()
8604 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008605 }
8606
Alexey Bataeved09d242014-05-28 05:53:51 +00008607 if (Vars.empty())
8608 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008609
8610 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8611}
8612
Alexey Bataevc5e02582014-06-16 07:08:35 +00008613namespace {
8614class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8615 DSAStackTy *Stack;
8616
8617public:
8618 bool VisitDeclRefExpr(DeclRefExpr *E) {
8619 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008620 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008621 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8622 return false;
8623 if (DVar.CKind != OMPC_unknown)
8624 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008625 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8626 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8627 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008628 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008629 return true;
8630 return false;
8631 }
8632 return false;
8633 }
8634 bool VisitStmt(Stmt *S) {
8635 for (auto Child : S->children()) {
8636 if (Child && Visit(Child))
8637 return true;
8638 }
8639 return false;
8640 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008641 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008642};
Alexey Bataev23b69422014-06-18 07:08:49 +00008643} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008644
Alexey Bataev60da77e2016-02-29 05:54:20 +00008645namespace {
8646// Transform MemberExpression for specified FieldDecl of current class to
8647// DeclRefExpr to specified OMPCapturedExprDecl.
8648class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8649 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8650 ValueDecl *Field;
8651 DeclRefExpr *CapturedExpr;
8652
8653public:
8654 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8655 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8656
8657 ExprResult TransformMemberExpr(MemberExpr *E) {
8658 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8659 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008660 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008661 return CapturedExpr;
8662 }
8663 return BaseTransform::TransformMemberExpr(E);
8664 }
8665 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8666};
8667} // namespace
8668
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008669template <typename T>
8670static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8671 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8672 for (auto &Set : Lookups) {
8673 for (auto *D : Set) {
8674 if (auto Res = Gen(cast<ValueDecl>(D)))
8675 return Res;
8676 }
8677 }
8678 return T();
8679}
8680
8681static ExprResult
8682buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8683 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8684 const DeclarationNameInfo &ReductionId, QualType Ty,
8685 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8686 if (ReductionIdScopeSpec.isInvalid())
8687 return ExprError();
8688 SmallVector<UnresolvedSet<8>, 4> Lookups;
8689 if (S) {
8690 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8691 Lookup.suppressDiagnostics();
8692 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8693 auto *D = Lookup.getRepresentativeDecl();
8694 do {
8695 S = S->getParent();
8696 } while (S && !S->isDeclScope(D));
8697 if (S)
8698 S = S->getParent();
8699 Lookups.push_back(UnresolvedSet<8>());
8700 Lookups.back().append(Lookup.begin(), Lookup.end());
8701 Lookup.clear();
8702 }
8703 } else if (auto *ULE =
8704 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8705 Lookups.push_back(UnresolvedSet<8>());
8706 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008707 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008708 if (D == PrevD)
8709 Lookups.push_back(UnresolvedSet<8>());
8710 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8711 Lookups.back().addDecl(DRD);
8712 PrevD = D;
8713 }
8714 }
8715 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8716 Ty->containsUnexpandedParameterPack() ||
8717 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8718 return !D->isInvalidDecl() &&
8719 (D->getType()->isDependentType() ||
8720 D->getType()->isInstantiationDependentType() ||
8721 D->getType()->containsUnexpandedParameterPack());
8722 })) {
8723 UnresolvedSet<8> ResSet;
8724 for (auto &Set : Lookups) {
8725 ResSet.append(Set.begin(), Set.end());
8726 // The last item marks the end of all declarations at the specified scope.
8727 ResSet.addDecl(Set[Set.size() - 1]);
8728 }
8729 return UnresolvedLookupExpr::Create(
8730 SemaRef.Context, /*NamingClass=*/nullptr,
8731 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8732 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8733 }
8734 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8735 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8736 if (!D->isInvalidDecl() &&
8737 SemaRef.Context.hasSameType(D->getType(), Ty))
8738 return D;
8739 return nullptr;
8740 }))
8741 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8742 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8743 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8744 if (!D->isInvalidDecl() &&
8745 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8746 !Ty.isMoreQualifiedThan(D->getType()))
8747 return D;
8748 return nullptr;
8749 })) {
8750 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8751 /*DetectVirtual=*/false);
8752 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8753 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8754 VD->getType().getUnqualifiedType()))) {
8755 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8756 /*DiagID=*/0) !=
8757 Sema::AR_inaccessible) {
8758 SemaRef.BuildBasePathArray(Paths, BasePath);
8759 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8760 }
8761 }
8762 }
8763 }
8764 if (ReductionIdScopeSpec.isSet()) {
8765 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8766 return ExprError();
8767 }
8768 return ExprEmpty();
8769}
8770
Alexey Bataevc5e02582014-06-16 07:08:35 +00008771OMPClause *Sema::ActOnOpenMPReductionClause(
8772 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8773 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008774 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8775 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008776 auto DN = ReductionId.getName();
8777 auto OOK = DN.getCXXOverloadedOperator();
8778 BinaryOperatorKind BOK = BO_Comma;
8779
8780 // OpenMP [2.14.3.6, reduction clause]
8781 // C
8782 // reduction-identifier is either an identifier or one of the following
8783 // operators: +, -, *, &, |, ^, && and ||
8784 // C++
8785 // reduction-identifier is either an id-expression or one of the following
8786 // operators: +, -, *, &, |, ^, && and ||
8787 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8788 switch (OOK) {
8789 case OO_Plus:
8790 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008791 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008792 break;
8793 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008794 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008795 break;
8796 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008797 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008798 break;
8799 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008800 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008801 break;
8802 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008803 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008804 break;
8805 case OO_AmpAmp:
8806 BOK = BO_LAnd;
8807 break;
8808 case OO_PipePipe:
8809 BOK = BO_LOr;
8810 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008811 case OO_New:
8812 case OO_Delete:
8813 case OO_Array_New:
8814 case OO_Array_Delete:
8815 case OO_Slash:
8816 case OO_Percent:
8817 case OO_Tilde:
8818 case OO_Exclaim:
8819 case OO_Equal:
8820 case OO_Less:
8821 case OO_Greater:
8822 case OO_LessEqual:
8823 case OO_GreaterEqual:
8824 case OO_PlusEqual:
8825 case OO_MinusEqual:
8826 case OO_StarEqual:
8827 case OO_SlashEqual:
8828 case OO_PercentEqual:
8829 case OO_CaretEqual:
8830 case OO_AmpEqual:
8831 case OO_PipeEqual:
8832 case OO_LessLess:
8833 case OO_GreaterGreater:
8834 case OO_LessLessEqual:
8835 case OO_GreaterGreaterEqual:
8836 case OO_EqualEqual:
8837 case OO_ExclaimEqual:
8838 case OO_PlusPlus:
8839 case OO_MinusMinus:
8840 case OO_Comma:
8841 case OO_ArrowStar:
8842 case OO_Arrow:
8843 case OO_Call:
8844 case OO_Subscript:
8845 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008846 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008847 case NUM_OVERLOADED_OPERATORS:
8848 llvm_unreachable("Unexpected reduction identifier");
8849 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008850 if (auto II = DN.getAsIdentifierInfo()) {
8851 if (II->isStr("max"))
8852 BOK = BO_GT;
8853 else if (II->isStr("min"))
8854 BOK = BO_LT;
8855 }
8856 break;
8857 }
8858 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008859 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008860 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008861 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008862
8863 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008864 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008865 SmallVector<Expr *, 8> LHSs;
8866 SmallVector<Expr *, 8> RHSs;
8867 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008868 SmallVector<Decl *, 4> ExprCaptures;
8869 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008870 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8871 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008872 for (auto RefExpr : VarList) {
8873 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008874 // OpenMP [2.1, C/C++]
8875 // A list item is a variable or array section, subject to the restrictions
8876 // specified in Section 2.4 on page 42 and in each of the sections
8877 // describing clauses and directives for which a list appears.
8878 // OpenMP [2.14.3.3, Restrictions, p.1]
8879 // A variable that is part of another variable (as an array or
8880 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008881 if (!FirstIter && IR != ER)
8882 ++IR;
8883 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008884 SourceLocation ELoc;
8885 SourceRange ERange;
8886 Expr *SimpleRefExpr = RefExpr;
8887 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8888 /*AllowArraySection=*/true);
8889 if (Res.second) {
8890 // It will be analyzed later.
8891 Vars.push_back(RefExpr);
8892 Privates.push_back(nullptr);
8893 LHSs.push_back(nullptr);
8894 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008895 // Try to find 'declare reduction' corresponding construct before using
8896 // builtin/overloaded operators.
8897 QualType Type = Context.DependentTy;
8898 CXXCastPath BasePath;
8899 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8900 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8901 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8902 if (CurContext->isDependentContext() &&
8903 (DeclareReductionRef.isUnset() ||
8904 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8905 ReductionOps.push_back(DeclareReductionRef.get());
8906 else
8907 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008908 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008909 ValueDecl *D = Res.first;
8910 if (!D)
8911 continue;
8912
Alexey Bataeva1764212015-09-30 09:22:36 +00008913 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008914 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8915 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8916 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008917 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008918 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008919 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8920 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8921 Type = ATy->getElementType();
8922 else
8923 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008924 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008925 } else
8926 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8927 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008928
Alexey Bataevc5e02582014-06-16 07:08:35 +00008929 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8930 // A variable that appears in a private clause must not have an incomplete
8931 // type or a reference type.
8932 if (RequireCompleteType(ELoc, Type,
8933 diag::err_omp_reduction_incomplete_type))
8934 continue;
8935 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008936 // A list item that appears in a reduction clause must not be
8937 // const-qualified.
8938 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008939 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008940 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008941 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008942 bool IsDecl = !VD ||
8943 VD->isThisDeclarationADefinition(Context) ==
8944 VarDecl::DeclarationOnly;
8945 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008946 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008947 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008948 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008949 continue;
8950 }
8951 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8952 // If a list-item is a reference type then it must bind to the same object
8953 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008954 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008955 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008956 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008957 DSARefChecker Check(DSAStack);
8958 if (Check.Visit(VDDef->getInit())) {
8959 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8960 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8961 continue;
8962 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008963 }
8964 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008965
Alexey Bataevc5e02582014-06-16 07:08:35 +00008966 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8967 // in a Construct]
8968 // Variables with the predetermined data-sharing attributes may not be
8969 // listed in data-sharing attributes clauses, except for the cases
8970 // listed below. For these exceptions only, listing a predetermined
8971 // variable in a data-sharing attribute clause is allowed and overrides
8972 // the variable's predetermined data-sharing attributes.
8973 // OpenMP [2.14.3.6, Restrictions, p.3]
8974 // Any number of reduction clauses can be specified on the directive,
8975 // but a list item can appear only once in the reduction clauses for that
8976 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008977 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008978 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008979 if (DVar.CKind == OMPC_reduction) {
8980 Diag(ELoc, diag::err_omp_once_referenced)
8981 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008982 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008983 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008984 } else if (DVar.CKind != OMPC_unknown) {
8985 Diag(ELoc, diag::err_omp_wrong_dsa)
8986 << getOpenMPClauseName(DVar.CKind)
8987 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008988 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008989 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008990 }
8991
8992 // OpenMP [2.14.3.6, Restrictions, p.1]
8993 // A list item that appears in a reduction clause of a worksharing
8994 // construct must be shared in the parallel regions to which any of the
8995 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008996 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8997 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008998 !isOpenMPParallelDirective(CurrDir) &&
8999 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009000 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009001 if (DVar.CKind != OMPC_shared) {
9002 Diag(ELoc, diag::err_omp_required_access)
9003 << getOpenMPClauseName(OMPC_reduction)
9004 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009005 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009006 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009007 }
9008 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009009
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009010 // Try to find 'declare reduction' corresponding construct before using
9011 // builtin/overloaded operators.
9012 CXXCastPath BasePath;
9013 ExprResult DeclareReductionRef = buildDeclareReductionRef(
9014 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
9015 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9016 if (DeclareReductionRef.isInvalid())
9017 continue;
9018 if (CurContext->isDependentContext() &&
9019 (DeclareReductionRef.isUnset() ||
9020 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
9021 Vars.push_back(RefExpr);
9022 Privates.push_back(nullptr);
9023 LHSs.push_back(nullptr);
9024 RHSs.push_back(nullptr);
9025 ReductionOps.push_back(DeclareReductionRef.get());
9026 continue;
9027 }
9028 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9029 // Not allowed reduction identifier is found.
9030 Diag(ReductionId.getLocStart(),
9031 diag::err_omp_unknown_reduction_identifier)
9032 << Type << ReductionIdRange;
9033 continue;
9034 }
9035
9036 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9037 // The type of a list item that appears in a reduction clause must be valid
9038 // for the reduction-identifier. For a max or min reduction in C, the type
9039 // of the list item must be an allowed arithmetic data type: char, int,
9040 // float, double, or _Bool, possibly modified with long, short, signed, or
9041 // unsigned. For a max or min reduction in C++, the type of the list item
9042 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9043 // double, or bool, possibly modified with long, short, signed, or unsigned.
9044 if (DeclareReductionRef.isUnset()) {
9045 if ((BOK == BO_GT || BOK == BO_LT) &&
9046 !(Type->isScalarType() ||
9047 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9048 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
9049 << getLangOpts().CPlusPlus;
9050 if (!ASE && !OASE) {
9051 bool IsDecl = !VD ||
9052 VD->isThisDeclarationADefinition(Context) ==
9053 VarDecl::DeclarationOnly;
9054 Diag(D->getLocation(),
9055 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9056 << D;
9057 }
9058 continue;
9059 }
9060 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
9061 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
9062 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
9063 if (!ASE && !OASE) {
9064 bool IsDecl = !VD ||
9065 VD->isThisDeclarationADefinition(Context) ==
9066 VarDecl::DeclarationOnly;
9067 Diag(D->getLocation(),
9068 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9069 << D;
9070 }
9071 continue;
9072 }
9073 }
9074
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009075 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009076 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009077 D->hasAttrs() ? &D->getAttrs() : nullptr);
9078 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9079 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009080 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009081 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009082 (!ASE &&
9083 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009084 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009085 // Create pseudo array type for private copy. The size for this array will
9086 // be generated during codegen.
9087 // For array subscripts or single variables Private Ty is the same as Type
9088 // (type of the variable or single array element).
9089 PrivateTy = Context.getVariableArrayType(
9090 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9091 Context.getSizeType(), VK_RValue),
9092 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009093 } else if (!ASE && !OASE &&
9094 Context.getAsArrayType(D->getType().getNonReferenceType()))
9095 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009096 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009097 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9098 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009099 // Add initializer for private variable.
9100 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009101 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9102 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9103 if (DeclareReductionRef.isUsable()) {
9104 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9105 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9106 if (DRD->getInitializer()) {
9107 Init = DRDRef;
9108 RHSVD->setInit(DRDRef);
9109 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009110 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009111 } else {
9112 switch (BOK) {
9113 case BO_Add:
9114 case BO_Xor:
9115 case BO_Or:
9116 case BO_LOr:
9117 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9118 if (Type->isScalarType() || Type->isAnyComplexType())
9119 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9120 break;
9121 case BO_Mul:
9122 case BO_LAnd:
9123 if (Type->isScalarType() || Type->isAnyComplexType()) {
9124 // '*' and '&&' reduction ops - initializer is '1'.
9125 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009126 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009127 break;
9128 case BO_And: {
9129 // '&' reduction op - initializer is '~0'.
9130 QualType OrigType = Type;
9131 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9132 Type = ComplexTy->getElementType();
9133 if (Type->isRealFloatingType()) {
9134 llvm::APFloat InitValue =
9135 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9136 /*isIEEE=*/true);
9137 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9138 Type, ELoc);
9139 } else if (Type->isScalarType()) {
9140 auto Size = Context.getTypeSize(Type);
9141 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9142 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9143 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9144 }
9145 if (Init && OrigType->isAnyComplexType()) {
9146 // Init = 0xFFFF + 0xFFFFi;
9147 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9148 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9149 }
9150 Type = OrigType;
9151 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009152 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009153 case BO_LT:
9154 case BO_GT: {
9155 // 'min' reduction op - initializer is 'Largest representable number in
9156 // the reduction list item type'.
9157 // 'max' reduction op - initializer is 'Least representable number in
9158 // the reduction list item type'.
9159 if (Type->isIntegerType() || Type->isPointerType()) {
9160 bool IsSigned = Type->hasSignedIntegerRepresentation();
9161 auto Size = Context.getTypeSize(Type);
9162 QualType IntTy =
9163 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9164 llvm::APInt InitValue =
9165 (BOK != BO_LT)
9166 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9167 : llvm::APInt::getMinValue(Size)
9168 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9169 : llvm::APInt::getMaxValue(Size);
9170 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9171 if (Type->isPointerType()) {
9172 // Cast to pointer type.
9173 auto CastExpr = BuildCStyleCastExpr(
9174 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9175 SourceLocation(), Init);
9176 if (CastExpr.isInvalid())
9177 continue;
9178 Init = CastExpr.get();
9179 }
9180 } else if (Type->isRealFloatingType()) {
9181 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9182 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9183 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9184 Type, ELoc);
9185 }
9186 break;
9187 }
9188 case BO_PtrMemD:
9189 case BO_PtrMemI:
9190 case BO_MulAssign:
9191 case BO_Div:
9192 case BO_Rem:
9193 case BO_Sub:
9194 case BO_Shl:
9195 case BO_Shr:
9196 case BO_LE:
9197 case BO_GE:
9198 case BO_EQ:
9199 case BO_NE:
9200 case BO_AndAssign:
9201 case BO_XorAssign:
9202 case BO_OrAssign:
9203 case BO_Assign:
9204 case BO_AddAssign:
9205 case BO_SubAssign:
9206 case BO_DivAssign:
9207 case BO_RemAssign:
9208 case BO_ShlAssign:
9209 case BO_ShrAssign:
9210 case BO_Comma:
9211 llvm_unreachable("Unexpected reduction operation");
9212 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009213 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009214 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009215 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009216 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009217 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009218 if (RHSVD->isInvalidDecl())
9219 continue;
9220 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009221 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9222 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009223 bool IsDecl =
9224 !VD ||
9225 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9226 Diag(D->getLocation(),
9227 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9228 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009229 continue;
9230 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009231 // Store initializer for single element in private copy. Will be used during
9232 // codegen.
9233 PrivateVD->setInit(RHSVD->getInit());
9234 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009235 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009236 ExprResult ReductionOp;
9237 if (DeclareReductionRef.isUsable()) {
9238 QualType RedTy = DeclareReductionRef.get()->getType();
9239 QualType PtrRedTy = Context.getPointerType(RedTy);
9240 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9241 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9242 if (!BasePath.empty()) {
9243 LHS = DefaultLvalueConversion(LHS.get());
9244 RHS = DefaultLvalueConversion(RHS.get());
9245 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9246 CK_UncheckedDerivedToBase, LHS.get(),
9247 &BasePath, LHS.get()->getValueKind());
9248 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9249 CK_UncheckedDerivedToBase, RHS.get(),
9250 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009251 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009252 FunctionProtoType::ExtProtoInfo EPI;
9253 QualType Params[] = {PtrRedTy, PtrRedTy};
9254 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9255 auto *OVE = new (Context) OpaqueValueExpr(
9256 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9257 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9258 Expr *Args[] = {LHS.get(), RHS.get()};
9259 ReductionOp = new (Context)
9260 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9261 } else {
9262 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9263 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9264 if (ReductionOp.isUsable()) {
9265 if (BOK != BO_LT && BOK != BO_GT) {
9266 ReductionOp =
9267 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9268 BO_Assign, LHSDRE, ReductionOp.get());
9269 } else {
9270 auto *ConditionalOp = new (Context) ConditionalOperator(
9271 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9272 RHSDRE, Type, VK_LValue, OK_Ordinary);
9273 ReductionOp =
9274 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9275 BO_Assign, LHSDRE, ConditionalOp);
9276 }
9277 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9278 }
9279 if (ReductionOp.isInvalid())
9280 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009281 }
9282
Alexey Bataev60da77e2016-02-29 05:54:20 +00009283 DeclRefExpr *Ref = nullptr;
9284 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009285 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009286 if (ASE || OASE) {
9287 TransformExprToCaptures RebuildToCapture(*this, D);
9288 VarsExpr =
9289 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9290 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009291 } else {
9292 VarsExpr = Ref =
9293 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009294 }
9295 if (!IsOpenMPCapturedDecl(D)) {
9296 ExprCaptures.push_back(Ref->getDecl());
9297 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9298 ExprResult RefRes = DefaultLvalueConversion(Ref);
9299 if (!RefRes.isUsable())
9300 continue;
9301 ExprResult PostUpdateRes =
9302 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9303 SimpleRefExpr, RefRes.get());
9304 if (!PostUpdateRes.isUsable())
9305 continue;
9306 ExprPostUpdates.push_back(
9307 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009308 }
9309 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009310 }
9311 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9312 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009313 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009314 LHSs.push_back(LHSDRE);
9315 RHSs.push_back(RHSDRE);
9316 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009317 }
9318
9319 if (Vars.empty())
9320 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009321
Alexey Bataevc5e02582014-06-16 07:08:35 +00009322 return OMPReductionClause::Create(
9323 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009324 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009325 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9326 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009327}
9328
Alexey Bataevecba70f2016-04-12 11:02:11 +00009329bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9330 SourceLocation LinLoc) {
9331 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9332 LinKind == OMPC_LINEAR_unknown) {
9333 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9334 return true;
9335 }
9336 return false;
9337}
9338
9339bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9340 OpenMPLinearClauseKind LinKind,
9341 QualType Type) {
9342 auto *VD = dyn_cast_or_null<VarDecl>(D);
9343 // A variable must not have an incomplete type or a reference type.
9344 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9345 return true;
9346 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9347 !Type->isReferenceType()) {
9348 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9349 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9350 return true;
9351 }
9352 Type = Type.getNonReferenceType();
9353
9354 // A list item must not be const-qualified.
9355 if (Type.isConstant(Context)) {
9356 Diag(ELoc, diag::err_omp_const_variable)
9357 << getOpenMPClauseName(OMPC_linear);
9358 if (D) {
9359 bool IsDecl =
9360 !VD ||
9361 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9362 Diag(D->getLocation(),
9363 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9364 << D;
9365 }
9366 return true;
9367 }
9368
9369 // A list item must be of integral or pointer type.
9370 Type = Type.getUnqualifiedType().getCanonicalType();
9371 const auto *Ty = Type.getTypePtrOrNull();
9372 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9373 !Ty->isPointerType())) {
9374 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9375 if (D) {
9376 bool IsDecl =
9377 !VD ||
9378 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9379 Diag(D->getLocation(),
9380 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9381 << D;
9382 }
9383 return true;
9384 }
9385 return false;
9386}
9387
Alexey Bataev182227b2015-08-20 10:54:39 +00009388OMPClause *Sema::ActOnOpenMPLinearClause(
9389 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9390 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9391 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009392 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009393 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009394 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009395 SmallVector<Decl *, 4> ExprCaptures;
9396 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009397 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009398 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009399 for (auto &RefExpr : VarList) {
9400 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009401 SourceLocation ELoc;
9402 SourceRange ERange;
9403 Expr *SimpleRefExpr = RefExpr;
9404 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9405 /*AllowArraySection=*/false);
9406 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009407 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009408 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009409 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009410 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009411 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009412 ValueDecl *D = Res.first;
9413 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009414 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009415
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009416 QualType Type = D->getType();
9417 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009418
9419 // OpenMP [2.14.3.7, linear clause]
9420 // A list-item cannot appear in more than one linear clause.
9421 // A list-item that appears in a linear clause cannot appear in any
9422 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009423 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009424 if (DVar.RefExpr) {
9425 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9426 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009427 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009428 continue;
9429 }
9430
Alexey Bataevecba70f2016-04-12 11:02:11 +00009431 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009432 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009433 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009434
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009435 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009436 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9437 D->hasAttrs() ? &D->getAttrs() : nullptr);
9438 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009439 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009440 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009441 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009442 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009443 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009444 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9445 if (!IsOpenMPCapturedDecl(D)) {
9446 ExprCaptures.push_back(Ref->getDecl());
9447 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9448 ExprResult RefRes = DefaultLvalueConversion(Ref);
9449 if (!RefRes.isUsable())
9450 continue;
9451 ExprResult PostUpdateRes =
9452 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9453 SimpleRefExpr, RefRes.get());
9454 if (!PostUpdateRes.isUsable())
9455 continue;
9456 ExprPostUpdates.push_back(
9457 IgnoredValueConversions(PostUpdateRes.get()).get());
9458 }
9459 }
9460 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009461 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009462 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009463 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009464 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009465 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009466 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009467 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9468
9469 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009470 Vars.push_back((VD || CurContext->isDependentContext())
9471 ? RefExpr->IgnoreParens()
9472 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009473 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009474 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009475 }
9476
9477 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009478 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009479
9480 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009481 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009482 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9483 !Step->isInstantiationDependent() &&
9484 !Step->containsUnexpandedParameterPack()) {
9485 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009486 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009487 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009488 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009489 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009490
Alexander Musman3276a272015-03-21 10:12:56 +00009491 // Build var to save the step value.
9492 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009493 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009494 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009495 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009496 ExprResult CalcStep =
9497 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009498 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009499
Alexander Musman8dba6642014-04-22 13:09:42 +00009500 // Warn about zero linear step (it would be probably better specified as
9501 // making corresponding variables 'const').
9502 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009503 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9504 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009505 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9506 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009507 if (!IsConstant && CalcStep.isUsable()) {
9508 // Calculate the step beforehand instead of doing this on each iteration.
9509 // (This is not used if the number of iterations may be kfold-ed).
9510 CalcStepExpr = CalcStep.get();
9511 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009512 }
9513
Alexey Bataev182227b2015-08-20 10:54:39 +00009514 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9515 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009516 StepExpr, CalcStepExpr,
9517 buildPreInits(Context, ExprCaptures),
9518 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009519}
9520
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009521static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9522 Expr *NumIterations, Sema &SemaRef,
9523 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009524 // Walk the vars and build update/final expressions for the CodeGen.
9525 SmallVector<Expr *, 8> Updates;
9526 SmallVector<Expr *, 8> Finals;
9527 Expr *Step = Clause.getStep();
9528 Expr *CalcStep = Clause.getCalcStep();
9529 // OpenMP [2.14.3.7, linear clause]
9530 // If linear-step is not specified it is assumed to be 1.
9531 if (Step == nullptr)
9532 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009533 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009534 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009535 }
Alexander Musman3276a272015-03-21 10:12:56 +00009536 bool HasErrors = false;
9537 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009538 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009539 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009540 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009541 SourceLocation ELoc;
9542 SourceRange ERange;
9543 Expr *SimpleRefExpr = RefExpr;
9544 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9545 /*AllowArraySection=*/false);
9546 ValueDecl *D = Res.first;
9547 if (Res.second || !D) {
9548 Updates.push_back(nullptr);
9549 Finals.push_back(nullptr);
9550 HasErrors = true;
9551 continue;
9552 }
9553 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9554 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9555 ->getMemberDecl();
9556 }
9557 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009558 Expr *InitExpr = *CurInit;
9559
9560 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009561 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009562 Expr *CapturedRef;
9563 if (LinKind == OMPC_LINEAR_uval)
9564 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9565 else
9566 CapturedRef =
9567 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9568 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9569 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009570
9571 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009572 ExprResult Update;
9573 if (!Info.first) {
9574 Update =
9575 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9576 InitExpr, IV, Step, /* Subtract */ false);
9577 } else
9578 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009579 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9580 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009581
9582 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009583 ExprResult Final;
9584 if (!Info.first) {
9585 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9586 InitExpr, NumIterations, Step,
9587 /* Subtract */ false);
9588 } else
9589 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009590 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9591 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009592
Alexander Musman3276a272015-03-21 10:12:56 +00009593 if (!Update.isUsable() || !Final.isUsable()) {
9594 Updates.push_back(nullptr);
9595 Finals.push_back(nullptr);
9596 HasErrors = true;
9597 } else {
9598 Updates.push_back(Update.get());
9599 Finals.push_back(Final.get());
9600 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009601 ++CurInit;
9602 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009603 }
9604 Clause.setUpdates(Updates);
9605 Clause.setFinals(Finals);
9606 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009607}
9608
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009609OMPClause *Sema::ActOnOpenMPAlignedClause(
9610 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9611 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9612
9613 SmallVector<Expr *, 8> Vars;
9614 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009615 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9616 SourceLocation ELoc;
9617 SourceRange ERange;
9618 Expr *SimpleRefExpr = RefExpr;
9619 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9620 /*AllowArraySection=*/false);
9621 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009622 // It will be analyzed later.
9623 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009624 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009625 ValueDecl *D = Res.first;
9626 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009627 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009628
Alexey Bataev1efd1662016-03-29 10:59:56 +00009629 QualType QType = D->getType();
9630 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009631
9632 // OpenMP [2.8.1, simd construct, Restrictions]
9633 // The type of list items appearing in the aligned clause must be
9634 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009635 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009636 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009637 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009638 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009639 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009640 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009641 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009642 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009643 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009644 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009645 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009646 continue;
9647 }
9648
9649 // OpenMP [2.8.1, simd construct, Restrictions]
9650 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009651 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009652 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009653 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9654 << getOpenMPClauseName(OMPC_aligned);
9655 continue;
9656 }
9657
Alexey Bataev1efd1662016-03-29 10:59:56 +00009658 DeclRefExpr *Ref = nullptr;
9659 if (!VD && IsOpenMPCapturedDecl(D))
9660 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9661 Vars.push_back(DefaultFunctionArrayConversion(
9662 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9663 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009664 }
9665
9666 // OpenMP [2.8.1, simd construct, Description]
9667 // The parameter of the aligned clause, alignment, must be a constant
9668 // positive integer expression.
9669 // If no optional parameter is specified, implementation-defined default
9670 // alignments for SIMD instructions on the target platforms are assumed.
9671 if (Alignment != nullptr) {
9672 ExprResult AlignResult =
9673 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9674 if (AlignResult.isInvalid())
9675 return nullptr;
9676 Alignment = AlignResult.get();
9677 }
9678 if (Vars.empty())
9679 return nullptr;
9680
9681 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9682 EndLoc, Vars, Alignment);
9683}
9684
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009685OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9686 SourceLocation StartLoc,
9687 SourceLocation LParenLoc,
9688 SourceLocation EndLoc) {
9689 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009690 SmallVector<Expr *, 8> SrcExprs;
9691 SmallVector<Expr *, 8> DstExprs;
9692 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009693 for (auto &RefExpr : VarList) {
9694 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9695 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009696 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009697 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009698 SrcExprs.push_back(nullptr);
9699 DstExprs.push_back(nullptr);
9700 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009701 continue;
9702 }
9703
Alexey Bataeved09d242014-05-28 05:53:51 +00009704 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009705 // OpenMP [2.1, C/C++]
9706 // A list item is a variable name.
9707 // OpenMP [2.14.4.1, Restrictions, p.1]
9708 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009709 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009710 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009711 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9712 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009713 continue;
9714 }
9715
9716 Decl *D = DE->getDecl();
9717 VarDecl *VD = cast<VarDecl>(D);
9718
9719 QualType Type = VD->getType();
9720 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9721 // It will be analyzed later.
9722 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009723 SrcExprs.push_back(nullptr);
9724 DstExprs.push_back(nullptr);
9725 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009726 continue;
9727 }
9728
9729 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9730 // A list item that appears in a copyin clause must be threadprivate.
9731 if (!DSAStack->isThreadPrivate(VD)) {
9732 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009733 << getOpenMPClauseName(OMPC_copyin)
9734 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009735 continue;
9736 }
9737
9738 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9739 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009740 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009741 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009742 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009743 auto *SrcVD =
9744 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9745 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009746 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009747 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9748 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009749 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9750 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009751 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009752 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009753 // For arrays generate assignment operation for single element and replace
9754 // it by the original array element in CodeGen.
9755 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9756 PseudoDstExpr, PseudoSrcExpr);
9757 if (AssignmentOp.isInvalid())
9758 continue;
9759 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9760 /*DiscardedValue=*/true);
9761 if (AssignmentOp.isInvalid())
9762 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009763
9764 DSAStack->addDSA(VD, DE, OMPC_copyin);
9765 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009766 SrcExprs.push_back(PseudoSrcExpr);
9767 DstExprs.push_back(PseudoDstExpr);
9768 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009769 }
9770
Alexey Bataeved09d242014-05-28 05:53:51 +00009771 if (Vars.empty())
9772 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009773
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009774 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9775 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009776}
9777
Alexey Bataevbae9a792014-06-27 10:37:06 +00009778OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9779 SourceLocation StartLoc,
9780 SourceLocation LParenLoc,
9781 SourceLocation EndLoc) {
9782 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009783 SmallVector<Expr *, 8> SrcExprs;
9784 SmallVector<Expr *, 8> DstExprs;
9785 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009786 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009787 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9788 SourceLocation ELoc;
9789 SourceRange ERange;
9790 Expr *SimpleRefExpr = RefExpr;
9791 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9792 /*AllowArraySection=*/false);
9793 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009794 // It will be analyzed later.
9795 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009796 SrcExprs.push_back(nullptr);
9797 DstExprs.push_back(nullptr);
9798 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009799 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009800 ValueDecl *D = Res.first;
9801 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009802 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009803
Alexey Bataeve122da12016-03-17 10:50:17 +00009804 QualType Type = D->getType();
9805 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009806
9807 // OpenMP [2.14.4.2, Restrictions, p.2]
9808 // A list item that appears in a copyprivate clause may not appear in a
9809 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009810 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9811 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009812 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9813 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009814 Diag(ELoc, diag::err_omp_wrong_dsa)
9815 << getOpenMPClauseName(DVar.CKind)
9816 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009817 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009818 continue;
9819 }
9820
9821 // OpenMP [2.11.4.2, Restrictions, p.1]
9822 // All list items that appear in a copyprivate clause must be either
9823 // threadprivate or private in the enclosing context.
9824 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009825 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009826 if (DVar.CKind == OMPC_shared) {
9827 Diag(ELoc, diag::err_omp_required_access)
9828 << getOpenMPClauseName(OMPC_copyprivate)
9829 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009830 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009831 continue;
9832 }
9833 }
9834 }
9835
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009836 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009837 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009838 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009839 << getOpenMPClauseName(OMPC_copyprivate) << Type
9840 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009841 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009842 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009843 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009844 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009845 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009846 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009847 continue;
9848 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009849
Alexey Bataevbae9a792014-06-27 10:37:06 +00009850 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9851 // A variable of class type (or array thereof) that appears in a
9852 // copyin clause requires an accessible, unambiguous copy assignment
9853 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009854 Type = Context.getBaseElementType(Type.getNonReferenceType())
9855 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009856 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009857 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9858 D->hasAttrs() ? &D->getAttrs() : nullptr);
9859 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009860 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009861 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9862 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009863 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009864 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009865 PseudoDstExpr, PseudoSrcExpr);
9866 if (AssignmentOp.isInvalid())
9867 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009868 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009869 /*DiscardedValue=*/true);
9870 if (AssignmentOp.isInvalid())
9871 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009872
9873 // No need to mark vars as copyprivate, they are already threadprivate or
9874 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009875 assert(VD || IsOpenMPCapturedDecl(D));
9876 Vars.push_back(
9877 VD ? RefExpr->IgnoreParens()
9878 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009879 SrcExprs.push_back(PseudoSrcExpr);
9880 DstExprs.push_back(PseudoDstExpr);
9881 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009882 }
9883
9884 if (Vars.empty())
9885 return nullptr;
9886
Alexey Bataeva63048e2015-03-23 06:18:07 +00009887 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9888 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009889}
9890
Alexey Bataev6125da92014-07-21 11:26:11 +00009891OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9892 SourceLocation StartLoc,
9893 SourceLocation LParenLoc,
9894 SourceLocation EndLoc) {
9895 if (VarList.empty())
9896 return nullptr;
9897
9898 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9899}
Alexey Bataevdea47612014-07-23 07:46:59 +00009900
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009901OMPClause *
9902Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9903 SourceLocation DepLoc, SourceLocation ColonLoc,
9904 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9905 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009906 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009907 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009908 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009909 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009910 return nullptr;
9911 }
9912 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009913 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9914 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009915 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009916 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009917 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9918 /*Last=*/OMPC_DEPEND_unknown, Except)
9919 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009920 return nullptr;
9921 }
9922 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009923 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009924 llvm::APSInt DepCounter(/*BitWidth=*/32);
9925 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9926 if (DepKind == OMPC_DEPEND_sink) {
9927 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9928 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9929 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009930 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009931 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009932 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9933 DSAStack->getParentOrderedRegionParam()) {
9934 for (auto &RefExpr : VarList) {
9935 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009936 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009937 // It will be analyzed later.
9938 Vars.push_back(RefExpr);
9939 continue;
9940 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009941
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009942 SourceLocation ELoc = RefExpr->getExprLoc();
9943 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9944 if (DepKind == OMPC_DEPEND_sink) {
9945 if (DepCounter >= TotalDepCount) {
9946 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9947 continue;
9948 }
9949 ++DepCounter;
9950 // OpenMP [2.13.9, Summary]
9951 // depend(dependence-type : vec), where dependence-type is:
9952 // 'sink' and where vec is the iteration vector, which has the form:
9953 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9954 // where n is the value specified by the ordered clause in the loop
9955 // directive, xi denotes the loop iteration variable of the i-th nested
9956 // loop associated with the loop directive, and di is a constant
9957 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009958 if (CurContext->isDependentContext()) {
9959 // It will be analyzed later.
9960 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009961 continue;
9962 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009963 SimpleExpr = SimpleExpr->IgnoreImplicit();
9964 OverloadedOperatorKind OOK = OO_None;
9965 SourceLocation OOLoc;
9966 Expr *LHS = SimpleExpr;
9967 Expr *RHS = nullptr;
9968 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9969 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9970 OOLoc = BO->getOperatorLoc();
9971 LHS = BO->getLHS()->IgnoreParenImpCasts();
9972 RHS = BO->getRHS()->IgnoreParenImpCasts();
9973 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9974 OOK = OCE->getOperator();
9975 OOLoc = OCE->getOperatorLoc();
9976 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9977 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9978 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9979 OOK = MCE->getMethodDecl()
9980 ->getNameInfo()
9981 .getName()
9982 .getCXXOverloadedOperator();
9983 OOLoc = MCE->getCallee()->getExprLoc();
9984 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9985 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9986 }
9987 SourceLocation ELoc;
9988 SourceRange ERange;
9989 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9990 /*AllowArraySection=*/false);
9991 if (Res.second) {
9992 // It will be analyzed later.
9993 Vars.push_back(RefExpr);
9994 }
9995 ValueDecl *D = Res.first;
9996 if (!D)
9997 continue;
9998
9999 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10000 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10001 continue;
10002 }
10003 if (RHS) {
10004 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10005 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10006 if (RHSRes.isInvalid())
10007 continue;
10008 }
10009 if (!CurContext->isDependentContext() &&
10010 DSAStack->getParentOrderedRegionParam() &&
10011 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10012 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10013 << DSAStack->getParentLoopControlVariable(
10014 DepCounter.getZExtValue());
10015 continue;
10016 }
10017 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010018 } else {
10019 // OpenMP [2.11.1.1, Restrictions, p.3]
10020 // A variable that is part of another variable (such as a field of a
10021 // structure) but is not an array element or an array section cannot
10022 // appear in a depend clause.
10023 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10024 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10025 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10026 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10027 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010028 (ASE &&
10029 !ASE->getBase()
10030 ->getType()
10031 .getNonReferenceType()
10032 ->isPointerType() &&
10033 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010034 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10035 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010036 continue;
10037 }
10038 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010039 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10040 }
10041
10042 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10043 TotalDepCount > VarList.size() &&
10044 DSAStack->getParentOrderedRegionParam()) {
10045 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10046 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10047 }
10048 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10049 Vars.empty())
10050 return nullptr;
10051 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010052 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10053 DepKind, DepLoc, ColonLoc, Vars);
10054 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10055 DSAStack->addDoacrossDependClause(C, OpsOffs);
10056 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010057}
Michael Wonge710d542015-08-07 16:16:36 +000010058
10059OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10060 SourceLocation LParenLoc,
10061 SourceLocation EndLoc) {
10062 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010063
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010064 // OpenMP [2.9.1, Restrictions]
10065 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010066 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10067 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010068 return nullptr;
10069
Michael Wonge710d542015-08-07 16:16:36 +000010070 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10071}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010072
10073static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10074 DSAStackTy *Stack, CXXRecordDecl *RD) {
10075 if (!RD || RD->isInvalidDecl())
10076 return true;
10077
10078 auto QTy = SemaRef.Context.getRecordType(RD);
10079 if (RD->isDynamicClass()) {
10080 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10081 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10082 return false;
10083 }
10084 auto *DC = RD;
10085 bool IsCorrect = true;
10086 for (auto *I : DC->decls()) {
10087 if (I) {
10088 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10089 if (MD->isStatic()) {
10090 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10091 SemaRef.Diag(MD->getLocation(),
10092 diag::note_omp_static_member_in_target);
10093 IsCorrect = false;
10094 }
10095 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10096 if (VD->isStaticDataMember()) {
10097 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10098 SemaRef.Diag(VD->getLocation(),
10099 diag::note_omp_static_member_in_target);
10100 IsCorrect = false;
10101 }
10102 }
10103 }
10104 }
10105
10106 for (auto &I : RD->bases()) {
10107 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10108 I.getType()->getAsCXXRecordDecl()))
10109 IsCorrect = false;
10110 }
10111 return IsCorrect;
10112}
10113
10114static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10115 DSAStackTy *Stack, QualType QTy) {
10116 NamedDecl *ND;
10117 if (QTy->isIncompleteType(&ND)) {
10118 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10119 return false;
10120 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010121 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010122 return false;
10123 }
10124 return true;
10125}
10126
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010127/// \brief Return true if it can be proven that the provided array expression
10128/// (array section or array subscript) does NOT specify the whole size of the
10129/// array whose base type is \a BaseQTy.
10130static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10131 const Expr *E,
10132 QualType BaseQTy) {
10133 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10134
10135 // If this is an array subscript, it refers to the whole size if the size of
10136 // the dimension is constant and equals 1. Also, an array section assumes the
10137 // format of an array subscript if no colon is used.
10138 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10139 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10140 return ATy->getSize().getSExtValue() != 1;
10141 // Size can't be evaluated statically.
10142 return false;
10143 }
10144
10145 assert(OASE && "Expecting array section if not an array subscript.");
10146 auto *LowerBound = OASE->getLowerBound();
10147 auto *Length = OASE->getLength();
10148
10149 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010150 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010151 if (LowerBound) {
10152 llvm::APSInt ConstLowerBound;
10153 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10154 return false; // Can't get the integer value as a constant.
10155 if (ConstLowerBound.getSExtValue())
10156 return true;
10157 }
10158
10159 // If we don't have a length we covering the whole dimension.
10160 if (!Length)
10161 return false;
10162
10163 // If the base is a pointer, we don't have a way to get the size of the
10164 // pointee.
10165 if (BaseQTy->isPointerType())
10166 return false;
10167
10168 // We can only check if the length is the same as the size of the dimension
10169 // if we have a constant array.
10170 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10171 if (!CATy)
10172 return false;
10173
10174 llvm::APSInt ConstLength;
10175 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10176 return false; // Can't get the integer value as a constant.
10177
10178 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10179}
10180
10181// Return true if it can be proven that the provided array expression (array
10182// section or array subscript) does NOT specify a single element of the array
10183// whose base type is \a BaseQTy.
10184static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010185 const Expr *E,
10186 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010187 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10188
10189 // An array subscript always refer to a single element. Also, an array section
10190 // assumes the format of an array subscript if no colon is used.
10191 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10192 return false;
10193
10194 assert(OASE && "Expecting array section if not an array subscript.");
10195 auto *Length = OASE->getLength();
10196
10197 // If we don't have a length we have to check if the array has unitary size
10198 // for this dimension. Also, we should always expect a length if the base type
10199 // is pointer.
10200 if (!Length) {
10201 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10202 return ATy->getSize().getSExtValue() != 1;
10203 // We cannot assume anything.
10204 return false;
10205 }
10206
10207 // Check if the length evaluates to 1.
10208 llvm::APSInt ConstLength;
10209 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10210 return false; // Can't get the integer value as a constant.
10211
10212 return ConstLength.getSExtValue() != 1;
10213}
10214
Samuel Antao661c0902016-05-26 17:39:58 +000010215// Return the expression of the base of the mappable expression or null if it
10216// cannot be determined and do all the necessary checks to see if the expression
10217// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010218// components of the expression.
10219static Expr *CheckMapClauseExpressionBase(
10220 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010221 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10222 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010223 SourceLocation ELoc = E->getExprLoc();
10224 SourceRange ERange = E->getSourceRange();
10225
10226 // The base of elements of list in a map clause have to be either:
10227 // - a reference to variable or field.
10228 // - a member expression.
10229 // - an array expression.
10230 //
10231 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10232 // reference to 'r'.
10233 //
10234 // If we have:
10235 //
10236 // struct SS {
10237 // Bla S;
10238 // foo() {
10239 // #pragma omp target map (S.Arr[:12]);
10240 // }
10241 // }
10242 //
10243 // We want to retrieve the member expression 'this->S';
10244
10245 Expr *RelevantExpr = nullptr;
10246
Samuel Antao5de996e2016-01-22 20:21:36 +000010247 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10248 // If a list item is an array section, it must specify contiguous storage.
10249 //
10250 // For this restriction it is sufficient that we make sure only references
10251 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010252 // exist except in the rightmost expression (unless they cover the whole
10253 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010254 //
10255 // r.ArrS[3:5].Arr[6:7]
10256 //
10257 // r.ArrS[3:5].x
10258 //
10259 // but these would be valid:
10260 // r.ArrS[3].Arr[6:7]
10261 //
10262 // r.ArrS[3].x
10263
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010264 bool AllowUnitySizeArraySection = true;
10265 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010266
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010267 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010268 E = E->IgnoreParenImpCasts();
10269
10270 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10271 if (!isa<VarDecl>(CurE->getDecl()))
10272 break;
10273
10274 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010275
10276 // If we got a reference to a declaration, we should not expect any array
10277 // section before that.
10278 AllowUnitySizeArraySection = false;
10279 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010280
10281 // Record the component.
10282 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10283 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010284 continue;
10285 }
10286
10287 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10288 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10289
10290 if (isa<CXXThisExpr>(BaseE))
10291 // We found a base expression: this->Val.
10292 RelevantExpr = CurE;
10293 else
10294 E = BaseE;
10295
10296 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10297 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10298 << CurE->getSourceRange();
10299 break;
10300 }
10301
10302 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10303
10304 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10305 // A bit-field cannot appear in a map clause.
10306 //
10307 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010308 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10309 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010310 break;
10311 }
10312
10313 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10314 // If the type of a list item is a reference to a type T then the type
10315 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010316 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010317
10318 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10319 // A list item cannot be a variable that is a member of a structure with
10320 // a union type.
10321 //
10322 if (auto *RT = CurType->getAs<RecordType>())
10323 if (RT->isUnionType()) {
10324 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10325 << CurE->getSourceRange();
10326 break;
10327 }
10328
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010329 // If we got a member expression, we should not expect any array section
10330 // before that:
10331 //
10332 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10333 // If a list item is an element of a structure, only the rightmost symbol
10334 // of the variable reference can be an array section.
10335 //
10336 AllowUnitySizeArraySection = false;
10337 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010338
10339 // Record the component.
10340 CurComponents.push_back(
10341 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010342 continue;
10343 }
10344
10345 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10346 E = CurE->getBase()->IgnoreParenImpCasts();
10347
10348 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10349 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10350 << 0 << CurE->getSourceRange();
10351 break;
10352 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010353
10354 // If we got an array subscript that express the whole dimension we
10355 // can have any array expressions before. If it only expressing part of
10356 // the dimension, we can only have unitary-size array expressions.
10357 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10358 E->getType()))
10359 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010360
10361 // Record the component - we don't have any declaration associated.
10362 CurComponents.push_back(
10363 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010364 continue;
10365 }
10366
10367 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010368 E = CurE->getBase()->IgnoreParenImpCasts();
10369
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010370 auto CurType =
10371 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10372
Samuel Antao5de996e2016-01-22 20:21:36 +000010373 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10374 // If the type of a list item is a reference to a type T then the type
10375 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010376 if (CurType->isReferenceType())
10377 CurType = CurType->getPointeeType();
10378
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010379 bool IsPointer = CurType->isAnyPointerType();
10380
10381 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010382 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10383 << 0 << CurE->getSourceRange();
10384 break;
10385 }
10386
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010387 bool NotWhole =
10388 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10389 bool NotUnity =
10390 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10391
Samuel Antaodab51bb2016-07-18 23:22:11 +000010392 if (AllowWholeSizeArraySection) {
10393 // Any array section is currently allowed. Allowing a whole size array
10394 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010395 //
10396 // If this array section refers to the whole dimension we can still
10397 // accept other array sections before this one, except if the base is a
10398 // pointer. Otherwise, only unitary sections are accepted.
10399 if (NotWhole || IsPointer)
10400 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010401 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010402 // A unity or whole array section is not allowed and that is not
10403 // compatible with the properties of the current array section.
10404 SemaRef.Diag(
10405 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10406 << CurE->getSourceRange();
10407 break;
10408 }
Samuel Antao90927002016-04-26 14:54:23 +000010409
10410 // Record the component - we don't have any declaration associated.
10411 CurComponents.push_back(
10412 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010413 continue;
10414 }
10415
10416 // If nothing else worked, this is not a valid map clause expression.
10417 SemaRef.Diag(ELoc,
10418 diag::err_omp_expected_named_var_member_or_array_expression)
10419 << ERange;
10420 break;
10421 }
10422
10423 return RelevantExpr;
10424}
10425
10426// Return true if expression E associated with value VD has conflicts with other
10427// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010428static bool CheckMapConflicts(
10429 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10430 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010431 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10432 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010433 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010434 SourceLocation ELoc = E->getExprLoc();
10435 SourceRange ERange = E->getSourceRange();
10436
10437 // In order to easily check the conflicts we need to match each component of
10438 // the expression under test with the components of the expressions that are
10439 // already in the stack.
10440
Samuel Antao5de996e2016-01-22 20:21:36 +000010441 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010442 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010443 "Map clause expression with unexpected base!");
10444
10445 // Variables to help detecting enclosing problems in data environment nests.
10446 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010447 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010448
Samuel Antao90927002016-04-26 14:54:23 +000010449 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10450 VD, CurrentRegionOnly,
10451 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010452 StackComponents,
10453 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010454
Samuel Antao5de996e2016-01-22 20:21:36 +000010455 assert(!StackComponents.empty() &&
10456 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010457 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010458 "Map clause expression with unexpected base!");
10459
Samuel Antao90927002016-04-26 14:54:23 +000010460 // The whole expression in the stack.
10461 auto *RE = StackComponents.front().getAssociatedExpression();
10462
Samuel Antao5de996e2016-01-22 20:21:36 +000010463 // Expressions must start from the same base. Here we detect at which
10464 // point both expressions diverge from each other and see if we can
10465 // detect if the memory referred to both expressions is contiguous and
10466 // do not overlap.
10467 auto CI = CurComponents.rbegin();
10468 auto CE = CurComponents.rend();
10469 auto SI = StackComponents.rbegin();
10470 auto SE = StackComponents.rend();
10471 for (; CI != CE && SI != SE; ++CI, ++SI) {
10472
10473 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10474 // At most one list item can be an array item derived from a given
10475 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010476 if (CurrentRegionOnly &&
10477 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10478 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10479 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10480 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10481 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010482 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010483 << CI->getAssociatedExpression()->getSourceRange();
10484 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10485 diag::note_used_here)
10486 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010487 return true;
10488 }
10489
10490 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010491 if (CI->getAssociatedExpression()->getStmtClass() !=
10492 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010493 break;
10494
10495 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010496 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010497 break;
10498 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010499 // Check if the extra components of the expressions in the enclosing
10500 // data environment are redundant for the current base declaration.
10501 // If they are, the maps completely overlap, which is legal.
10502 for (; SI != SE; ++SI) {
10503 QualType Type;
10504 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010505 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010506 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010507 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10508 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010509 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10510 Type =
10511 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10512 }
10513 if (Type.isNull() || Type->isAnyPointerType() ||
10514 CheckArrayExpressionDoesNotReferToWholeSize(
10515 SemaRef, SI->getAssociatedExpression(), Type))
10516 break;
10517 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010518
10519 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10520 // List items of map clauses in the same construct must not share
10521 // original storage.
10522 //
10523 // If the expressions are exactly the same or one is a subset of the
10524 // other, it means they are sharing storage.
10525 if (CI == CE && SI == SE) {
10526 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010527 if (CKind == OMPC_map)
10528 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10529 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010530 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010531 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10532 << ERange;
10533 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010534 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10535 << RE->getSourceRange();
10536 return true;
10537 } else {
10538 // If we find the same expression in the enclosing data environment,
10539 // that is legal.
10540 IsEnclosedByDataEnvironmentExpr = true;
10541 return false;
10542 }
10543 }
10544
Samuel Antao90927002016-04-26 14:54:23 +000010545 QualType DerivedType =
10546 std::prev(CI)->getAssociatedDeclaration()->getType();
10547 SourceLocation DerivedLoc =
10548 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010549
10550 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10551 // If the type of a list item is a reference to a type T then the type
10552 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010553 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010554
10555 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10556 // A variable for which the type is pointer and an array section
10557 // derived from that variable must not appear as list items of map
10558 // clauses of the same construct.
10559 //
10560 // Also, cover one of the cases in:
10561 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10562 // If any part of the original storage of a list item has corresponding
10563 // storage in the device data environment, all of the original storage
10564 // must have corresponding storage in the device data environment.
10565 //
10566 if (DerivedType->isAnyPointerType()) {
10567 if (CI == CE || SI == SE) {
10568 SemaRef.Diag(
10569 DerivedLoc,
10570 diag::err_omp_pointer_mapped_along_with_derived_section)
10571 << DerivedLoc;
10572 } else {
10573 assert(CI != CE && SI != SE);
10574 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10575 << DerivedLoc;
10576 }
10577 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10578 << RE->getSourceRange();
10579 return true;
10580 }
10581
10582 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10583 // List items of map clauses in the same construct must not share
10584 // original storage.
10585 //
10586 // An expression is a subset of the other.
10587 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010588 if (CKind == OMPC_map)
10589 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10590 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010591 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010592 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10593 << ERange;
10594 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010595 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10596 << RE->getSourceRange();
10597 return true;
10598 }
10599
10600 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010601 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010602 if (!CurrentRegionOnly && SI != SE)
10603 EnclosingExpr = RE;
10604
10605 // The current expression is a subset of the expression in the data
10606 // environment.
10607 IsEnclosedByDataEnvironmentExpr |=
10608 (!CurrentRegionOnly && CI != CE && SI == SE);
10609
10610 return false;
10611 });
10612
10613 if (CurrentRegionOnly)
10614 return FoundError;
10615
10616 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10617 // If any part of the original storage of a list item has corresponding
10618 // storage in the device data environment, all of the original storage must
10619 // have corresponding storage in the device data environment.
10620 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10621 // If a list item is an element of a structure, and a different element of
10622 // the structure has a corresponding list item in the device data environment
10623 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010624 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010625 // data environment prior to the task encountering the construct.
10626 //
10627 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10628 SemaRef.Diag(ELoc,
10629 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10630 << ERange;
10631 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10632 << EnclosingExpr->getSourceRange();
10633 return true;
10634 }
10635
10636 return FoundError;
10637}
10638
Samuel Antao661c0902016-05-26 17:39:58 +000010639namespace {
10640// Utility struct that gathers all the related lists associated with a mappable
10641// expression.
10642struct MappableVarListInfo final {
10643 // The list of expressions.
10644 ArrayRef<Expr *> VarList;
10645 // The list of processed expressions.
10646 SmallVector<Expr *, 16> ProcessedVarList;
10647 // The mappble components for each expression.
10648 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10649 // The base declaration of the variable.
10650 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10651
10652 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10653 // We have a list of components and base declarations for each entry in the
10654 // variable list.
10655 VarComponents.reserve(VarList.size());
10656 VarBaseDeclarations.reserve(VarList.size());
10657 }
10658};
10659}
10660
10661// Check the validity of the provided variable list for the provided clause kind
10662// \a CKind. In the check process the valid expressions, and mappable expression
10663// components and variables are extracted and used to fill \a Vars,
10664// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10665// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10666static void
10667checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10668 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10669 SourceLocation StartLoc,
10670 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10671 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010672 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10673 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010674 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010675
Samuel Antao90927002016-04-26 14:54:23 +000010676 // Keep track of the mappable components and base declarations in this clause.
10677 // Each entry in the list is going to have a list of components associated. We
10678 // record each set of the components so that we can build the clause later on.
10679 // In the end we should have the same amount of declarations and component
10680 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010681
Samuel Antao661c0902016-05-26 17:39:58 +000010682 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010683 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010684 SourceLocation ELoc = RE->getExprLoc();
10685
Kelvin Li0bff7af2015-11-23 05:32:03 +000010686 auto *VE = RE->IgnoreParenLValueCasts();
10687
10688 if (VE->isValueDependent() || VE->isTypeDependent() ||
10689 VE->isInstantiationDependent() ||
10690 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010691 // We can only analyze this information once the missing information is
10692 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010693 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010694 continue;
10695 }
10696
10697 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010698
Samuel Antao5de996e2016-01-22 20:21:36 +000010699 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010700 SemaRef.Diag(ELoc,
10701 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010702 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010703 continue;
10704 }
10705
Samuel Antao90927002016-04-26 14:54:23 +000010706 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10707 ValueDecl *CurDeclaration = nullptr;
10708
10709 // Obtain the array or member expression bases if required. Also, fill the
10710 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010711 auto *BE =
10712 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010713 if (!BE)
10714 continue;
10715
Samuel Antao90927002016-04-26 14:54:23 +000010716 assert(!CurComponents.empty() &&
10717 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010718
Samuel Antao90927002016-04-26 14:54:23 +000010719 // For the following checks, we rely on the base declaration which is
10720 // expected to be associated with the last component. The declaration is
10721 // expected to be a variable or a field (if 'this' is being mapped).
10722 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10723 assert(CurDeclaration && "Null decl on map clause.");
10724 assert(
10725 CurDeclaration->isCanonicalDecl() &&
10726 "Expecting components to have associated only canonical declarations.");
10727
10728 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10729 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010730
10731 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010732 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010733
10734 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010735 // threadprivate variables cannot appear in a map clause.
10736 // OpenMP 4.5 [2.10.5, target update Construct]
10737 // threadprivate variables cannot appear in a from clause.
10738 if (VD && DSAS->isThreadPrivate(VD)) {
10739 auto DVar = DSAS->getTopDSA(VD, false);
10740 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10741 << getOpenMPClauseName(CKind);
10742 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010743 continue;
10744 }
10745
Samuel Antao5de996e2016-01-22 20:21:36 +000010746 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10747 // A list item cannot appear in both a map clause and a data-sharing
10748 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010749
Samuel Antao5de996e2016-01-22 20:21:36 +000010750 // Check conflicts with other map clause expressions. We check the conflicts
10751 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010752 // environment, because the restrictions are different. We only have to
10753 // check conflicts across regions for the map clauses.
10754 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10755 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010756 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010757 if (CKind == OMPC_map &&
10758 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10759 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010760 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010761
Samuel Antao661c0902016-05-26 17:39:58 +000010762 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010763 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10764 // If the type of a list item is a reference to a type T then the type will
10765 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010766 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010767
Samuel Antao661c0902016-05-26 17:39:58 +000010768 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10769 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010770 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010771 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010772 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10773 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010774 continue;
10775
Samuel Antao661c0902016-05-26 17:39:58 +000010776 if (CKind == OMPC_map) {
10777 // target enter data
10778 // OpenMP [2.10.2, Restrictions, p. 99]
10779 // A map-type must be specified in all map clauses and must be either
10780 // to or alloc.
10781 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10782 if (DKind == OMPD_target_enter_data &&
10783 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10784 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10785 << (IsMapTypeImplicit ? 1 : 0)
10786 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10787 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010788 continue;
10789 }
Samuel Antao661c0902016-05-26 17:39:58 +000010790
10791 // target exit_data
10792 // OpenMP [2.10.3, Restrictions, p. 102]
10793 // A map-type must be specified in all map clauses and must be either
10794 // from, release, or delete.
10795 if (DKind == OMPD_target_exit_data &&
10796 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10797 MapType == OMPC_MAP_delete)) {
10798 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10799 << (IsMapTypeImplicit ? 1 : 0)
10800 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10801 << getOpenMPDirectiveName(DKind);
10802 continue;
10803 }
10804
10805 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10806 // A list item cannot appear in both a map clause and a data-sharing
10807 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010808 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010809 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010810 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010811 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10812 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010813 auto DVar = DSAS->getTopDSA(VD, false);
10814 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010815 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010816 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010817 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010818 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10819 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10820 continue;
10821 }
10822 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010823 }
10824
Samuel Antao90927002016-04-26 14:54:23 +000010825 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010826 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010827
10828 // Store the components in the stack so that they can be used to check
10829 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010830 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10831 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010832
10833 // Save the components and declaration to create the clause. For purposes of
10834 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010835 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010836 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10837 MVLI.VarComponents.back().append(CurComponents.begin(),
10838 CurComponents.end());
10839 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10840 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010841 }
Samuel Antao661c0902016-05-26 17:39:58 +000010842}
10843
10844OMPClause *
10845Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10846 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10847 SourceLocation MapLoc, SourceLocation ColonLoc,
10848 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10849 SourceLocation LParenLoc, SourceLocation EndLoc) {
10850 MappableVarListInfo MVLI(VarList);
10851 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10852 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010853
Samuel Antao5de996e2016-01-22 20:21:36 +000010854 // We need to produce a map clause even if we don't have variables so that
10855 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010856 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10857 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10858 MVLI.VarComponents, MapTypeModifier, MapType,
10859 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010860}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010861
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010862QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10863 TypeResult ParsedType) {
10864 assert(ParsedType.isUsable());
10865
10866 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10867 if (ReductionType.isNull())
10868 return QualType();
10869
10870 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10871 // A type name in a declare reduction directive cannot be a function type, an
10872 // array type, a reference type, or a type qualified with const, volatile or
10873 // restrict.
10874 if (ReductionType.hasQualifiers()) {
10875 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10876 return QualType();
10877 }
10878
10879 if (ReductionType->isFunctionType()) {
10880 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10881 return QualType();
10882 }
10883 if (ReductionType->isReferenceType()) {
10884 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10885 return QualType();
10886 }
10887 if (ReductionType->isArrayType()) {
10888 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10889 return QualType();
10890 }
10891 return ReductionType;
10892}
10893
10894Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10895 Scope *S, DeclContext *DC, DeclarationName Name,
10896 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10897 AccessSpecifier AS, Decl *PrevDeclInScope) {
10898 SmallVector<Decl *, 8> Decls;
10899 Decls.reserve(ReductionTypes.size());
10900
10901 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10902 ForRedeclaration);
10903 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10904 // A reduction-identifier may not be re-declared in the current scope for the
10905 // same type or for a type that is compatible according to the base language
10906 // rules.
10907 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10908 OMPDeclareReductionDecl *PrevDRD = nullptr;
10909 bool InCompoundScope = true;
10910 if (S != nullptr) {
10911 // Find previous declaration with the same name not referenced in other
10912 // declarations.
10913 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10914 InCompoundScope =
10915 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10916 LookupName(Lookup, S);
10917 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10918 /*AllowInlineNamespace=*/false);
10919 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10920 auto Filter = Lookup.makeFilter();
10921 while (Filter.hasNext()) {
10922 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10923 if (InCompoundScope) {
10924 auto I = UsedAsPrevious.find(PrevDecl);
10925 if (I == UsedAsPrevious.end())
10926 UsedAsPrevious[PrevDecl] = false;
10927 if (auto *D = PrevDecl->getPrevDeclInScope())
10928 UsedAsPrevious[D] = true;
10929 }
10930 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10931 PrevDecl->getLocation();
10932 }
10933 Filter.done();
10934 if (InCompoundScope) {
10935 for (auto &PrevData : UsedAsPrevious) {
10936 if (!PrevData.second) {
10937 PrevDRD = PrevData.first;
10938 break;
10939 }
10940 }
10941 }
10942 } else if (PrevDeclInScope != nullptr) {
10943 auto *PrevDRDInScope = PrevDRD =
10944 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10945 do {
10946 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10947 PrevDRDInScope->getLocation();
10948 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10949 } while (PrevDRDInScope != nullptr);
10950 }
10951 for (auto &TyData : ReductionTypes) {
10952 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10953 bool Invalid = false;
10954 if (I != PreviousRedeclTypes.end()) {
10955 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10956 << TyData.first;
10957 Diag(I->second, diag::note_previous_definition);
10958 Invalid = true;
10959 }
10960 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10961 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10962 Name, TyData.first, PrevDRD);
10963 DC->addDecl(DRD);
10964 DRD->setAccess(AS);
10965 Decls.push_back(DRD);
10966 if (Invalid)
10967 DRD->setInvalidDecl();
10968 else
10969 PrevDRD = DRD;
10970 }
10971
10972 return DeclGroupPtrTy::make(
10973 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10974}
10975
10976void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10977 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10978
10979 // Enter new function scope.
10980 PushFunctionScope();
10981 getCurFunction()->setHasBranchProtectedScope();
10982 getCurFunction()->setHasOMPDeclareReductionCombiner();
10983
10984 if (S != nullptr)
10985 PushDeclContext(S, DRD);
10986 else
10987 CurContext = DRD;
10988
Faisal Valid143a0c2017-04-01 21:30:49 +000010989 PushExpressionEvaluationContext(
10990 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010991
10992 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010993 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10994 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10995 // uses semantics of argument handles by value, but it should be passed by
10996 // reference. C lang does not support references, so pass all parameters as
10997 // pointers.
10998 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010999 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011000 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011001 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11002 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11003 // uses semantics of argument handles by value, but it should be passed by
11004 // reference. C lang does not support references, so pass all parameters as
11005 // pointers.
11006 // Create 'T omp_out;' variable.
11007 auto *OmpOutParm =
11008 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11009 if (S != nullptr) {
11010 PushOnScopeChains(OmpInParm, S);
11011 PushOnScopeChains(OmpOutParm, S);
11012 } else {
11013 DRD->addDecl(OmpInParm);
11014 DRD->addDecl(OmpOutParm);
11015 }
11016}
11017
11018void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11019 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11020 DiscardCleanupsInEvaluationContext();
11021 PopExpressionEvaluationContext();
11022
11023 PopDeclContext();
11024 PopFunctionScopeInfo();
11025
11026 if (Combiner != nullptr)
11027 DRD->setCombiner(Combiner);
11028 else
11029 DRD->setInvalidDecl();
11030}
11031
11032void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11033 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11034
11035 // Enter new function scope.
11036 PushFunctionScope();
11037 getCurFunction()->setHasBranchProtectedScope();
11038
11039 if (S != nullptr)
11040 PushDeclContext(S, DRD);
11041 else
11042 CurContext = DRD;
11043
Faisal Valid143a0c2017-04-01 21:30:49 +000011044 PushExpressionEvaluationContext(
11045 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011046
11047 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011048 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11049 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11050 // uses semantics of argument handles by value, but it should be passed by
11051 // reference. C lang does not support references, so pass all parameters as
11052 // pointers.
11053 // Create 'T omp_priv;' variable.
11054 auto *OmpPrivParm =
11055 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011056 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11057 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11058 // uses semantics of argument handles by value, but it should be passed by
11059 // reference. C lang does not support references, so pass all parameters as
11060 // pointers.
11061 // Create 'T omp_orig;' variable.
11062 auto *OmpOrigParm =
11063 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011064 if (S != nullptr) {
11065 PushOnScopeChains(OmpPrivParm, S);
11066 PushOnScopeChains(OmpOrigParm, S);
11067 } else {
11068 DRD->addDecl(OmpPrivParm);
11069 DRD->addDecl(OmpOrigParm);
11070 }
11071}
11072
11073void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11074 Expr *Initializer) {
11075 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11076 DiscardCleanupsInEvaluationContext();
11077 PopExpressionEvaluationContext();
11078
11079 PopDeclContext();
11080 PopFunctionScopeInfo();
11081
11082 if (Initializer != nullptr)
11083 DRD->setInitializer(Initializer);
11084 else
11085 DRD->setInvalidDecl();
11086}
11087
11088Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11089 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11090 for (auto *D : DeclReductions.get()) {
11091 if (IsValid) {
11092 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11093 if (S != nullptr)
11094 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11095 } else
11096 D->setInvalidDecl();
11097 }
11098 return DeclReductions;
11099}
11100
David Majnemer9d168222016-08-05 17:44:54 +000011101OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011102 SourceLocation StartLoc,
11103 SourceLocation LParenLoc,
11104 SourceLocation EndLoc) {
11105 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011106 Stmt *HelperValStmt = nullptr;
11107 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011108
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011109 // OpenMP [teams Constrcut, Restrictions]
11110 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011111 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11112 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011113 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011114
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011115 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11116 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11117 if (CaptureRegion != OMPD_unknown) {
11118 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11119 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11120 HelperValStmt = buildPreInits(Context, Captures);
11121 }
11122
11123 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11124 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011125}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011126
11127OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11128 SourceLocation StartLoc,
11129 SourceLocation LParenLoc,
11130 SourceLocation EndLoc) {
11131 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011132 Stmt *HelperValStmt = nullptr;
11133 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011134
11135 // OpenMP [teams Constrcut, Restrictions]
11136 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011137 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11138 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011139 return nullptr;
11140
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011141 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11142 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11143 if (CaptureRegion != OMPD_unknown) {
11144 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11145 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11146 HelperValStmt = buildPreInits(Context, Captures);
11147 }
11148
11149 return new (Context) OMPThreadLimitClause(
11150 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011151}
Alexey Bataeva0569352015-12-01 10:17:31 +000011152
11153OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11154 SourceLocation StartLoc,
11155 SourceLocation LParenLoc,
11156 SourceLocation EndLoc) {
11157 Expr *ValExpr = Priority;
11158
11159 // OpenMP [2.9.1, task Constrcut]
11160 // The priority-value is a non-negative numerical scalar expression.
11161 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11162 /*StrictlyPositive=*/false))
11163 return nullptr;
11164
11165 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11166}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011167
11168OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11169 SourceLocation StartLoc,
11170 SourceLocation LParenLoc,
11171 SourceLocation EndLoc) {
11172 Expr *ValExpr = Grainsize;
11173
11174 // OpenMP [2.9.2, taskloop Constrcut]
11175 // The parameter of the grainsize clause must be a positive integer
11176 // expression.
11177 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11178 /*StrictlyPositive=*/true))
11179 return nullptr;
11180
11181 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11182}
Alexey Bataev382967a2015-12-08 12:06:20 +000011183
11184OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11185 SourceLocation StartLoc,
11186 SourceLocation LParenLoc,
11187 SourceLocation EndLoc) {
11188 Expr *ValExpr = NumTasks;
11189
11190 // OpenMP [2.9.2, taskloop Constrcut]
11191 // The parameter of the num_tasks clause must be a positive integer
11192 // expression.
11193 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11194 /*StrictlyPositive=*/true))
11195 return nullptr;
11196
11197 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11198}
11199
Alexey Bataev28c75412015-12-15 08:19:24 +000011200OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11201 SourceLocation LParenLoc,
11202 SourceLocation EndLoc) {
11203 // OpenMP [2.13.2, critical construct, Description]
11204 // ... where hint-expression is an integer constant expression that evaluates
11205 // to a valid lock hint.
11206 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11207 if (HintExpr.isInvalid())
11208 return nullptr;
11209 return new (Context)
11210 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11211}
11212
Carlo Bertollib4adf552016-01-15 18:50:31 +000011213OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11214 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11215 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11216 SourceLocation EndLoc) {
11217 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11218 std::string Values;
11219 Values += "'";
11220 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11221 Values += "'";
11222 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11223 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11224 return nullptr;
11225 }
11226 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011227 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011228 if (ChunkSize) {
11229 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11230 !ChunkSize->isInstantiationDependent() &&
11231 !ChunkSize->containsUnexpandedParameterPack()) {
11232 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11233 ExprResult Val =
11234 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11235 if (Val.isInvalid())
11236 return nullptr;
11237
11238 ValExpr = Val.get();
11239
11240 // OpenMP [2.7.1, Restrictions]
11241 // chunk_size must be a loop invariant integer expression with a positive
11242 // value.
11243 llvm::APSInt Result;
11244 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11245 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11246 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11247 << "dist_schedule" << ChunkSize->getSourceRange();
11248 return nullptr;
11249 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011250 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11251 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011252 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11253 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11254 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011255 }
11256 }
11257 }
11258
11259 return new (Context)
11260 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011261 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011262}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011263
11264OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11265 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11266 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11267 SourceLocation KindLoc, SourceLocation EndLoc) {
11268 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011269 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011270 std::string Value;
11271 SourceLocation Loc;
11272 Value += "'";
11273 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11274 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011275 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011276 Loc = MLoc;
11277 } else {
11278 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011279 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011280 Loc = KindLoc;
11281 }
11282 Value += "'";
11283 Diag(Loc, diag::err_omp_unexpected_clause_value)
11284 << Value << getOpenMPClauseName(OMPC_defaultmap);
11285 return nullptr;
11286 }
11287
11288 return new (Context)
11289 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11290}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011291
11292bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11293 DeclContext *CurLexicalContext = getCurLexicalContext();
11294 if (!CurLexicalContext->isFileContext() &&
11295 !CurLexicalContext->isExternCContext() &&
11296 !CurLexicalContext->isExternCXXContext()) {
11297 Diag(Loc, diag::err_omp_region_not_file_context);
11298 return false;
11299 }
11300 if (IsInOpenMPDeclareTargetContext) {
11301 Diag(Loc, diag::err_omp_enclosed_declare_target);
11302 return false;
11303 }
11304
11305 IsInOpenMPDeclareTargetContext = true;
11306 return true;
11307}
11308
11309void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11310 assert(IsInOpenMPDeclareTargetContext &&
11311 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11312
11313 IsInOpenMPDeclareTargetContext = false;
11314}
11315
David Majnemer9d168222016-08-05 17:44:54 +000011316void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11317 CXXScopeSpec &ScopeSpec,
11318 const DeclarationNameInfo &Id,
11319 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11320 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011321 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11322 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11323
11324 if (Lookup.isAmbiguous())
11325 return;
11326 Lookup.suppressDiagnostics();
11327
11328 if (!Lookup.isSingleResult()) {
11329 if (TypoCorrection Corrected =
11330 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11331 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11332 CTK_ErrorRecovery)) {
11333 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11334 << Id.getName());
11335 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11336 return;
11337 }
11338
11339 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11340 return;
11341 }
11342
11343 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11344 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11345 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11346 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11347
11348 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11349 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11350 ND->addAttr(A);
11351 if (ASTMutationListener *ML = Context.getASTMutationListener())
11352 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11353 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11354 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11355 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11356 << Id.getName();
11357 }
11358 } else
11359 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11360}
11361
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011362static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11363 Sema &SemaRef, Decl *D) {
11364 if (!D)
11365 return;
11366 Decl *LD = nullptr;
11367 if (isa<TagDecl>(D)) {
11368 LD = cast<TagDecl>(D)->getDefinition();
11369 } else if (isa<VarDecl>(D)) {
11370 LD = cast<VarDecl>(D)->getDefinition();
11371
11372 // If this is an implicit variable that is legal and we do not need to do
11373 // anything.
11374 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011375 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11376 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11377 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011378 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011379 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011380 return;
11381 }
11382
11383 } else if (isa<FunctionDecl>(D)) {
11384 const FunctionDecl *FD = nullptr;
11385 if (cast<FunctionDecl>(D)->hasBody(FD))
11386 LD = const_cast<FunctionDecl *>(FD);
11387
11388 // If the definition is associated with the current declaration in the
11389 // target region (it can be e.g. a lambda) that is legal and we do not need
11390 // to do anything else.
11391 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011392 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11393 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11394 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011395 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011396 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011397 return;
11398 }
11399 }
11400 if (!LD)
11401 LD = D;
11402 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11403 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11404 // Outlined declaration is not declared target.
11405 if (LD->isOutOfLine()) {
11406 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11407 SemaRef.Diag(SL, diag::note_used_here) << SR;
11408 } else {
11409 DeclContext *DC = LD->getDeclContext();
11410 while (DC) {
11411 if (isa<FunctionDecl>(DC) &&
11412 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11413 break;
11414 DC = DC->getParent();
11415 }
11416 if (DC)
11417 return;
11418
11419 // Is not declared in target context.
11420 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11421 SemaRef.Diag(SL, diag::note_used_here) << SR;
11422 }
11423 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011424 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11425 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11426 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011427 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011428 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011429 }
11430}
11431
11432static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11433 Sema &SemaRef, DSAStackTy *Stack,
11434 ValueDecl *VD) {
11435 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11436 return true;
11437 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11438 return false;
11439 return true;
11440}
11441
11442void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11443 if (!D || D->isInvalidDecl())
11444 return;
11445 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11446 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11447 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11448 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11449 if (DSAStack->isThreadPrivate(VD)) {
11450 Diag(SL, diag::err_omp_threadprivate_in_target);
11451 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11452 return;
11453 }
11454 }
11455 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11456 // Problem if any with var declared with incomplete type will be reported
11457 // as normal, so no need to check it here.
11458 if ((E || !VD->getType()->isIncompleteType()) &&
11459 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11460 // Mark decl as declared target to prevent further diagnostic.
11461 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011462 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11463 Context, OMPDeclareTargetDeclAttr::MT_To);
11464 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011465 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011466 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011467 }
11468 return;
11469 }
11470 }
11471 if (!E) {
11472 // Checking declaration inside declare target region.
11473 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11474 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011475 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11476 Context, OMPDeclareTargetDeclAttr::MT_To);
11477 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011478 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011479 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011480 }
11481 return;
11482 }
11483 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11484}
Samuel Antao661c0902016-05-26 17:39:58 +000011485
11486OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11487 SourceLocation StartLoc,
11488 SourceLocation LParenLoc,
11489 SourceLocation EndLoc) {
11490 MappableVarListInfo MVLI(VarList);
11491 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11492 if (MVLI.ProcessedVarList.empty())
11493 return nullptr;
11494
11495 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11496 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11497 MVLI.VarComponents);
11498}
Samuel Antaoec172c62016-05-26 17:49:04 +000011499
11500OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11501 SourceLocation StartLoc,
11502 SourceLocation LParenLoc,
11503 SourceLocation EndLoc) {
11504 MappableVarListInfo MVLI(VarList);
11505 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11506 if (MVLI.ProcessedVarList.empty())
11507 return nullptr;
11508
11509 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11510 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11511 MVLI.VarComponents);
11512}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011513
11514OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11515 SourceLocation StartLoc,
11516 SourceLocation LParenLoc,
11517 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011518 MappableVarListInfo MVLI(VarList);
11519 SmallVector<Expr *, 8> PrivateCopies;
11520 SmallVector<Expr *, 8> Inits;
11521
Carlo Bertolli2404b172016-07-13 15:37:16 +000011522 for (auto &RefExpr : VarList) {
11523 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11524 SourceLocation ELoc;
11525 SourceRange ERange;
11526 Expr *SimpleRefExpr = RefExpr;
11527 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11528 if (Res.second) {
11529 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011530 MVLI.ProcessedVarList.push_back(RefExpr);
11531 PrivateCopies.push_back(nullptr);
11532 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011533 }
11534 ValueDecl *D = Res.first;
11535 if (!D)
11536 continue;
11537
11538 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011539 Type = Type.getNonReferenceType().getUnqualifiedType();
11540
11541 auto *VD = dyn_cast<VarDecl>(D);
11542
11543 // Item should be a pointer or reference to pointer.
11544 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011545 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11546 << 0 << RefExpr->getSourceRange();
11547 continue;
11548 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011549
11550 // Build the private variable and the expression that refers to it.
11551 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11552 D->hasAttrs() ? &D->getAttrs() : nullptr);
11553 if (VDPrivate->isInvalidDecl())
11554 continue;
11555
11556 CurContext->addDecl(VDPrivate);
11557 auto VDPrivateRefExpr = buildDeclRefExpr(
11558 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11559
11560 // Add temporary variable to initialize the private copy of the pointer.
11561 auto *VDInit =
11562 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11563 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11564 RefExpr->getExprLoc());
11565 AddInitializerToDecl(VDPrivate,
11566 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011567 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011568
11569 // If required, build a capture to implement the privatization initialized
11570 // with the current list item value.
11571 DeclRefExpr *Ref = nullptr;
11572 if (!VD)
11573 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11574 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11575 PrivateCopies.push_back(VDPrivateRefExpr);
11576 Inits.push_back(VDInitRefExpr);
11577
11578 // We need to add a data sharing attribute for this variable to make sure it
11579 // is correctly captured. A variable that shows up in a use_device_ptr has
11580 // similar properties of a first private variable.
11581 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11582
11583 // Create a mappable component for the list item. List items in this clause
11584 // only need a component.
11585 MVLI.VarBaseDeclarations.push_back(D);
11586 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11587 MVLI.VarComponents.back().push_back(
11588 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011589 }
11590
Samuel Antaocc10b852016-07-28 14:23:26 +000011591 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011592 return nullptr;
11593
Samuel Antaocc10b852016-07-28 14:23:26 +000011594 return OMPUseDevicePtrClause::Create(
11595 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11596 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011597}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011598
11599OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11600 SourceLocation StartLoc,
11601 SourceLocation LParenLoc,
11602 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011603 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011604 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011605 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011606 SourceLocation ELoc;
11607 SourceRange ERange;
11608 Expr *SimpleRefExpr = RefExpr;
11609 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11610 if (Res.second) {
11611 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011612 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011613 }
11614 ValueDecl *D = Res.first;
11615 if (!D)
11616 continue;
11617
11618 QualType Type = D->getType();
11619 // item should be a pointer or array or reference to pointer or array
11620 if (!Type.getNonReferenceType()->isPointerType() &&
11621 !Type.getNonReferenceType()->isArrayType()) {
11622 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11623 << 0 << RefExpr->getSourceRange();
11624 continue;
11625 }
Samuel Antao6890b092016-07-28 14:25:09 +000011626
11627 // Check if the declaration in the clause does not show up in any data
11628 // sharing attribute.
11629 auto DVar = DSAStack->getTopDSA(D, false);
11630 if (isOpenMPPrivate(DVar.CKind)) {
11631 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11632 << getOpenMPClauseName(DVar.CKind)
11633 << getOpenMPClauseName(OMPC_is_device_ptr)
11634 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11635 ReportOriginalDSA(*this, DSAStack, D, DVar);
11636 continue;
11637 }
11638
11639 Expr *ConflictExpr;
11640 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011641 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011642 [&ConflictExpr](
11643 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11644 OpenMPClauseKind) -> bool {
11645 ConflictExpr = R.front().getAssociatedExpression();
11646 return true;
11647 })) {
11648 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11649 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11650 << ConflictExpr->getSourceRange();
11651 continue;
11652 }
11653
11654 // Store the components in the stack so that they can be used to check
11655 // against other clauses later on.
11656 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11657 DSAStack->addMappableExpressionComponents(
11658 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11659
11660 // Record the expression we've just processed.
11661 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11662
11663 // Create a mappable component for the list item. List items in this clause
11664 // only need a component. We use a null declaration to signal fields in
11665 // 'this'.
11666 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11667 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11668 "Unexpected device pointer expression!");
11669 MVLI.VarBaseDeclarations.push_back(
11670 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11671 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11672 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011673 }
11674
Samuel Antao6890b092016-07-28 14:25:09 +000011675 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011676 return nullptr;
11677
Samuel Antao6890b092016-07-28 14:25:09 +000011678 return OMPIsDevicePtrClause::Create(
11679 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11680 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011681}