blob: 2b7733d2adbd2c5dd5d6f8c3bf0799e26284b3d9 [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 Bataev4b465392017-04-26 15:06:24 +0000122 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
123 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000124 /// \brief true, if check for DSA must be from parent directive, false, if
125 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000127 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000129 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130
131 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
132
David Majnemer9d168222016-08-05 17:44:54 +0000133 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000134
135 /// \brief Checks if the variable is a local for OpenMP region.
136 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000137
Alexey Bataev4b465392017-04-26 15:06:24 +0000138 bool isStackEmpty() const {
139 return Stack.empty() ||
140 Stack.back().second != CurrentNonCapturingFunctionScope ||
141 Stack.back().first.empty();
142 }
143
Alexey Bataev758e55e2013-09-06 18:03:48 +0000144public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000145 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000146
Alexey Bataevaac108a2015-06-23 04:51:00 +0000147 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
148 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000150 bool isForceVarCapturing() const { return ForceCapturing; }
151 void setForceVarCapturing(bool V) { ForceCapturing = V; }
152
Alexey Bataev758e55e2013-09-06 18:03:48 +0000153 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000154 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 if (Stack.empty() ||
156 Stack.back().second != CurrentNonCapturingFunctionScope)
157 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
158 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
159 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 }
161
162 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000163 assert(!Stack.back().first.empty() &&
164 "Data-sharing attributes stack is empty!");
165 Stack.back().first.pop_back();
166 }
167
168 /// Start new OpenMP region stack in new non-capturing function.
169 void pushFunction() {
170 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
171 assert(!isa<CapturingScopeInfo>(CurFnScope));
172 CurrentNonCapturingFunctionScope = CurFnScope;
173 }
174 /// Pop region stack for non-capturing function.
175 void popFunction(const FunctionScopeInfo *OldFSI) {
176 if (!Stack.empty() && Stack.back().second == OldFSI) {
177 assert(Stack.back().first.empty());
178 Stack.pop_back();
179 }
180 CurrentNonCapturingFunctionScope = nullptr;
181 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
182 if (!isa<CapturingScopeInfo>(FSI)) {
183 CurrentNonCapturingFunctionScope = FSI;
184 break;
185 }
186 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 }
188
Alexey Bataev28c75412015-12-15 08:19:24 +0000189 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
190 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
191 }
192 const std::pair<OMPCriticalDirective *, llvm::APSInt>
193 getCriticalWithHint(const DeclarationNameInfo &Name) const {
194 auto I = Criticals.find(Name.getAsString());
195 if (I != Criticals.end())
196 return I->second;
197 return std::make_pair(nullptr, llvm::APSInt());
198 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000199 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000200 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000201 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000202 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000203
Alexey Bataev9c821032015-04-30 04:23:23 +0000204 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000205 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000206 /// \brief Check if the specified variable is a loop control variable for
207 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000208 /// \return The index of the loop control variable in the list of associated
209 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000210 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000211 /// \brief Check if the specified variable is a loop control variable for
212 /// parent region.
213 /// \return The index of the loop control variable in the list of associated
214 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000215 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000216 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
217 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000218 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000219
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000221 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
222 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000223
Alexey Bataev758e55e2013-09-06 18:03:48 +0000224 /// \brief Returns data sharing attributes from top of the stack for the
225 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000226 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000227 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000228 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000229 /// \brief Checks if the specified variables has data-sharing attributes which
230 /// match specified \a CPred predicate in any directive which matches \a DPred
231 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000232 DSAVarData hasDSA(ValueDecl *D,
233 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
234 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
235 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000236 /// \brief Checks if the specified variables has data-sharing attributes which
237 /// match specified \a CPred predicate in any innermost directive which
238 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000239 DSAVarData
240 hasInnermostDSA(ValueDecl *D,
241 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
242 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
243 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000244 /// \brief Checks if the specified variables has explicit data-sharing
245 /// attributes which match specified \a CPred predicate at the specified
246 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000247 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000248 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000249 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000250
251 /// \brief Returns true if the directive at level \Level matches in the
252 /// specified \a DPred predicate.
253 bool hasExplicitDirective(
254 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
255 unsigned Level);
256
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000257 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000258 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
259 const DeclarationNameInfo &,
260 SourceLocation)> &DPred,
261 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000262
Alexey Bataev758e55e2013-09-06 18:03:48 +0000263 /// \brief Returns currently analyzed directive.
264 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000265 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000267 /// \brief Returns parent directive.
268 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000269 if (isStackEmpty() || Stack.back().first.size() == 1)
270 return OMPD_unknown;
271 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000272 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273
274 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000275 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000276 assert(!isStackEmpty());
277 Stack.back().first.back().DefaultAttr = DSA_none;
278 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000279 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000280 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000281 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000282 assert(!isStackEmpty());
283 Stack.back().first.back().DefaultAttr = DSA_shared;
284 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000285 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000286
287 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000288 return isStackEmpty() ? DSA_unspecified
289 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000291 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000292 return isStackEmpty() ? SourceLocation()
293 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000294 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000295
Alexey Bataevf29276e2014-06-18 04:14:57 +0000296 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000297 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000298 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000299 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000300 }
301
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000303 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000304 assert(!isStackEmpty());
305 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
306 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000307 }
308 /// \brief Returns true, if parent region is ordered (has associated
309 /// 'ordered' clause), false - otherwise.
310 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000311 if (isStackEmpty() || Stack.back().first.size() == 1)
312 return false;
313 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000314 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000315 /// \brief Returns optional parameter for the ordered region.
316 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000317 if (isStackEmpty() || Stack.back().first.size() == 1)
318 return nullptr;
319 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000320 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000321 /// \brief Marks current region as nowait (it has a 'nowait' clause).
322 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000323 assert(!isStackEmpty());
324 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000325 }
326 /// \brief Returns true, if parent region is nowait (has associated
327 /// 'nowait' clause), false - otherwise.
328 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000329 if (isStackEmpty() || Stack.back().first.size() == 1)
330 return false;
331 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000332 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000333 /// \brief Marks parent region as cancel region.
334 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 if (!isStackEmpty() && Stack.back().first.size() > 1) {
336 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
337 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
338 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000339 }
340 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000341 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000342 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000343 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000344
Alexey Bataev9c821032015-04-30 04:23:23 +0000345 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000346 void setAssociatedLoops(unsigned Val) {
347 assert(!isStackEmpty());
348 Stack.back().first.back().AssociatedLoops = Val;
349 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000350 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000351 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000352 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000353 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000354
Alexey Bataev13314bf2014-10-09 04:18:56 +0000355 /// \brief Marks current target region as one with closely nested teams
356 /// region.
357 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000358 if (!isStackEmpty() && Stack.back().first.size() > 1) {
359 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
360 TeamsRegionLoc;
361 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000362 }
363 /// \brief Returns true, if current region has closely nested teams region.
364 bool hasInnerTeamsRegion() const {
365 return getInnerTeamsRegionLoc().isValid();
366 }
367 /// \brief Returns location of the nested teams region (if any).
368 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000369 return isStackEmpty() ? SourceLocation()
370 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000371 }
372
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000373 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000374 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000375 }
376 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000377 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000378 }
379 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000380 return isStackEmpty() ? SourceLocation()
381 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000382 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000383
Samuel Antao4c8035b2016-12-12 18:00:20 +0000384 /// Do the check specified in \a Check to all component lists and return true
385 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000386 bool checkMappableExprComponentListsForDecl(
387 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000388 const llvm::function_ref<
389 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
390 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000391 if (isStackEmpty())
392 return false;
393 auto SI = Stack.back().first.rbegin();
394 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000395
396 if (SI == SE)
397 return false;
398
399 if (CurrentRegionOnly) {
400 SE = std::next(SI);
401 } else {
402 ++SI;
403 }
404
405 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000406 auto MI = SI->MappedExprComponents.find(VD);
407 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000408 for (auto &L : MI->second.Components)
409 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000410 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000411 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000412 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000413 }
414
Samuel Antao4c8035b2016-12-12 18:00:20 +0000415 /// Create a new mappable expression component list associated with a given
416 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000417 void addMappableExpressionComponents(
418 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000419 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
420 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000421 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000422 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000423 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000424 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000425 MEC.Components.resize(MEC.Components.size() + 1);
426 MEC.Components.back().append(Components.begin(), Components.end());
427 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000428 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000429
430 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000431 assert(!isStackEmpty());
432 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000433 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000434 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000435 assert(!isStackEmpty() && Stack.back().first.size() > 1);
436 auto &StackElem = *std::next(Stack.back().first.rbegin());
437 assert(isOpenMPWorksharingDirective(StackElem.Directive));
438 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000439 }
440 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
441 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000442 assert(!isStackEmpty());
443 auto &StackElem = Stack.back().first.back();
444 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
445 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000446 return llvm::make_range(Ref.begin(), Ref.end());
447 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000448 return llvm::make_range(StackElem.DoacrossDepends.end(),
449 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000450 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000451};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000452bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000453 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
454 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000455}
Alexey Bataeved09d242014-05-28 05:53:51 +0000456} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000457
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000458static ValueDecl *getCanonicalDecl(ValueDecl *D) {
459 auto *VD = dyn_cast<VarDecl>(D);
460 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000461 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000462 VD = VD->getCanonicalDecl();
463 D = VD;
464 } else {
465 assert(FD);
466 FD = FD->getCanonicalDecl();
467 D = FD;
468 }
469 return D;
470}
471
David Majnemer9d168222016-08-05 17:44:54 +0000472DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000473 ValueDecl *D) {
474 D = getCanonicalDecl(D);
475 auto *VD = dyn_cast<VarDecl>(D);
476 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000477 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000478 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000479 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
480 // in a region but not in construct]
481 // File-scope or namespace-scope variables referenced in called routines
482 // in the region are shared unless they appear in a threadprivate
483 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000484 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000485 DVar.CKind = OMPC_shared;
486
487 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
488 // in a region but not in construct]
489 // Variables with static storage duration that are declared in called
490 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000491 if (VD && VD->hasGlobalStorage())
492 DVar.CKind = OMPC_shared;
493
494 // Non-static data members are shared by default.
495 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000496 DVar.CKind = OMPC_shared;
497
Alexey Bataev758e55e2013-09-06 18:03:48 +0000498 return DVar;
499 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000500
Alexey Bataev758e55e2013-09-06 18:03:48 +0000501 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000502 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
503 // in a Construct, C/C++, predetermined, p.1]
504 // Variables with automatic storage duration that are declared in a scope
505 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000506 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
507 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000508 DVar.CKind = OMPC_private;
509 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000510 }
511
Alexey Bataev758e55e2013-09-06 18:03:48 +0000512 // Explicitly specified attributes and local variables with predetermined
513 // attributes.
514 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000515 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000516 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000518 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
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, C/C++, implicitly determined, p.1]
524 // In a parallel or task construct, the data-sharing attributes of these
525 // variables are determined by the default clause, if present.
526 switch (Iter->DefaultAttr) {
527 case DSA_shared:
528 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000529 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000530 return DVar;
531 case DSA_none:
532 return DVar;
533 case DSA_unspecified:
534 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
535 // in a Construct, implicitly determined, p.2]
536 // In a parallel construct, if no default clause is present, these
537 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000538 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000539 if (isOpenMPParallelDirective(DVar.DKind) ||
540 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000541 DVar.CKind = OMPC_shared;
542 return DVar;
543 }
544
545 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
546 // in a Construct, implicitly determined, p.4]
547 // In a task construct, if no default clause is present, a variable that in
548 // the enclosing context is determined to be shared by all implicit tasks
549 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000550 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000551 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000552 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000553 do {
554 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000555 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000556 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000557 // In a task construct, if no default clause is present, a variable
558 // whose data-sharing attribute is not determined by the rules above is
559 // firstprivate.
560 DVarTemp = getDSA(I, D);
561 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000562 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000563 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000564 return DVar;
565 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000566 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000567 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000568 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000569 return DVar;
570 }
571 }
572 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
573 // in a Construct, implicitly determined, p.3]
574 // For constructs other than task, if no default clause is present, these
575 // variables inherit their data-sharing attributes from the enclosing
576 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000577 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578}
579
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000581 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000582 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000583 auto &StackElem = Stack.back().first.back();
584 auto It = StackElem.AlignedMap.find(D);
585 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000586 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000587 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000588 return nullptr;
589 } else {
590 assert(It->second && "Unexpected nullptr expr in the aligned map");
591 return It->second;
592 }
593 return nullptr;
594}
595
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000596void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000597 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000598 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000599 auto &StackElem = Stack.back().first.back();
600 StackElem.LCVMap.insert(
601 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000602}
603
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000604DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000605 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000606 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000607 auto &StackElem = Stack.back().first.back();
608 auto It = StackElem.LCVMap.find(D);
609 if (It != StackElem.LCVMap.end())
610 return It->second;
611 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000612}
613
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000614DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000615 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
616 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000617 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000618 auto &StackElem = *std::next(Stack.back().first.rbegin());
619 auto It = StackElem.LCVMap.find(D);
620 if (It != StackElem.LCVMap.end())
621 return It->second;
622 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000623}
624
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000625ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000626 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
627 "Data-sharing attributes stack is empty");
628 auto &StackElem = *std::next(Stack.back().first.rbegin());
629 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000630 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000631 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000632 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000633 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000634 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000635}
636
Alexey Bataev90c228f2016-02-08 09:29:13 +0000637void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
638 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000639 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000640 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000641 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000642 Data.Attributes = A;
643 Data.RefExpr.setPointer(E);
644 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000645 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000646 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
647 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000648 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
649 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
650 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
651 (isLoopControlVariable(D).first && A == OMPC_private));
652 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
653 Data.RefExpr.setInt(/*IntVal=*/true);
654 return;
655 }
656 const bool IsLastprivate =
657 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
658 Data.Attributes = A;
659 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
660 Data.PrivateCopy = PrivateCopy;
661 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000662 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000663 Data.Attributes = A;
664 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
665 Data.PrivateCopy = nullptr;
666 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668}
669
Alexey Bataeved09d242014-05-28 05:53:51 +0000670bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000671 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000672 if (!isStackEmpty() && Stack.back().first.size() > 1) {
673 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000674 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000675 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000676 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000677 if (I == E)
678 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000679 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000680 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000681 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000682 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000683 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000684 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000685 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000686}
687
Alexey Bataev39f915b82015-05-08 10:41:21 +0000688/// \brief Build a variable declaration for OpenMP loop iteration variable.
689static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000690 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000691 DeclContext *DC = SemaRef.CurContext;
692 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
693 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
694 VarDecl *Decl =
695 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000696 if (Attrs) {
697 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
698 I != E; ++I)
699 Decl->addAttr(*I);
700 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000701 Decl->setImplicit();
702 return Decl;
703}
704
705static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
706 SourceLocation Loc,
707 bool RefersToCapture = false) {
708 D->setReferenced();
709 D->markUsed(S.Context);
710 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
711 SourceLocation(), D, RefersToCapture, Loc, Ty,
712 VK_LValue);
713}
714
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000715DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
716 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000717 DSAVarData DVar;
718
719 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
720 // in a Construct, C/C++, predetermined, p.1]
721 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000722 auto *VD = dyn_cast<VarDecl>(D);
723 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
724 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000725 SemaRef.getLangOpts().OpenMPUseTLS &&
726 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000727 (VD && VD->getStorageClass() == SC_Register &&
728 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
729 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000730 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000731 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000732 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000733 auto TI = Threadprivates.find(D);
734 if (TI != Threadprivates.end()) {
735 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 DVar.CKind = OMPC_threadprivate;
737 return DVar;
738 }
739
Alexey Bataev4b465392017-04-26 15:06:24 +0000740 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000741 // Not in OpenMP execution region and top scope was already checked.
742 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000743
Alexey Bataev758e55e2013-09-06 18:03:48 +0000744 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000745 // in a Construct, C/C++, predetermined, p.4]
746 // Static data members are shared.
747 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
748 // in a Construct, C/C++, predetermined, p.7]
749 // Variables with static storage duration that are declared in a scope
750 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000751 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000752 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000753 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000754 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000755 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000756
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000757 DVar.CKind = OMPC_shared;
758 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000759 }
760
761 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000762 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
763 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000764 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
765 // in a Construct, C/C++, predetermined, p.6]
766 // Variables with const qualified type having no mutable member are
767 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000768 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000769 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000770 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
771 if (auto *CTD = CTSD->getSpecializedTemplate())
772 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000773 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000774 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
775 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000776 // Variables with const-qualified type having no mutable member may be
777 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000778 DSAVarData DVarTemp = hasDSA(
779 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
780 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000781 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
782 return DVar;
783
Alexey Bataev758e55e2013-09-06 18:03:48 +0000784 DVar.CKind = OMPC_shared;
785 return DVar;
786 }
787
Alexey Bataev758e55e2013-09-06 18:03:48 +0000788 // Explicitly specified attributes and local variables with predetermined
789 // attributes.
Alexey Bataev4b465392017-04-26 15:06:24 +0000790 auto StartI = std::next(Stack.back().first.rbegin());
791 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000792 if (FromParent && StartI != EndI)
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000793 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000794 auto I = std::prev(StartI);
795 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000796 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000797 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000798 DVar.CKind = I->SharingMap[D].Attributes;
799 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000800 }
801
802 return DVar;
803}
804
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000805DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
806 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000807 if (isStackEmpty()) {
808 StackTy::reverse_iterator I;
809 return getDSA(I, D);
810 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000811 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000812 auto StartI = Stack.back().first.rbegin();
813 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000814 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000815 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000816 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000817}
818
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000819DSAStackTy::DSAVarData
820DSAStackTy::hasDSA(ValueDecl *D,
821 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
822 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
823 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000824 if (isStackEmpty())
825 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000826 D = getCanonicalDecl(D);
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +0000827 auto I = (FromParent && Stack.back().first.size() > 1)
828 ? std::next(Stack.back().first.rbegin())
829 : Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000830 auto EndI = Stack.back().first.rend();
Alexey Bataev60859c02017-04-27 15:10:33 +0000831 while (std::distance(I, EndI) > 1) {
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +0000832 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000833 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000834 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000835 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000836 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000837 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +0000838 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000839 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000840}
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
843 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
844 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
845 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000846 if (isStackEmpty())
847 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000848 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000849 auto StartI = std::next(Stack.back().first.rbegin());
850 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000851 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000852 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000853 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +0000854 return {};
Alexey Bataeve3978122016-07-19 05:06:39 +0000855 DSAVarData DVar = getDSA(StartI, D);
856 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000857}
858
Alexey Bataevaac108a2015-06-23 04:51:00 +0000859bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000860 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000861 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000862 if (CPred(ClauseKindMode))
863 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000864 if (isStackEmpty())
865 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000866 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000867 auto StartI = Stack.back().first.begin();
868 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000869 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000870 return false;
871 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000872 return (StartI->SharingMap.count(D) > 0) &&
873 StartI->SharingMap[D].RefExpr.getPointer() &&
874 CPred(StartI->SharingMap[D].Attributes) &&
875 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000876}
877
Samuel Antao4be30e92015-10-02 17:14:03 +0000878bool DSAStackTy::hasExplicitDirective(
879 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
880 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000881 if (isStackEmpty())
882 return false;
883 auto StartI = Stack.back().first.begin();
884 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000885 if (std::distance(StartI, EndI) <= (int)Level)
886 return false;
887 std::advance(StartI, Level);
888 return DPred(StartI->Directive);
889}
890
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000891bool DSAStackTy::hasDirective(
892 const llvm::function_ref<bool(OpenMPDirectiveKind,
893 const DeclarationNameInfo &, SourceLocation)>
894 &DPred,
895 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000896 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000897 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +0000898 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +0000899 auto StartI = std::next(Stack.back().first.rbegin());
900 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000901 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000902 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000903 for (auto I = StartI, EE = EndI; I != EE; ++I) {
904 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
905 return true;
906 }
907 return false;
908}
909
Alexey Bataev758e55e2013-09-06 18:03:48 +0000910void Sema::InitDataSharingAttributesStack() {
911 VarDataSharingAttributesStack = new DSAStackTy(*this);
912}
913
914#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
915
Alexey Bataev4b465392017-04-26 15:06:24 +0000916void Sema::pushOpenMPFunctionRegion() {
917 DSAStack->pushFunction();
918}
919
920void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
921 DSAStack->popFunction(OldFSI);
922}
923
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000924bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000925 assert(LangOpts.OpenMP && "OpenMP is not allowed");
926
927 auto &Ctx = getASTContext();
928 bool IsByRef = true;
929
930 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000931 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000932
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000933 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000934 // This table summarizes how a given variable should be passed to the device
935 // given its type and the clauses where it appears. This table is based on
936 // the description in OpenMP 4.5 [2.10.4, target Construct] and
937 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
938 //
939 // =========================================================================
940 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
941 // | |(tofrom:scalar)| | pvt | | | |
942 // =========================================================================
943 // | scl | | | | - | | bycopy|
944 // | scl | | - | x | - | - | bycopy|
945 // | scl | | x | - | - | - | null |
946 // | scl | x | | | - | | byref |
947 // | scl | x | - | x | - | - | bycopy|
948 // | scl | x | x | - | - | - | null |
949 // | scl | | - | - | - | x | byref |
950 // | scl | x | - | - | - | x | byref |
951 //
952 // | agg | n.a. | | | - | | byref |
953 // | agg | n.a. | - | x | - | - | byref |
954 // | agg | n.a. | x | - | - | - | null |
955 // | agg | n.a. | - | - | - | x | byref |
956 // | agg | n.a. | - | - | - | x[] | byref |
957 //
958 // | ptr | n.a. | | | - | | bycopy|
959 // | ptr | n.a. | - | x | - | - | bycopy|
960 // | ptr | n.a. | x | - | - | - | null |
961 // | ptr | n.a. | - | - | - | x | byref |
962 // | ptr | n.a. | - | - | - | x[] | bycopy|
963 // | ptr | n.a. | - | - | x | | bycopy|
964 // | ptr | n.a. | - | - | x | x | bycopy|
965 // | ptr | n.a. | - | - | x | x[] | bycopy|
966 // =========================================================================
967 // Legend:
968 // scl - scalar
969 // ptr - pointer
970 // agg - aggregate
971 // x - applies
972 // - - invalid in this combination
973 // [] - mapped with an array section
974 // byref - should be mapped by reference
975 // byval - should be mapped by value
976 // null - initialize a local variable to null on the device
977 //
978 // Observations:
979 // - All scalar declarations that show up in a map clause have to be passed
980 // by reference, because they may have been mapped in the enclosing data
981 // environment.
982 // - If the scalar value does not fit the size of uintptr, it has to be
983 // passed by reference, regardless the result in the table above.
984 // - For pointers mapped by value that have either an implicit map or an
985 // array section, the runtime library may pass the NULL value to the
986 // device instead of the value passed to it by the compiler.
987
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000988 if (Ty->isReferenceType())
989 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000990
991 // Locate map clauses and see if the variable being captured is referred to
992 // in any of those clauses. Here we only care about variables, not fields,
993 // because fields are part of aggregates.
994 bool IsVariableUsedInMapClause = false;
995 bool IsVariableAssociatedWithSection = false;
996
997 DSAStack->checkMappableExprComponentListsForDecl(
998 D, /*CurrentRegionOnly=*/true,
999 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001000 MapExprComponents,
1001 OpenMPClauseKind WhereFoundClauseKind) {
1002 // Only the map clause information influences how a variable is
1003 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001004 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001005 if (WhereFoundClauseKind != OMPC_map)
1006 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001007
1008 auto EI = MapExprComponents.rbegin();
1009 auto EE = MapExprComponents.rend();
1010
1011 assert(EI != EE && "Invalid map expression!");
1012
1013 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1014 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1015
1016 ++EI;
1017 if (EI == EE)
1018 return false;
1019
1020 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1021 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1022 isa<MemberExpr>(EI->getAssociatedExpression())) {
1023 IsVariableAssociatedWithSection = true;
1024 // There is nothing more we need to know about this variable.
1025 return true;
1026 }
1027
1028 // Keep looking for more map info.
1029 return false;
1030 });
1031
1032 if (IsVariableUsedInMapClause) {
1033 // If variable is identified in a map clause it is always captured by
1034 // reference except if it is a pointer that is dereferenced somehow.
1035 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1036 } else {
1037 // By default, all the data that has a scalar type is mapped by copy.
1038 IsByRef = !Ty->isScalarType();
1039 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001040 }
1041
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001042 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1043 IsByRef = !DSAStack->hasExplicitDSA(
1044 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1045 Level, /*NotLastprivate=*/true);
1046 }
1047
Samuel Antao86ace552016-04-27 22:40:57 +00001048 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001049 // and alignment, because the runtime library only deals with uintptr types.
1050 // If it does not fit the uintptr size, we need to pass the data by reference
1051 // instead.
1052 if (!IsByRef &&
1053 (Ctx.getTypeSizeInChars(Ty) >
1054 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001055 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001056 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001057 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001058
1059 return IsByRef;
1060}
1061
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001062unsigned Sema::getOpenMPNestingLevel() const {
1063 assert(getLangOpts().OpenMP);
1064 return DSAStack->getNestingLevel();
1065}
1066
Alexey Bataev90c228f2016-02-08 09:29:13 +00001067VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001068 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001069 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001070
1071 // If we are attempting to capture a global variable in a directive with
1072 // 'target' we return true so that this global is also mapped to the device.
1073 //
1074 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1075 // then it should not be captured. Therefore, an extra check has to be
1076 // inserted here once support for 'declare target' is added.
1077 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001078 auto *VD = dyn_cast<VarDecl>(D);
1079 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001080 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001081 !DSAStack->isClauseParsingMode())
1082 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001083 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001084 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1085 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001086 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001087 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001088 false))
1089 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001090 }
1091
Alexey Bataev48977c32015-08-04 08:10:48 +00001092 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1093 (!DSAStack->isClauseParsingMode() ||
1094 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001095 auto &&Info = DSAStack->isLoopControlVariable(D);
1096 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001097 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001098 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001099 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001100 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001101 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001102 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001103 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001104 DVarPrivate = DSAStack->hasDSA(
1105 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1106 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001107 if (DVarPrivate.CKind != OMPC_unknown)
1108 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001109 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001110 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001111}
1112
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001113bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001114 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1115 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001116 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001117}
1118
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001119bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001120 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1121 // Return true if the current level is no longer enclosed in a target region.
1122
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001123 auto *VD = dyn_cast<VarDecl>(D);
1124 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001125 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1126 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001127}
1128
Alexey Bataeved09d242014-05-28 05:53:51 +00001129void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001130
1131void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1132 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001133 Scope *CurScope, SourceLocation Loc) {
1134 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001135 PushExpressionEvaluationContext(
1136 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001137}
1138
Alexey Bataevaac108a2015-06-23 04:51:00 +00001139void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1140 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001141}
1142
Alexey Bataevaac108a2015-06-23 04:51:00 +00001143void Sema::EndOpenMPClause() {
1144 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001145}
1146
Alexey Bataev758e55e2013-09-06 18:03:48 +00001147void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001148 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1149 // A variable of class type (or array thereof) that appears in a lastprivate
1150 // clause requires an accessible, unambiguous default constructor for the
1151 // class type, unless the list item is also specified in a firstprivate
1152 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001153 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001154 for (auto *C : D->clauses()) {
1155 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1156 SmallVector<Expr *, 8> PrivateCopies;
1157 for (auto *DE : Clause->varlists()) {
1158 if (DE->isValueDependent() || DE->isTypeDependent()) {
1159 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001160 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001161 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001162 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001163 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1164 QualType Type = VD->getType().getNonReferenceType();
1165 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001166 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001167 // Generate helper private variable and initialize it with the
1168 // default value. The address of the original variable is replaced
1169 // by the address of the new private variable in CodeGen. This new
1170 // variable is not added to IdResolver, so the code in the OpenMP
1171 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001172 auto *VDPrivate = buildVarDecl(
1173 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001174 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001175 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001176 if (VDPrivate->isInvalidDecl())
1177 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001178 PrivateCopies.push_back(buildDeclRefExpr(
1179 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001180 } else {
1181 // The variable is also a firstprivate, so initialization sequence
1182 // for private copy is generated already.
1183 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001184 }
1185 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001186 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001187 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001188 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001189 }
1190 }
1191 }
1192
Alexey Bataev758e55e2013-09-06 18:03:48 +00001193 DSAStack->pop();
1194 DiscardCleanupsInEvaluationContext();
1195 PopExpressionEvaluationContext();
1196}
1197
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001198static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1199 Expr *NumIterations, Sema &SemaRef,
1200 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001201
Alexey Bataeva769e072013-03-22 06:34:35 +00001202namespace {
1203
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001204class VarDeclFilterCCC : public CorrectionCandidateCallback {
1205private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001206 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001207
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001208public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001209 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001210 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001211 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001212 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001213 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001214 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1215 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001216 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001217 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001218 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001219};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001220
1221class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1222private:
1223 Sema &SemaRef;
1224
1225public:
1226 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1227 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1228 NamedDecl *ND = Candidate.getCorrectionDecl();
1229 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1230 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1231 SemaRef.getCurScope());
1232 }
1233 return false;
1234 }
1235};
1236
Alexey Bataeved09d242014-05-28 05:53:51 +00001237} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001238
1239ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1240 CXXScopeSpec &ScopeSpec,
1241 const DeclarationNameInfo &Id) {
1242 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1243 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1244
1245 if (Lookup.isAmbiguous())
1246 return ExprError();
1247
1248 VarDecl *VD;
1249 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001250 if (TypoCorrection Corrected = CorrectTypo(
1251 Id, LookupOrdinaryName, CurScope, nullptr,
1252 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001253 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001254 PDiag(Lookup.empty()
1255 ? diag::err_undeclared_var_use_suggest
1256 : diag::err_omp_expected_var_arg_suggest)
1257 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001258 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001259 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001260 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1261 : diag::err_omp_expected_var_arg)
1262 << Id.getName();
1263 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001264 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001265 } else {
1266 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001267 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001268 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1269 return ExprError();
1270 }
1271 }
1272 Lookup.suppressDiagnostics();
1273
1274 // OpenMP [2.9.2, Syntax, C/C++]
1275 // Variables must be file-scope, namespace-scope, or static block-scope.
1276 if (!VD->hasGlobalStorage()) {
1277 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001278 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1279 bool IsDecl =
1280 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001281 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001282 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1283 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001284 return ExprError();
1285 }
1286
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001287 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1288 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001289 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1290 // A threadprivate directive for file-scope variables must appear outside
1291 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001292 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1293 !getCurLexicalContext()->isTranslationUnit()) {
1294 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001295 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1296 bool IsDecl =
1297 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1298 Diag(VD->getLocation(),
1299 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1300 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001301 return ExprError();
1302 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001303 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1304 // A threadprivate directive for static class member variables must appear
1305 // in the class definition, in the same scope in which the member
1306 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001307 if (CanonicalVD->isStaticDataMember() &&
1308 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1309 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001310 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1311 bool IsDecl =
1312 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1313 Diag(VD->getLocation(),
1314 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1315 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001316 return ExprError();
1317 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001318 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1319 // A threadprivate directive for namespace-scope variables must appear
1320 // outside any definition or declaration other than the namespace
1321 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001322 if (CanonicalVD->getDeclContext()->isNamespace() &&
1323 (!getCurLexicalContext()->isFileContext() ||
1324 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1325 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001326 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1327 bool IsDecl =
1328 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1329 Diag(VD->getLocation(),
1330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1331 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001332 return ExprError();
1333 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001334 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1335 // A threadprivate directive for static block-scope variables must appear
1336 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001337 if (CanonicalVD->isStaticLocal() && CurScope &&
1338 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001339 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001340 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1341 bool IsDecl =
1342 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1343 Diag(VD->getLocation(),
1344 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1345 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001346 return ExprError();
1347 }
1348
1349 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1350 // A threadprivate directive must lexically precede all references to any
1351 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001352 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001353 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001354 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001355 return ExprError();
1356 }
1357
1358 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001359 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1360 SourceLocation(), VD,
1361 /*RefersToEnclosingVariableOrCapture=*/false,
1362 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001363}
1364
Alexey Bataeved09d242014-05-28 05:53:51 +00001365Sema::DeclGroupPtrTy
1366Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1367 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001368 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001369 CurContext->addDecl(D);
1370 return DeclGroupPtrTy::make(DeclGroupRef(D));
1371 }
David Blaikie0403cb12016-01-15 23:43:25 +00001372 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001373}
1374
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001375namespace {
1376class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1377 Sema &SemaRef;
1378
1379public:
1380 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001381 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001382 if (VD->hasLocalStorage()) {
1383 SemaRef.Diag(E->getLocStart(),
1384 diag::err_omp_local_var_in_threadprivate_init)
1385 << E->getSourceRange();
1386 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1387 << VD << VD->getSourceRange();
1388 return true;
1389 }
1390 }
1391 return false;
1392 }
1393 bool VisitStmt(const Stmt *S) {
1394 for (auto Child : S->children()) {
1395 if (Child && Visit(Child))
1396 return true;
1397 }
1398 return false;
1399 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001400 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001401};
1402} // namespace
1403
Alexey Bataeved09d242014-05-28 05:53:51 +00001404OMPThreadPrivateDecl *
1405Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001406 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001407 for (auto &RefExpr : VarList) {
1408 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001409 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1410 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001411
Alexey Bataev376b4a42016-02-09 09:41:09 +00001412 // Mark variable as used.
1413 VD->setReferenced();
1414 VD->markUsed(Context);
1415
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001416 QualType QType = VD->getType();
1417 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1418 // It will be analyzed later.
1419 Vars.push_back(DE);
1420 continue;
1421 }
1422
Alexey Bataeva769e072013-03-22 06:34:35 +00001423 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1424 // A threadprivate variable must not have an incomplete type.
1425 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001426 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001427 continue;
1428 }
1429
1430 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1431 // A threadprivate variable must not have a reference type.
1432 if (VD->getType()->isReferenceType()) {
1433 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001434 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1435 bool IsDecl =
1436 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1437 Diag(VD->getLocation(),
1438 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1439 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001440 continue;
1441 }
1442
Samuel Antaof8b50122015-07-13 22:54:53 +00001443 // Check if this is a TLS variable. If TLS is not being supported, produce
1444 // the corresponding diagnostic.
1445 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1446 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1447 getLangOpts().OpenMPUseTLS &&
1448 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001449 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1450 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001451 Diag(ILoc, diag::err_omp_var_thread_local)
1452 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001453 bool IsDecl =
1454 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1455 Diag(VD->getLocation(),
1456 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1457 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001458 continue;
1459 }
1460
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001461 // Check if initial value of threadprivate variable reference variable with
1462 // local storage (it is not supported by runtime).
1463 if (auto Init = VD->getAnyInitializer()) {
1464 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001465 if (Checker.Visit(Init))
1466 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001467 }
1468
Alexey Bataeved09d242014-05-28 05:53:51 +00001469 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001470 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001471 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1472 Context, SourceRange(Loc, Loc)));
1473 if (auto *ML = Context.getASTMutationListener())
1474 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001475 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001476 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001477 if (!Vars.empty()) {
1478 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1479 Vars);
1480 D->setAccess(AS_public);
1481 }
1482 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001483}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001484
Alexey Bataev7ff55242014-06-19 09:13:45 +00001485static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001486 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001487 bool IsLoopIterVar = false) {
1488 if (DVar.RefExpr) {
1489 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1490 << getOpenMPClauseName(DVar.CKind);
1491 return;
1492 }
1493 enum {
1494 PDSA_StaticMemberShared,
1495 PDSA_StaticLocalVarShared,
1496 PDSA_LoopIterVarPrivate,
1497 PDSA_LoopIterVarLinear,
1498 PDSA_LoopIterVarLastprivate,
1499 PDSA_ConstVarShared,
1500 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001501 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001502 PDSA_LocalVarPrivate,
1503 PDSA_Implicit
1504 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001505 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001506 auto ReportLoc = D->getLocation();
1507 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 if (IsLoopIterVar) {
1509 if (DVar.CKind == OMPC_private)
1510 Reason = PDSA_LoopIterVarPrivate;
1511 else if (DVar.CKind == OMPC_lastprivate)
1512 Reason = PDSA_LoopIterVarLastprivate;
1513 else
1514 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1516 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 Reason = PDSA_TaskVarFirstprivate;
1518 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001519 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001520 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001521 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001522 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001523 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001524 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001525 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001526 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001527 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001528 ReportHint = true;
1529 Reason = PDSA_LocalVarPrivate;
1530 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001531 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001532 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001533 << Reason << ReportHint
1534 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1535 } else if (DVar.ImplicitDSALoc.isValid()) {
1536 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1537 << getOpenMPClauseName(DVar.CKind);
1538 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001539}
1540
Alexey Bataev758e55e2013-09-06 18:03:48 +00001541namespace {
1542class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1543 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001544 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001545 bool ErrorFound;
1546 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001547 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001548 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001549
Alexey Bataev758e55e2013-09-06 18:03:48 +00001550public:
1551 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001552 if (E->isTypeDependent() || E->isValueDependent() ||
1553 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1554 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001555 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001556 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001557 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1558 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001559
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001560 auto DVar = Stack->getTopDSA(VD, false);
1561 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001562 if (DVar.RefExpr)
1563 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001564
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001565 auto ELoc = E->getExprLoc();
1566 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001567 // The default(none) clause requires that each variable that is referenced
1568 // in the construct, and does not have a predetermined data-sharing
1569 // attribute, must have its data-sharing attribute explicitly determined
1570 // by being listed in a data-sharing attribute clause.
1571 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001572 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001573 VarsWithInheritedDSA.count(VD) == 0) {
1574 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001575 return;
1576 }
1577
1578 // OpenMP [2.9.3.6, Restrictions, p.2]
1579 // A list item that appears in a reduction clause of the innermost
1580 // enclosing worksharing or parallel construct may not be accessed in an
1581 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001582 DVar = Stack->hasInnermostDSA(
1583 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1584 [](OpenMPDirectiveKind K) -> bool {
1585 return isOpenMPParallelDirective(K) ||
1586 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1587 },
1588 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001589 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001590 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001591 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1592 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001593 return;
1594 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001595
1596 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001597 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001598 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1599 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001600 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001601 }
1602 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001603 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001604 if (E->isTypeDependent() || E->isValueDependent() ||
1605 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1606 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001607 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1608 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1609 auto DVar = Stack->getTopDSA(FD, false);
1610 // Check if the variable has explicit DSA set and stop analysis if it
1611 // so.
1612 if (DVar.RefExpr)
1613 return;
1614
1615 auto ELoc = E->getExprLoc();
1616 auto DKind = Stack->getCurrentDirective();
1617 // OpenMP [2.9.3.6, Restrictions, p.2]
1618 // A list item that appears in a reduction clause of the innermost
1619 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001620 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001621 DVar = Stack->hasInnermostDSA(
1622 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1623 [](OpenMPDirectiveKind K) -> bool {
1624 return isOpenMPParallelDirective(K) ||
1625 isOpenMPWorksharingDirective(K) ||
1626 isOpenMPTeamsDirective(K);
1627 },
1628 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001629 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001630 ErrorFound = true;
1631 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1632 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1633 return;
1634 }
1635
1636 // Define implicit data-sharing attributes for task.
1637 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001638 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1639 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001640 ImplicitFirstprivate.push_back(E);
1641 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001642 } else
1643 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001644 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001645 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001646 for (auto *C : S->clauses()) {
1647 // Skip analysis of arguments of implicitly defined firstprivate clause
1648 // for task directives.
1649 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1650 for (auto *CC : C->children()) {
1651 if (CC)
1652 Visit(CC);
1653 }
1654 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001655 }
1656 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001657 for (auto *C : S->children()) {
1658 if (C && !isa<OMPExecutableDirective>(C))
1659 Visit(C);
1660 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001661 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001662
1663 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001664 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001665 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001666 return VarsWithInheritedDSA;
1667 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001668
Alexey Bataev7ff55242014-06-19 09:13:45 +00001669 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1670 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001671};
Alexey Bataeved09d242014-05-28 05:53:51 +00001672} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001673
Alexey Bataevbae9a792014-06-27 10:37:06 +00001674void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001675 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001676 case OMPD_parallel:
1677 case OMPD_parallel_for:
1678 case OMPD_parallel_for_simd:
1679 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001680 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001681 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001682 QualType KmpInt32PtrTy =
1683 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001684 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001685 std::make_pair(".global_tid.", KmpInt32PtrTy),
1686 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1687 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001688 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001689 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1690 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001691 break;
1692 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001693 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001694 case OMPD_target_parallel: {
1695 Sema::CapturedParamNameType ParamsTarget[] = {
1696 std::make_pair(StringRef(), QualType()) // __context with shared vars
1697 };
1698 // Start a captured region for 'target' with no implicit parameters.
1699 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1700 ParamsTarget);
1701 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1702 QualType KmpInt32PtrTy =
1703 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001704 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001705 std::make_pair(".global_tid.", KmpInt32PtrTy),
1706 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1707 std::make_pair(StringRef(), QualType()) // __context with shared vars
1708 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001709 // Start a captured region for 'teams' or 'parallel'. Both regions have
1710 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001711 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001712 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001713 break;
1714 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001715 case OMPD_simd:
1716 case OMPD_for:
1717 case OMPD_for_simd:
1718 case OMPD_sections:
1719 case OMPD_section:
1720 case OMPD_single:
1721 case OMPD_master:
1722 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001723 case OMPD_taskgroup:
1724 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001725 case OMPD_ordered:
1726 case OMPD_atomic:
1727 case OMPD_target_data:
1728 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001729 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001730 case OMPD_target_parallel_for_simd:
1731 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001732 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001733 std::make_pair(StringRef(), QualType()) // __context with shared vars
1734 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001735 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1736 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001737 break;
1738 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001739 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001740 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001741 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1742 FunctionProtoType::ExtProtoInfo EPI;
1743 EPI.Variadic = true;
1744 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001745 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001746 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001747 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1748 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1749 std::make_pair(".copy_fn.",
1750 Context.getPointerType(CopyFnType).withConst()),
1751 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001752 std::make_pair(StringRef(), QualType()) // __context with shared vars
1753 };
1754 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1755 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001756 // Mark this captured region as inlined, because we don't use outlined
1757 // function directly.
1758 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1759 AlwaysInlineAttr::CreateImplicit(
1760 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001761 break;
1762 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001763 case OMPD_taskloop:
1764 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001765 QualType KmpInt32Ty =
1766 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1767 QualType KmpUInt64Ty =
1768 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1769 QualType KmpInt64Ty =
1770 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1771 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1772 FunctionProtoType::ExtProtoInfo EPI;
1773 EPI.Variadic = true;
1774 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001775 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001776 std::make_pair(".global_tid.", KmpInt32Ty),
1777 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1778 std::make_pair(".privates.",
1779 Context.VoidPtrTy.withConst().withRestrict()),
1780 std::make_pair(
1781 ".copy_fn.",
1782 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1783 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1784 std::make_pair(".lb.", KmpUInt64Ty),
1785 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1786 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001787 std::make_pair(StringRef(), QualType()) // __context with shared vars
1788 };
1789 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1790 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001791 // Mark this captured region as inlined, because we don't use outlined
1792 // function directly.
1793 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1794 AlwaysInlineAttr::CreateImplicit(
1795 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001796 break;
1797 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001798 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001799 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001800 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001801 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001802 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001803 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001804 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001805 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001806 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001807 case OMPD_target_teams_distribute_parallel_for_simd:
1808 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001809 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1810 QualType KmpInt32PtrTy =
1811 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1812 Sema::CapturedParamNameType Params[] = {
1813 std::make_pair(".global_tid.", KmpInt32PtrTy),
1814 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1815 std::make_pair(".previous.lb.", Context.getSizeType()),
1816 std::make_pair(".previous.ub.", Context.getSizeType()),
1817 std::make_pair(StringRef(), QualType()) // __context with shared vars
1818 };
1819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1820 Params);
1821 break;
1822 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001823 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001824 case OMPD_taskyield:
1825 case OMPD_barrier:
1826 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001827 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001828 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001829 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001830 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001831 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001832 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001833 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001834 case OMPD_declare_target:
1835 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001836 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001837 llvm_unreachable("OpenMP Directive is not allowed");
1838 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001839 llvm_unreachable("Unknown OpenMP directive");
1840 }
1841}
1842
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001843int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1844 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1845 getOpenMPCaptureRegions(CaptureRegions, DKind);
1846 return CaptureRegions.size();
1847}
1848
Alexey Bataev3392d762016-02-16 11:18:12 +00001849static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001850 Expr *CaptureExpr, bool WithInit,
1851 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001852 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001853 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001854 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001855 QualType Ty = Init->getType();
1856 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1857 if (S.getLangOpts().CPlusPlus)
1858 Ty = C.getLValueReferenceType(Ty);
1859 else {
1860 Ty = C.getPointerType(Ty);
1861 ExprResult Res =
1862 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1863 if (!Res.isUsable())
1864 return nullptr;
1865 Init = Res.get();
1866 }
Alexey Bataev61205072016-03-02 04:57:40 +00001867 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001868 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001869 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1870 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001871 if (!WithInit)
1872 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001873 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001874 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001875 return CED;
1876}
1877
Alexey Bataev61205072016-03-02 04:57:40 +00001878static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1879 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001880 OMPCapturedExprDecl *CD;
1881 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1882 CD = cast<OMPCapturedExprDecl>(VD);
1883 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001884 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1885 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001886 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001887 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001888}
1889
Alexey Bataev5a3af132016-03-29 08:58:54 +00001890static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1891 if (!Ref) {
1892 auto *CD =
1893 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1894 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1895 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1896 CaptureExpr->getExprLoc());
1897 }
1898 ExprResult Res = Ref;
1899 if (!S.getLangOpts().CPlusPlus &&
1900 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1901 Ref->getType()->isPointerType())
1902 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1903 if (!Res.isUsable())
1904 return ExprError();
1905 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001906}
1907
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001908namespace {
1909// OpenMP directives parsed in this section are represented as a
1910// CapturedStatement with an associated statement. If a syntax error
1911// is detected during the parsing of the associated statement, the
1912// compiler must abort processing and close the CapturedStatement.
1913//
1914// Combined directives such as 'target parallel' have more than one
1915// nested CapturedStatements. This RAII ensures that we unwind out
1916// of all the nested CapturedStatements when an error is found.
1917class CaptureRegionUnwinderRAII {
1918private:
1919 Sema &S;
1920 bool &ErrorFound;
1921 OpenMPDirectiveKind DKind;
1922
1923public:
1924 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1925 OpenMPDirectiveKind DKind)
1926 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1927 ~CaptureRegionUnwinderRAII() {
1928 if (ErrorFound) {
1929 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1930 while (--ThisCaptureLevel >= 0)
1931 S.ActOnCapturedRegionError();
1932 }
1933 }
1934};
1935} // namespace
1936
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001937StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1938 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001939 bool ErrorFound = false;
1940 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1941 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001942 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001943 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001944 return StmtError();
1945 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001946
1947 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001948 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001949 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001950 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001951 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001952 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001953 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001954 Clause->getClauseKind() == OMPC_copyprivate ||
1955 (getLangOpts().OpenMPUseTLS &&
1956 getASTContext().getTargetInfo().isTLSSupported() &&
1957 Clause->getClauseKind() == OMPC_copyin)) {
1958 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001959 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001960 for (auto *VarRef : Clause->children()) {
1961 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001962 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001963 }
1964 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001965 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001966 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001967 if (auto *C = OMPClauseWithPreInit::get(Clause))
1968 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001969 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1970 if (auto *E = C->getPostUpdateExpr())
1971 MarkDeclarationsReferencedInExpr(E);
1972 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001973 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001974 if (Clause->getClauseKind() == OMPC_schedule)
1975 SC = cast<OMPScheduleClause>(Clause);
1976 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001977 OC = cast<OMPOrderedClause>(Clause);
1978 else if (Clause->getClauseKind() == OMPC_linear)
1979 LCs.push_back(cast<OMPLinearClause>(Clause));
1980 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001981 // OpenMP, 2.7.1 Loop Construct, Restrictions
1982 // The nonmonotonic modifier cannot be specified if an ordered clause is
1983 // specified.
1984 if (SC &&
1985 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1986 SC->getSecondScheduleModifier() ==
1987 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1988 OC) {
1989 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1990 ? SC->getFirstScheduleModifierLoc()
1991 : SC->getSecondScheduleModifierLoc(),
1992 diag::err_omp_schedule_nonmonotonic_ordered)
1993 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1994 ErrorFound = true;
1995 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001996 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1997 for (auto *C : LCs) {
1998 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1999 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2000 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002001 ErrorFound = true;
2002 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002003 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2004 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2005 OC->getNumForLoops()) {
2006 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2007 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2008 ErrorFound = true;
2009 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002010 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002011 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002012 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002013 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002014 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2015 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2016 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2017 // Mark all variables in private list clauses as used in inner region.
2018 // Required for proper codegen of combined directives.
2019 // TODO: add processing for other clauses.
2020 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2021 for (auto *C : PICs) {
2022 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2023 // Find the particular capture region for the clause if the
2024 // directive is a combined one with multiple capture regions.
2025 // If the directive is not a combined one, the capture region
2026 // associated with the clause is OMPD_unknown and is generated
2027 // only once.
2028 if (CaptureRegion == ThisCaptureRegion ||
2029 CaptureRegion == OMPD_unknown) {
2030 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2031 for (auto *D : DS->decls())
2032 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2033 }
2034 }
2035 }
2036 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002037 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002038 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002039 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002040}
2041
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002042static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2043 OpenMPDirectiveKind CancelRegion,
2044 SourceLocation StartLoc) {
2045 // CancelRegion is only needed for cancel and cancellation_point.
2046 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2047 return false;
2048
2049 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2050 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2051 return false;
2052
2053 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2054 << getOpenMPDirectiveName(CancelRegion);
2055 return true;
2056}
2057
2058static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002059 OpenMPDirectiveKind CurrentRegion,
2060 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002061 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002062 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002063 if (Stack->getCurScope()) {
2064 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002065 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002066 bool NestingProhibited = false;
2067 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002068 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002069 enum {
2070 NoRecommend,
2071 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002072 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002073 ShouldBeInTargetRegion,
2074 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002075 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002076 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002077 // OpenMP [2.16, Nesting of Regions]
2078 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002079 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002080 // An ordered construct with the simd clause is the only OpenMP
2081 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002082 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002083 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2084 // message.
2085 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2086 ? diag::err_omp_prohibited_region_simd
2087 : diag::warn_omp_nesting_simd);
2088 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002089 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002090 if (ParentRegion == OMPD_atomic) {
2091 // OpenMP [2.16, Nesting of Regions]
2092 // OpenMP constructs may not be nested inside an atomic region.
2093 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2094 return true;
2095 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002096 if (CurrentRegion == OMPD_section) {
2097 // OpenMP [2.7.2, sections Construct, Restrictions]
2098 // Orphaned section directives are prohibited. That is, the section
2099 // directives must appear within the sections construct and must not be
2100 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002101 if (ParentRegion != OMPD_sections &&
2102 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002103 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2104 << (ParentRegion != OMPD_unknown)
2105 << getOpenMPDirectiveName(ParentRegion);
2106 return true;
2107 }
2108 return false;
2109 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002110 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002111 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002112 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002113 if (ParentRegion == OMPD_unknown &&
2114 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002115 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002116 if (CurrentRegion == OMPD_cancellation_point ||
2117 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002118 // OpenMP [2.16, Nesting of Regions]
2119 // A cancellation point construct for which construct-type-clause is
2120 // taskgroup must be nested inside a task construct. A cancellation
2121 // point construct for which construct-type-clause is not taskgroup must
2122 // be closely nested inside an OpenMP construct that matches the type
2123 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002124 // A cancel construct for which construct-type-clause is taskgroup must be
2125 // nested inside a task construct. A cancel construct for which
2126 // construct-type-clause is not taskgroup must be closely nested inside an
2127 // OpenMP construct that matches the type specified in
2128 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002129 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002130 !((CancelRegion == OMPD_parallel &&
2131 (ParentRegion == OMPD_parallel ||
2132 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002133 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002134 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2135 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002136 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2137 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002138 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2139 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002140 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002141 // OpenMP [2.16, Nesting of Regions]
2142 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002143 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002144 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002145 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002146 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2147 // OpenMP [2.16, Nesting of Regions]
2148 // A critical region may not be nested (closely or otherwise) inside a
2149 // critical region with the same name. Note that this restriction is not
2150 // sufficient to prevent deadlock.
2151 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002152 bool DeadLock = Stack->hasDirective(
2153 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2154 const DeclarationNameInfo &DNI,
2155 SourceLocation Loc) -> bool {
2156 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2157 PreviousCriticalLoc = Loc;
2158 return true;
2159 } else
2160 return false;
2161 },
2162 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002163 if (DeadLock) {
2164 SemaRef.Diag(StartLoc,
2165 diag::err_omp_prohibited_region_critical_same_name)
2166 << CurrentName.getName();
2167 if (PreviousCriticalLoc.isValid())
2168 SemaRef.Diag(PreviousCriticalLoc,
2169 diag::note_omp_previous_critical_region);
2170 return true;
2171 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002172 } else if (CurrentRegion == OMPD_barrier) {
2173 // OpenMP [2.16, Nesting of Regions]
2174 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002175 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002176 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2177 isOpenMPTaskingDirective(ParentRegion) ||
2178 ParentRegion == OMPD_master ||
2179 ParentRegion == OMPD_critical ||
2180 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002181 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002182 !isOpenMPParallelDirective(CurrentRegion) &&
2183 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002184 // OpenMP [2.16, Nesting of Regions]
2185 // A worksharing region may not be closely nested inside a worksharing,
2186 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002187 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2188 isOpenMPTaskingDirective(ParentRegion) ||
2189 ParentRegion == OMPD_master ||
2190 ParentRegion == OMPD_critical ||
2191 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002192 Recommend = ShouldBeInParallelRegion;
2193 } else if (CurrentRegion == OMPD_ordered) {
2194 // OpenMP [2.16, Nesting of Regions]
2195 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002196 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002197 // An ordered region must be closely nested inside a loop region (or
2198 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002199 // OpenMP [2.8.1,simd Construct, Restrictions]
2200 // An ordered construct with the simd clause is the only OpenMP construct
2201 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002202 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002203 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002204 !(isOpenMPSimdDirective(ParentRegion) ||
2205 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002206 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002207 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002208 // OpenMP [2.16, Nesting of Regions]
2209 // If specified, a teams construct must be contained within a target
2210 // construct.
2211 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002212 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002213 Recommend = ShouldBeInTargetRegion;
2214 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2215 }
Kelvin Libf594a52016-12-17 05:48:59 +00002216 if (!NestingProhibited &&
2217 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2218 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2219 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002220 // OpenMP [2.16, Nesting of Regions]
2221 // distribute, parallel, parallel sections, parallel workshare, and the
2222 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2223 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002224 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2225 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002226 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002227 }
David Majnemer9d168222016-08-05 17:44:54 +00002228 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002229 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002230 // OpenMP 4.5 [2.17 Nesting of Regions]
2231 // The region associated with the distribute construct must be strictly
2232 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002233 NestingProhibited =
2234 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002235 Recommend = ShouldBeInTeamsRegion;
2236 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002237 if (!NestingProhibited &&
2238 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2239 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2240 // OpenMP 4.5 [2.17 Nesting of Regions]
2241 // If a target, target update, target data, target enter data, or
2242 // target exit data construct is encountered during execution of a
2243 // target region, the behavior is unspecified.
2244 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002245 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2246 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002247 if (isOpenMPTargetExecutionDirective(K)) {
2248 OffendingRegion = K;
2249 return true;
2250 } else
2251 return false;
2252 },
2253 false /* don't skip top directive */);
2254 CloseNesting = false;
2255 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002256 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002257 if (OrphanSeen) {
2258 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2259 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2260 } else {
2261 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2262 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2263 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2264 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002265 return true;
2266 }
2267 }
2268 return false;
2269}
2270
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002271static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2272 ArrayRef<OMPClause *> Clauses,
2273 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2274 bool ErrorFound = false;
2275 unsigned NamedModifiersNumber = 0;
2276 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2277 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002278 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002279 for (const auto *C : Clauses) {
2280 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2281 // At most one if clause without a directive-name-modifier can appear on
2282 // the directive.
2283 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2284 if (FoundNameModifiers[CurNM]) {
2285 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2286 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2287 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2288 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002289 } else if (CurNM != OMPD_unknown) {
2290 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002291 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002292 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002293 FoundNameModifiers[CurNM] = IC;
2294 if (CurNM == OMPD_unknown)
2295 continue;
2296 // Check if the specified name modifier is allowed for the current
2297 // directive.
2298 // At most one if clause with the particular directive-name-modifier can
2299 // appear on the directive.
2300 bool MatchFound = false;
2301 for (auto NM : AllowedNameModifiers) {
2302 if (CurNM == NM) {
2303 MatchFound = true;
2304 break;
2305 }
2306 }
2307 if (!MatchFound) {
2308 S.Diag(IC->getNameModifierLoc(),
2309 diag::err_omp_wrong_if_directive_name_modifier)
2310 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2311 ErrorFound = true;
2312 }
2313 }
2314 }
2315 // If any if clause on the directive includes a directive-name-modifier then
2316 // all if clauses on the directive must include a directive-name-modifier.
2317 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2318 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2319 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2320 diag::err_omp_no_more_if_clause);
2321 } else {
2322 std::string Values;
2323 std::string Sep(", ");
2324 unsigned AllowedCnt = 0;
2325 unsigned TotalAllowedNum =
2326 AllowedNameModifiers.size() - NamedModifiersNumber;
2327 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2328 ++Cnt) {
2329 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2330 if (!FoundNameModifiers[NM]) {
2331 Values += "'";
2332 Values += getOpenMPDirectiveName(NM);
2333 Values += "'";
2334 if (AllowedCnt + 2 == TotalAllowedNum)
2335 Values += " or ";
2336 else if (AllowedCnt + 1 != TotalAllowedNum)
2337 Values += Sep;
2338 ++AllowedCnt;
2339 }
2340 }
2341 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2342 diag::err_omp_unnamed_if_clause)
2343 << (TotalAllowedNum > 1) << Values;
2344 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002345 for (auto Loc : NameModifierLoc) {
2346 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2347 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002348 ErrorFound = true;
2349 }
2350 return ErrorFound;
2351}
2352
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002353StmtResult Sema::ActOnOpenMPExecutableDirective(
2354 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2355 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2356 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002357 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002358 // First check CancelRegion which is then used in checkNestingOfRegions.
2359 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2360 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002361 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002362 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002363
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002364 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002365 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002366 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002367 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002368 if (AStmt) {
2369 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2370
2371 // Check default data sharing attributes for referenced variables.
2372 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002373 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2374 Stmt *S = AStmt;
2375 while (--ThisCaptureLevel >= 0)
2376 S = cast<CapturedStmt>(S)->getCapturedStmt();
2377 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002378 if (DSAChecker.isErrorFound())
2379 return StmtError();
2380 // Generate list of implicitly defined firstprivate variables.
2381 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002382
2383 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2384 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2385 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2386 SourceLocation(), SourceLocation())) {
2387 ClausesWithImplicit.push_back(Implicit);
2388 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2389 DSAChecker.getImplicitFirstprivate().size();
2390 } else
2391 ErrorFound = true;
2392 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002393 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002394
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002395 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002396 switch (Kind) {
2397 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002398 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2399 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002400 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002401 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002402 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002403 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2404 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002405 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002406 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002407 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2408 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002409 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002410 case OMPD_for_simd:
2411 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2412 EndLoc, VarsWithInheritedDSA);
2413 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002414 case OMPD_sections:
2415 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2416 EndLoc);
2417 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002418 case OMPD_section:
2419 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002420 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002421 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2422 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002423 case OMPD_single:
2424 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2425 EndLoc);
2426 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002427 case OMPD_master:
2428 assert(ClausesWithImplicit.empty() &&
2429 "No clauses are allowed for 'omp master' directive");
2430 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2431 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002432 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002433 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2434 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002435 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002436 case OMPD_parallel_for:
2437 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2438 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002439 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002440 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002441 case OMPD_parallel_for_simd:
2442 Res = ActOnOpenMPParallelForSimdDirective(
2443 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002444 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002445 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002446 case OMPD_parallel_sections:
2447 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2448 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002449 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002450 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002451 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002452 Res =
2453 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002454 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002455 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002456 case OMPD_taskyield:
2457 assert(ClausesWithImplicit.empty() &&
2458 "No clauses are allowed for 'omp taskyield' directive");
2459 assert(AStmt == nullptr &&
2460 "No associated statement allowed for 'omp taskyield' directive");
2461 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2462 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002463 case OMPD_barrier:
2464 assert(ClausesWithImplicit.empty() &&
2465 "No clauses are allowed for 'omp barrier' directive");
2466 assert(AStmt == nullptr &&
2467 "No associated statement allowed for 'omp barrier' directive");
2468 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2469 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002470 case OMPD_taskwait:
2471 assert(ClausesWithImplicit.empty() &&
2472 "No clauses are allowed for 'omp taskwait' directive");
2473 assert(AStmt == nullptr &&
2474 "No associated statement allowed for 'omp taskwait' directive");
2475 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2476 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002477 case OMPD_taskgroup:
2478 assert(ClausesWithImplicit.empty() &&
2479 "No clauses are allowed for 'omp taskgroup' directive");
2480 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2481 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002482 case OMPD_flush:
2483 assert(AStmt == nullptr &&
2484 "No associated statement allowed for 'omp flush' directive");
2485 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2486 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002487 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002488 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2489 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002490 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002491 case OMPD_atomic:
2492 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2493 EndLoc);
2494 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002495 case OMPD_teams:
2496 Res =
2497 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2498 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002499 case OMPD_target:
2500 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2501 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002502 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002503 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002504 case OMPD_target_parallel:
2505 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2506 StartLoc, EndLoc);
2507 AllowedNameModifiers.push_back(OMPD_target);
2508 AllowedNameModifiers.push_back(OMPD_parallel);
2509 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002510 case OMPD_target_parallel_for:
2511 Res = ActOnOpenMPTargetParallelForDirective(
2512 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2513 AllowedNameModifiers.push_back(OMPD_target);
2514 AllowedNameModifiers.push_back(OMPD_parallel);
2515 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002516 case OMPD_cancellation_point:
2517 assert(ClausesWithImplicit.empty() &&
2518 "No clauses are allowed for 'omp cancellation point' directive");
2519 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2520 "cancellation point' directive");
2521 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2522 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002523 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002524 assert(AStmt == nullptr &&
2525 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002526 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2527 CancelRegion);
2528 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002529 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002530 case OMPD_target_data:
2531 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2532 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002533 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002534 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002535 case OMPD_target_enter_data:
2536 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2537 EndLoc);
2538 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2539 break;
Samuel Antao72590762016-01-19 20:04:50 +00002540 case OMPD_target_exit_data:
2541 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2542 EndLoc);
2543 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2544 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002545 case OMPD_taskloop:
2546 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2547 EndLoc, VarsWithInheritedDSA);
2548 AllowedNameModifiers.push_back(OMPD_taskloop);
2549 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002550 case OMPD_taskloop_simd:
2551 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2552 EndLoc, VarsWithInheritedDSA);
2553 AllowedNameModifiers.push_back(OMPD_taskloop);
2554 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002555 case OMPD_distribute:
2556 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2557 EndLoc, VarsWithInheritedDSA);
2558 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002559 case OMPD_target_update:
2560 assert(!AStmt && "Statement is not allowed for target update");
2561 Res =
2562 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2563 AllowedNameModifiers.push_back(OMPD_target_update);
2564 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002565 case OMPD_distribute_parallel_for:
2566 Res = ActOnOpenMPDistributeParallelForDirective(
2567 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2568 AllowedNameModifiers.push_back(OMPD_parallel);
2569 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002570 case OMPD_distribute_parallel_for_simd:
2571 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2572 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2573 AllowedNameModifiers.push_back(OMPD_parallel);
2574 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002575 case OMPD_distribute_simd:
2576 Res = ActOnOpenMPDistributeSimdDirective(
2577 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2578 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002579 case OMPD_target_parallel_for_simd:
2580 Res = ActOnOpenMPTargetParallelForSimdDirective(
2581 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2582 AllowedNameModifiers.push_back(OMPD_target);
2583 AllowedNameModifiers.push_back(OMPD_parallel);
2584 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002585 case OMPD_target_simd:
2586 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2587 EndLoc, VarsWithInheritedDSA);
2588 AllowedNameModifiers.push_back(OMPD_target);
2589 break;
Kelvin Li02532872016-08-05 14:37:37 +00002590 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002591 Res = ActOnOpenMPTeamsDistributeDirective(
2592 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002593 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002594 case OMPD_teams_distribute_simd:
2595 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2596 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2597 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002598 case OMPD_teams_distribute_parallel_for_simd:
2599 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2600 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2601 AllowedNameModifiers.push_back(OMPD_parallel);
2602 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002603 case OMPD_teams_distribute_parallel_for:
2604 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2605 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2606 AllowedNameModifiers.push_back(OMPD_parallel);
2607 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002608 case OMPD_target_teams:
2609 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2610 EndLoc);
2611 AllowedNameModifiers.push_back(OMPD_target);
2612 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002613 case OMPD_target_teams_distribute:
2614 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2615 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2616 AllowedNameModifiers.push_back(OMPD_target);
2617 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002618 case OMPD_target_teams_distribute_parallel_for:
2619 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2620 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2621 AllowedNameModifiers.push_back(OMPD_target);
2622 AllowedNameModifiers.push_back(OMPD_parallel);
2623 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002624 case OMPD_target_teams_distribute_parallel_for_simd:
2625 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2626 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2627 AllowedNameModifiers.push_back(OMPD_target);
2628 AllowedNameModifiers.push_back(OMPD_parallel);
2629 break;
Kelvin Lida681182017-01-10 18:08:18 +00002630 case OMPD_target_teams_distribute_simd:
2631 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2632 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2633 AllowedNameModifiers.push_back(OMPD_target);
2634 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002635 case OMPD_declare_target:
2636 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002637 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002638 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002639 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002640 llvm_unreachable("OpenMP Directive is not allowed");
2641 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002642 llvm_unreachable("Unknown OpenMP directive");
2643 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002644
Alexey Bataev4acb8592014-07-07 13:01:15 +00002645 for (auto P : VarsWithInheritedDSA) {
2646 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2647 << P.first << P.second->getSourceRange();
2648 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002649 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2650
2651 if (!AllowedNameModifiers.empty())
2652 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2653 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002654
Alexey Bataeved09d242014-05-28 05:53:51 +00002655 if (ErrorFound)
2656 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002657 return Res;
2658}
2659
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002660Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2661 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002662 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002663 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2664 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002665 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002666 assert(Linears.size() == LinModifiers.size());
2667 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002668 if (!DG || DG.get().isNull())
2669 return DeclGroupPtrTy();
2670
2671 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002672 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002673 return DG;
2674 }
2675 auto *ADecl = DG.get().getSingleDecl();
2676 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2677 ADecl = FTD->getTemplatedDecl();
2678
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002679 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2680 if (!FD) {
2681 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002682 return DeclGroupPtrTy();
2683 }
2684
Alexey Bataev2af33e32016-04-07 12:45:37 +00002685 // OpenMP [2.8.2, declare simd construct, Description]
2686 // The parameter of the simdlen clause must be a constant positive integer
2687 // expression.
2688 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002689 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002690 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002691 // OpenMP [2.8.2, declare simd construct, Description]
2692 // The special this pointer can be used as if was one of the arguments to the
2693 // function in any of the linear, aligned, or uniform clauses.
2694 // The uniform clause declares one or more arguments to have an invariant
2695 // value for all concurrent invocations of the function in the execution of a
2696 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002697 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2698 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002699 for (auto *E : Uniforms) {
2700 E = E->IgnoreParenImpCasts();
2701 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2702 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2703 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2704 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002705 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2706 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002707 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002708 }
2709 if (isa<CXXThisExpr>(E)) {
2710 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002711 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002712 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002713 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2714 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002715 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002716 // OpenMP [2.8.2, declare simd construct, Description]
2717 // The aligned clause declares that the object to which each list item points
2718 // is aligned to the number of bytes expressed in the optional parameter of
2719 // the aligned clause.
2720 // The special this pointer can be used as if was one of the arguments to the
2721 // function in any of the linear, aligned, or uniform clauses.
2722 // The type of list items appearing in the aligned clause must be array,
2723 // pointer, reference to array, or reference to pointer.
2724 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2725 Expr *AlignedThis = nullptr;
2726 for (auto *E : Aligneds) {
2727 E = E->IgnoreParenImpCasts();
2728 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2729 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2730 auto *CanonPVD = PVD->getCanonicalDecl();
2731 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2732 FD->getParamDecl(PVD->getFunctionScopeIndex())
2733 ->getCanonicalDecl() == CanonPVD) {
2734 // OpenMP [2.8.1, simd construct, Restrictions]
2735 // A list-item cannot appear in more than one aligned clause.
2736 if (AlignedArgs.count(CanonPVD) > 0) {
2737 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2738 << 1 << E->getSourceRange();
2739 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2740 diag::note_omp_explicit_dsa)
2741 << getOpenMPClauseName(OMPC_aligned);
2742 continue;
2743 }
2744 AlignedArgs[CanonPVD] = E;
2745 QualType QTy = PVD->getType()
2746 .getNonReferenceType()
2747 .getUnqualifiedType()
2748 .getCanonicalType();
2749 const Type *Ty = QTy.getTypePtrOrNull();
2750 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2751 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2752 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2753 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2754 }
2755 continue;
2756 }
2757 }
2758 if (isa<CXXThisExpr>(E)) {
2759 if (AlignedThis) {
2760 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2761 << 2 << E->getSourceRange();
2762 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2763 << getOpenMPClauseName(OMPC_aligned);
2764 }
2765 AlignedThis = E;
2766 continue;
2767 }
2768 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2769 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2770 }
2771 // The optional parameter of the aligned clause, alignment, must be a constant
2772 // positive integer expression. If no optional parameter is specified,
2773 // implementation-defined default alignments for SIMD instructions on the
2774 // target platforms are assumed.
2775 SmallVector<Expr *, 4> NewAligns;
2776 for (auto *E : Alignments) {
2777 ExprResult Align;
2778 if (E)
2779 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2780 NewAligns.push_back(Align.get());
2781 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002782 // OpenMP [2.8.2, declare simd construct, Description]
2783 // The linear clause declares one or more list items to be private to a SIMD
2784 // lane and to have a linear relationship with respect to the iteration space
2785 // of a loop.
2786 // The special this pointer can be used as if was one of the arguments to the
2787 // function in any of the linear, aligned, or uniform clauses.
2788 // When a linear-step expression is specified in a linear clause it must be
2789 // either a constant integer expression or an integer-typed parameter that is
2790 // specified in a uniform clause on the directive.
2791 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2792 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2793 auto MI = LinModifiers.begin();
2794 for (auto *E : Linears) {
2795 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2796 ++MI;
2797 E = E->IgnoreParenImpCasts();
2798 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2799 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2800 auto *CanonPVD = PVD->getCanonicalDecl();
2801 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2802 FD->getParamDecl(PVD->getFunctionScopeIndex())
2803 ->getCanonicalDecl() == CanonPVD) {
2804 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2805 // A list-item cannot appear in more than one linear clause.
2806 if (LinearArgs.count(CanonPVD) > 0) {
2807 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2808 << getOpenMPClauseName(OMPC_linear)
2809 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2810 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2811 diag::note_omp_explicit_dsa)
2812 << getOpenMPClauseName(OMPC_linear);
2813 continue;
2814 }
2815 // Each argument can appear in at most one uniform or linear clause.
2816 if (UniformedArgs.count(CanonPVD) > 0) {
2817 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2818 << getOpenMPClauseName(OMPC_linear)
2819 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2820 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2821 diag::note_omp_explicit_dsa)
2822 << getOpenMPClauseName(OMPC_uniform);
2823 continue;
2824 }
2825 LinearArgs[CanonPVD] = E;
2826 if (E->isValueDependent() || E->isTypeDependent() ||
2827 E->isInstantiationDependent() ||
2828 E->containsUnexpandedParameterPack())
2829 continue;
2830 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2831 PVD->getOriginalType());
2832 continue;
2833 }
2834 }
2835 if (isa<CXXThisExpr>(E)) {
2836 if (UniformedLinearThis) {
2837 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2838 << getOpenMPClauseName(OMPC_linear)
2839 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2840 << E->getSourceRange();
2841 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2842 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2843 : OMPC_linear);
2844 continue;
2845 }
2846 UniformedLinearThis = E;
2847 if (E->isValueDependent() || E->isTypeDependent() ||
2848 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2849 continue;
2850 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2851 E->getType());
2852 continue;
2853 }
2854 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2855 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2856 }
2857 Expr *Step = nullptr;
2858 Expr *NewStep = nullptr;
2859 SmallVector<Expr *, 4> NewSteps;
2860 for (auto *E : Steps) {
2861 // Skip the same step expression, it was checked already.
2862 if (Step == E || !E) {
2863 NewSteps.push_back(E ? NewStep : nullptr);
2864 continue;
2865 }
2866 Step = E;
2867 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2868 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2869 auto *CanonPVD = PVD->getCanonicalDecl();
2870 if (UniformedArgs.count(CanonPVD) == 0) {
2871 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2872 << Step->getSourceRange();
2873 } else if (E->isValueDependent() || E->isTypeDependent() ||
2874 E->isInstantiationDependent() ||
2875 E->containsUnexpandedParameterPack() ||
2876 CanonPVD->getType()->hasIntegerRepresentation())
2877 NewSteps.push_back(Step);
2878 else {
2879 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2880 << Step->getSourceRange();
2881 }
2882 continue;
2883 }
2884 NewStep = Step;
2885 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2886 !Step->isInstantiationDependent() &&
2887 !Step->containsUnexpandedParameterPack()) {
2888 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2889 .get();
2890 if (NewStep)
2891 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2892 }
2893 NewSteps.push_back(NewStep);
2894 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002895 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2896 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002897 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002898 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2899 const_cast<Expr **>(Linears.data()), Linears.size(),
2900 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2901 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002902 ADecl->addAttr(NewAttr);
2903 return ConvertDeclToDeclGroup(ADecl);
2904}
2905
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002906StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2907 Stmt *AStmt,
2908 SourceLocation StartLoc,
2909 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002910 if (!AStmt)
2911 return StmtError();
2912
Alexey Bataev9959db52014-05-06 10:08:46 +00002913 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2914 // 1.2.2 OpenMP Language Terminology
2915 // Structured block - An executable statement with a single entry at the
2916 // top and a single exit at the bottom.
2917 // The point of exit cannot be a branch out of the structured block.
2918 // longjmp() and throw() must not violate the entry/exit criteria.
2919 CS->getCapturedDecl()->setNothrow();
2920
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002921 getCurFunction()->setHasBranchProtectedScope();
2922
Alexey Bataev25e5b442015-09-15 12:52:43 +00002923 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2924 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002925}
2926
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002927namespace {
2928/// \brief Helper class for checking canonical form of the OpenMP loops and
2929/// extracting iteration space of each loop in the loop nest, that will be used
2930/// for IR generation.
2931class OpenMPIterationSpaceChecker {
2932 /// \brief Reference to Sema.
2933 Sema &SemaRef;
2934 /// \brief A location for diagnostics (when there is no some better location).
2935 SourceLocation DefaultLoc;
2936 /// \brief A location for diagnostics (when increment is not compatible).
2937 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002938 /// \brief A source location for referring to loop init later.
2939 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002940 /// \brief A source location for referring to condition later.
2941 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002942 /// \brief A source location for referring to increment later.
2943 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002944 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002945 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002946 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002947 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002948 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002949 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002950 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002951 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002952 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002953 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002954 /// \brief This flag is true when condition is one of:
2955 /// Var < UB
2956 /// Var <= UB
2957 /// UB > Var
2958 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002959 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002960 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002961 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002963 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002964
2965public:
2966 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002967 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002968 /// \brief Check init-expr for canonical loop form and save loop counter
2969 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002970 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002971 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2972 /// for less/greater and for strict/non-strict comparison.
2973 bool CheckCond(Expr *S);
2974 /// \brief Check incr-expr for canonical loop form and return true if it
2975 /// does not conform, otherwise save loop step (#Step).
2976 bool CheckInc(Expr *S);
2977 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002978 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002979 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002980 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002981 /// \brief Source range of the loop init.
2982 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2983 /// \brief Source range of the loop condition.
2984 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2985 /// \brief Source range of the loop increment.
2986 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2987 /// \brief True if the step should be subtracted.
2988 bool ShouldSubtractStep() const { return SubtractStep; }
2989 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002990 Expr *
2991 BuildNumIterations(Scope *S, const bool LimitedType,
2992 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002993 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002994 Expr *BuildPreCond(Scope *S, Expr *Cond,
2995 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002996 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002997 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2998 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002999 /// \brief Build reference expression to the private counter be used for
3000 /// codegen.
3001 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003002 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003003 Expr *BuildCounterInit() const;
3004 /// \brief Build step of the counter be used for codegen.
3005 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003006 /// \brief Return true if any expression is dependent.
3007 bool Dependent() const;
3008
3009private:
3010 /// \brief Check the right-hand side of an assignment in the increment
3011 /// expression.
3012 bool CheckIncRHS(Expr *RHS);
3013 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003014 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003015 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003016 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003017 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003018 /// \brief Helper to set loop increment.
3019 bool SetStep(Expr *NewStep, bool Subtract);
3020};
3021
3022bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003023 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003024 assert(!LB && !UB && !Step);
3025 return false;
3026 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003027 return LCDecl->getType()->isDependentType() ||
3028 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3029 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003030}
3031
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003032static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003033 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3034 E = ExprTemp->getSubExpr();
3035
3036 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3037 E = MTE->GetTemporaryExpr();
3038
3039 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3040 E = Binder->getSubExpr();
3041
3042 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3043 E = ICE->getSubExprAsWritten();
3044 return E->IgnoreParens();
3045}
3046
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003047bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3048 Expr *NewLCRefExpr,
3049 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003050 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003051 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003052 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003053 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003054 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003055 LCDecl = getCanonicalDecl(NewLCDecl);
3056 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003057 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3058 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003059 if ((Ctor->isCopyOrMoveConstructor() ||
3060 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3061 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003062 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003063 LB = NewLB;
3064 return false;
3065}
3066
3067bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003068 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003069 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003070 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3071 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003072 if (!NewUB)
3073 return true;
3074 UB = NewUB;
3075 TestIsLessOp = LessOp;
3076 TestIsStrictOp = StrictOp;
3077 ConditionSrcRange = SR;
3078 ConditionLoc = SL;
3079 return false;
3080}
3081
3082bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3083 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003084 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003085 if (!NewStep)
3086 return true;
3087 if (!NewStep->isValueDependent()) {
3088 // Check that the step is integer expression.
3089 SourceLocation StepLoc = NewStep->getLocStart();
3090 ExprResult Val =
3091 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3092 if (Val.isInvalid())
3093 return true;
3094 NewStep = Val.get();
3095
3096 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3097 // If test-expr is of form var relational-op b and relational-op is < or
3098 // <= then incr-expr must cause var to increase on each iteration of the
3099 // loop. If test-expr is of form var relational-op b and relational-op is
3100 // > or >= then incr-expr must cause var to decrease on each iteration of
3101 // the loop.
3102 // If test-expr is of form b relational-op var and relational-op is < or
3103 // <= then incr-expr must cause var to decrease on each iteration of the
3104 // loop. If test-expr is of form b relational-op var and relational-op is
3105 // > or >= then incr-expr must cause var to increase on each iteration of
3106 // the loop.
3107 llvm::APSInt Result;
3108 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3109 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3110 bool IsConstNeg =
3111 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003112 bool IsConstPos =
3113 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003114 bool IsConstZero = IsConstant && !Result.getBoolValue();
3115 if (UB && (IsConstZero ||
3116 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003117 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003118 SemaRef.Diag(NewStep->getExprLoc(),
3119 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003120 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003121 SemaRef.Diag(ConditionLoc,
3122 diag::note_omp_loop_cond_requres_compatible_incr)
3123 << TestIsLessOp << ConditionSrcRange;
3124 return true;
3125 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003126 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003127 NewStep =
3128 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3129 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003130 Subtract = !Subtract;
3131 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003132 }
3133
3134 Step = NewStep;
3135 SubtractStep = Subtract;
3136 return false;
3137}
3138
Alexey Bataev9c821032015-04-30 04:23:23 +00003139bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003140 // Check init-expr for canonical loop form and save loop counter
3141 // variable - #Var and its initialization value - #LB.
3142 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3143 // var = lb
3144 // integer-type var = lb
3145 // random-access-iterator-type var = lb
3146 // pointer-type var = lb
3147 //
3148 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003149 if (EmitDiags) {
3150 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3151 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003152 return true;
3153 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003154 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3155 if (!ExprTemp->cleanupsHaveSideEffects())
3156 S = ExprTemp->getSubExpr();
3157
Alexander Musmana5f070a2014-10-01 06:03:56 +00003158 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003159 if (Expr *E = dyn_cast<Expr>(S))
3160 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003161 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003162 if (BO->getOpcode() == BO_Assign) {
3163 auto *LHS = BO->getLHS()->IgnoreParens();
3164 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3165 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3166 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3167 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3168 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3169 }
3170 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3171 if (ME->isArrow() &&
3172 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3173 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3174 }
3175 }
David Majnemer9d168222016-08-05 17:44:54 +00003176 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003177 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003178 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003179 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003180 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003181 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003182 SemaRef.Diag(S->getLocStart(),
3183 diag::ext_omp_loop_not_canonical_init)
3184 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003185 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 }
3187 }
3188 }
David Majnemer9d168222016-08-05 17:44:54 +00003189 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003190 if (CE->getOperator() == OO_Equal) {
3191 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003192 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003193 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3194 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3195 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3196 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3197 }
3198 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3199 if (ME->isArrow() &&
3200 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3201 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3202 }
3203 }
3204 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003205
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003206 if (Dependent() || SemaRef.CurContext->isDependentContext())
3207 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003208 if (EmitDiags) {
3209 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3210 << S->getSourceRange();
3211 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003212 return true;
3213}
3214
Alexey Bataev23b69422014-06-18 07:08:49 +00003215/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003216/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003217static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003218 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003219 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003220 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003221 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3222 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003223 if ((Ctor->isCopyOrMoveConstructor() ||
3224 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3225 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003226 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003227 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3228 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3229 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3230 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3231 return getCanonicalDecl(ME->getMemberDecl());
3232 return getCanonicalDecl(VD);
3233 }
3234 }
3235 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3236 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3237 return getCanonicalDecl(ME->getMemberDecl());
3238 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003239}
3240
3241bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3242 // Check test-expr for canonical form, save upper-bound UB, flags for
3243 // less/greater and for strict/non-strict comparison.
3244 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3245 // var relational-op b
3246 // b relational-op var
3247 //
3248 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003249 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003250 return true;
3251 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003252 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003253 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003254 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003255 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003256 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003257 return SetUB(BO->getRHS(),
3258 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3259 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3260 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003261 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003262 return SetUB(BO->getLHS(),
3263 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3264 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3265 BO->getSourceRange(), BO->getOperatorLoc());
3266 }
David Majnemer9d168222016-08-05 17:44:54 +00003267 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003268 if (CE->getNumArgs() == 2) {
3269 auto Op = CE->getOperator();
3270 switch (Op) {
3271 case OO_Greater:
3272 case OO_GreaterEqual:
3273 case OO_Less:
3274 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003275 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003276 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3277 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3278 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003279 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003280 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3281 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3282 CE->getOperatorLoc());
3283 break;
3284 default:
3285 break;
3286 }
3287 }
3288 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003289 if (Dependent() || SemaRef.CurContext->isDependentContext())
3290 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003291 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003292 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003293 return true;
3294}
3295
3296bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3297 // RHS of canonical loop form increment can be:
3298 // var + incr
3299 // incr + var
3300 // var - incr
3301 //
3302 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003303 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003304 if (BO->isAdditiveOp()) {
3305 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003306 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003307 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003308 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003309 return SetStep(BO->getLHS(), false);
3310 }
David Majnemer9d168222016-08-05 17:44:54 +00003311 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003312 bool IsAdd = CE->getOperator() == OO_Plus;
3313 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003314 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003315 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003316 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003317 return SetStep(CE->getArg(0), false);
3318 }
3319 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003320 if (Dependent() || SemaRef.CurContext->isDependentContext())
3321 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003322 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003323 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003324 return true;
3325}
3326
3327bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3328 // Check incr-expr for canonical loop form and return true if it
3329 // does not conform.
3330 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3331 // ++var
3332 // var++
3333 // --var
3334 // var--
3335 // var += incr
3336 // var -= incr
3337 // var = var + incr
3338 // var = incr + var
3339 // var = var - incr
3340 //
3341 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003342 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003343 return true;
3344 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003345 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3346 if (!ExprTemp->cleanupsHaveSideEffects())
3347 S = ExprTemp->getSubExpr();
3348
Alexander Musmana5f070a2014-10-01 06:03:56 +00003349 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003350 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003351 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003352 if (UO->isIncrementDecrementOp() &&
3353 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003354 return SetStep(SemaRef
3355 .ActOnIntegerConstant(UO->getLocStart(),
3356 (UO->isDecrementOp() ? -1 : 1))
3357 .get(),
3358 false);
3359 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003360 switch (BO->getOpcode()) {
3361 case BO_AddAssign:
3362 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003363 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003364 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3365 break;
3366 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003367 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003368 return CheckIncRHS(BO->getRHS());
3369 break;
3370 default:
3371 break;
3372 }
David Majnemer9d168222016-08-05 17:44:54 +00003373 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003374 switch (CE->getOperator()) {
3375 case OO_PlusPlus:
3376 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003377 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003378 return SetStep(SemaRef
3379 .ActOnIntegerConstant(
3380 CE->getLocStart(),
3381 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3382 .get(),
3383 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003384 break;
3385 case OO_PlusEqual:
3386 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003387 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003388 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3389 break;
3390 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003391 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003392 return CheckIncRHS(CE->getArg(1));
3393 break;
3394 default:
3395 break;
3396 }
3397 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003398 if (Dependent() || SemaRef.CurContext->isDependentContext())
3399 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003400 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003401 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003402 return true;
3403}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003404
Alexey Bataev5a3af132016-03-29 08:58:54 +00003405static ExprResult
3406tryBuildCapture(Sema &SemaRef, Expr *Capture,
3407 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003408 if (SemaRef.CurContext->isDependentContext())
3409 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003410 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3411 return SemaRef.PerformImplicitConversion(
3412 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3413 /*AllowExplicit=*/true);
3414 auto I = Captures.find(Capture);
3415 if (I != Captures.end())
3416 return buildCapture(SemaRef, Capture, I->second);
3417 DeclRefExpr *Ref = nullptr;
3418 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3419 Captures[Capture] = Ref;
3420 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003421}
3422
Alexander Musmana5f070a2014-10-01 06:03:56 +00003423/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003424Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3425 Scope *S, const bool LimitedType,
3426 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003427 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003428 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003429 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003430 SemaRef.getLangOpts().CPlusPlus) {
3431 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003432 auto *UBExpr = TestIsLessOp ? UB : LB;
3433 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003434 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3435 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003436 if (!Upper || !Lower)
3437 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003438
3439 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3440
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003441 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003442 // BuildBinOp already emitted error, this one is to point user to upper
3443 // and lower bound, and to tell what is passed to 'operator-'.
3444 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3445 << Upper->getSourceRange() << Lower->getSourceRange();
3446 return nullptr;
3447 }
3448 }
3449
3450 if (!Diff.isUsable())
3451 return nullptr;
3452
3453 // Upper - Lower [- 1]
3454 if (TestIsStrictOp)
3455 Diff = SemaRef.BuildBinOp(
3456 S, DefaultLoc, BO_Sub, Diff.get(),
3457 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3458 if (!Diff.isUsable())
3459 return nullptr;
3460
3461 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003462 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3463 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003464 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003465 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003466 if (!Diff.isUsable())
3467 return nullptr;
3468
3469 // Parentheses (for dumping/debugging purposes only).
3470 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3471 if (!Diff.isUsable())
3472 return nullptr;
3473
3474 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003475 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003476 if (!Diff.isUsable())
3477 return nullptr;
3478
Alexander Musman174b3ca2014-10-06 11:16:29 +00003479 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003480 QualType Type = Diff.get()->getType();
3481 auto &C = SemaRef.Context;
3482 bool UseVarType = VarType->hasIntegerRepresentation() &&
3483 C.getTypeSize(Type) > C.getTypeSize(VarType);
3484 if (!Type->isIntegerType() || UseVarType) {
3485 unsigned NewSize =
3486 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3487 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3488 : Type->hasSignedIntegerRepresentation();
3489 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003490 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3491 Diff = SemaRef.PerformImplicitConversion(
3492 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3493 if (!Diff.isUsable())
3494 return nullptr;
3495 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003496 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003497 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003498 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3499 if (NewSize != C.getTypeSize(Type)) {
3500 if (NewSize < C.getTypeSize(Type)) {
3501 assert(NewSize == 64 && "incorrect loop var size");
3502 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3503 << InitSrcRange << ConditionSrcRange;
3504 }
3505 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003506 NewSize, Type->hasSignedIntegerRepresentation() ||
3507 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003508 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3509 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3510 Sema::AA_Converting, true);
3511 if (!Diff.isUsable())
3512 return nullptr;
3513 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003514 }
3515 }
3516
Alexander Musmana5f070a2014-10-01 06:03:56 +00003517 return Diff.get();
3518}
3519
Alexey Bataev5a3af132016-03-29 08:58:54 +00003520Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3521 Scope *S, Expr *Cond,
3522 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003523 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3524 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3525 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003526
Alexey Bataev5a3af132016-03-29 08:58:54 +00003527 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3528 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3529 if (!NewLB.isUsable() || !NewUB.isUsable())
3530 return nullptr;
3531
Alexey Bataev62dbb972015-04-22 11:59:37 +00003532 auto CondExpr = SemaRef.BuildBinOp(
3533 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3534 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003535 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003536 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003537 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3538 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003539 CondExpr = SemaRef.PerformImplicitConversion(
3540 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3541 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003542 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003543 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3544 // Otherwise use original loop conditon and evaluate it in runtime.
3545 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3546}
3547
Alexander Musmana5f070a2014-10-01 06:03:56 +00003548/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003549DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003550 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003551 auto *VD = dyn_cast<VarDecl>(LCDecl);
3552 if (!VD) {
3553 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3554 auto *Ref = buildDeclRefExpr(
3555 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003556 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3557 // If the loop control decl is explicitly marked as private, do not mark it
3558 // as captured again.
3559 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3560 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003561 return Ref;
3562 }
3563 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003564 DefaultLoc);
3565}
3566
3567Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003568 if (LCDecl && !LCDecl->isInvalidDecl()) {
3569 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003570 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003571 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3572 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003573 if (PrivateVar->isInvalidDecl())
3574 return nullptr;
3575 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3576 }
3577 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003578}
3579
Samuel Antao4c8035b2016-12-12 18:00:20 +00003580/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003581Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3582
3583/// \brief Build step of the counter be used for codegen.
3584Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3585
3586/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003587struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003588 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003589 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003590 /// \brief This expression calculates the number of iterations in the loop.
3591 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003592 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003593 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003594 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003595 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003596 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003597 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003598 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003599 /// \brief This is step for the #CounterVar used to generate its update:
3600 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003601 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003602 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003603 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003604 /// \brief Source range of the loop init.
3605 SourceRange InitSrcRange;
3606 /// \brief Source range of the loop condition.
3607 SourceRange CondSrcRange;
3608 /// \brief Source range of the loop increment.
3609 SourceRange IncSrcRange;
3610};
3611
Alexey Bataev23b69422014-06-18 07:08:49 +00003612} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003613
Alexey Bataev9c821032015-04-30 04:23:23 +00003614void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3615 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3616 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003617 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3618 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003619 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3620 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003621 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3622 if (auto *D = ISC.GetLoopDecl()) {
3623 auto *VD = dyn_cast<VarDecl>(D);
3624 if (!VD) {
3625 if (auto *Private = IsOpenMPCapturedDecl(D))
3626 VD = Private;
3627 else {
3628 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3629 /*WithInit=*/false);
3630 VD = cast<VarDecl>(Ref->getDecl());
3631 }
3632 }
3633 DSAStack->addLoopControlVariable(D, VD);
3634 }
3635 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003636 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003637 }
3638}
3639
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003640/// \brief Called on a for stmt to check and extract its iteration space
3641/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003642static bool CheckOpenMPIterationSpace(
3643 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3644 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003645 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003646 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003647 LoopIterationSpace &ResultIterSpace,
3648 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003649 // OpenMP [2.6, Canonical Loop Form]
3650 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003651 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652 if (!For) {
3653 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003654 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3655 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3656 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3657 if (NestedLoopCount > 1) {
3658 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3659 SemaRef.Diag(DSA.getConstructLoc(),
3660 diag::note_omp_collapse_ordered_expr)
3661 << 2 << CollapseLoopCountExpr->getSourceRange()
3662 << OrderedLoopCountExpr->getSourceRange();
3663 else if (CollapseLoopCountExpr)
3664 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3665 diag::note_omp_collapse_ordered_expr)
3666 << 0 << CollapseLoopCountExpr->getSourceRange();
3667 else
3668 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3669 diag::note_omp_collapse_ordered_expr)
3670 << 1 << OrderedLoopCountExpr->getSourceRange();
3671 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003672 return true;
3673 }
3674 assert(For->getBody());
3675
3676 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3677
3678 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003679 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003680 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003681 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682
3683 bool HasErrors = false;
3684
3685 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003686 if (auto *LCDecl = ISC.GetLoopDecl()) {
3687 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003688
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003689 // OpenMP [2.6, Canonical Loop Form]
3690 // Var is one of the following:
3691 // A variable of signed or unsigned integer type.
3692 // For C++, a variable of a random access iterator type.
3693 // For C, a variable of a pointer type.
3694 auto VarType = LCDecl->getType().getNonReferenceType();
3695 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3696 !VarType->isPointerType() &&
3697 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3698 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3699 << SemaRef.getLangOpts().CPlusPlus;
3700 HasErrors = true;
3701 }
3702
3703 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3704 // a Construct
3705 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3706 // parallel for construct is (are) private.
3707 // The loop iteration variable in the associated for-loop of a simd
3708 // construct with just one associated for-loop is linear with a
3709 // constant-linear-step that is the increment of the associated for-loop.
3710 // Exclude loop var from the list of variables with implicitly defined data
3711 // sharing attributes.
3712 VarsWithImplicitDSA.erase(LCDecl);
3713
3714 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3715 // in a Construct, C/C++].
3716 // The loop iteration variable in the associated for-loop of a simd
3717 // construct with just one associated for-loop may be listed in a linear
3718 // clause with a constant-linear-step that is the increment of the
3719 // associated for-loop.
3720 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3721 // parallel for construct may be listed in a private or lastprivate clause.
3722 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3723 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3724 // declared in the loop and it is predetermined as a private.
3725 auto PredeterminedCKind =
3726 isOpenMPSimdDirective(DKind)
3727 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3728 : OMPC_private;
3729 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3730 DVar.CKind != PredeterminedCKind) ||
3731 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3732 isOpenMPDistributeDirective(DKind)) &&
3733 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3734 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3735 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3736 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3737 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3738 << getOpenMPClauseName(PredeterminedCKind);
3739 if (DVar.RefExpr == nullptr)
3740 DVar.CKind = PredeterminedCKind;
3741 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3742 HasErrors = true;
3743 } else if (LoopDeclRefExpr != nullptr) {
3744 // Make the loop iteration variable private (for worksharing constructs),
3745 // linear (for simd directives with the only one associated loop) or
3746 // lastprivate (for simd directives with several collapsed or ordered
3747 // loops).
3748 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003749 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3750 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003751 /*FromParent=*/false);
3752 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3753 }
3754
3755 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3756
3757 // Check test-expr.
3758 HasErrors |= ISC.CheckCond(For->getCond());
3759
3760 // Check incr-expr.
3761 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003762 }
3763
Alexander Musmana5f070a2014-10-01 06:03:56 +00003764 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003765 return HasErrors;
3766
Alexander Musmana5f070a2014-10-01 06:03:56 +00003767 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003768 ResultIterSpace.PreCond =
3769 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003770 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003771 DSA.getCurScope(),
3772 (isOpenMPWorksharingDirective(DKind) ||
3773 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3774 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003775 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003776 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003777 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3778 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3779 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3780 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3781 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3782 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3783
Alexey Bataev62dbb972015-04-22 11:59:37 +00003784 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3785 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003786 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003787 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003788 ResultIterSpace.CounterInit == nullptr ||
3789 ResultIterSpace.CounterStep == nullptr);
3790
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003791 return HasErrors;
3792}
3793
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003794/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003795static ExprResult
3796BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3797 ExprResult Start,
3798 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003799 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003800 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3801 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003802 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003803 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003804 VarRef.get()->getType())) {
3805 NewStart = SemaRef.PerformImplicitConversion(
3806 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3807 /*AllowExplicit=*/true);
3808 if (!NewStart.isUsable())
3809 return ExprError();
3810 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003811
3812 auto Init =
3813 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3814 return Init;
3815}
3816
Alexander Musmana5f070a2014-10-01 06:03:56 +00003817/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003818static ExprResult
3819BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3820 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3821 ExprResult Step, bool Subtract,
3822 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003823 // Add parentheses (for debugging purposes only).
3824 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3825 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3826 !Step.isUsable())
3827 return ExprError();
3828
Alexey Bataev5a3af132016-03-29 08:58:54 +00003829 ExprResult NewStep = Step;
3830 if (Captures)
3831 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003832 if (NewStep.isInvalid())
3833 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003834 ExprResult Update =
3835 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003836 if (!Update.isUsable())
3837 return ExprError();
3838
Alexey Bataevc0214e02016-02-16 12:13:49 +00003839 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3840 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003841 ExprResult NewStart = Start;
3842 if (Captures)
3843 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003844 if (NewStart.isInvalid())
3845 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003846
Alexey Bataevc0214e02016-02-16 12:13:49 +00003847 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3848 ExprResult SavedUpdate = Update;
3849 ExprResult UpdateVal;
3850 if (VarRef.get()->getType()->isOverloadableType() ||
3851 NewStart.get()->getType()->isOverloadableType() ||
3852 Update.get()->getType()->isOverloadableType()) {
3853 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3854 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3855 Update =
3856 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3857 if (Update.isUsable()) {
3858 UpdateVal =
3859 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3860 VarRef.get(), SavedUpdate.get());
3861 if (UpdateVal.isUsable()) {
3862 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3863 UpdateVal.get());
3864 }
3865 }
3866 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3867 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003868
Alexey Bataevc0214e02016-02-16 12:13:49 +00003869 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3870 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3871 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3872 NewStart.get(), SavedUpdate.get());
3873 if (!Update.isUsable())
3874 return ExprError();
3875
Alexey Bataev11481f52016-02-17 10:29:05 +00003876 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3877 VarRef.get()->getType())) {
3878 Update = SemaRef.PerformImplicitConversion(
3879 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3880 if (!Update.isUsable())
3881 return ExprError();
3882 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003883
3884 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3885 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003886 return Update;
3887}
3888
3889/// \brief Convert integer expression \a E to make it have at least \a Bits
3890/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003891static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 if (E == nullptr)
3893 return ExprError();
3894 auto &C = SemaRef.Context;
3895 QualType OldType = E->getType();
3896 unsigned HasBits = C.getTypeSize(OldType);
3897 if (HasBits >= Bits)
3898 return ExprResult(E);
3899 // OK to convert to signed, because new type has more bits than old.
3900 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3901 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3902 true);
3903}
3904
3905/// \brief Check if the given expression \a E is a constant integer that fits
3906/// into \a Bits bits.
3907static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3908 if (E == nullptr)
3909 return false;
3910 llvm::APSInt Result;
3911 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3912 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3913 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003914}
3915
Alexey Bataev5a3af132016-03-29 08:58:54 +00003916/// Build preinits statement for the given declarations.
3917static Stmt *buildPreInits(ASTContext &Context,
3918 SmallVectorImpl<Decl *> &PreInits) {
3919 if (!PreInits.empty()) {
3920 return new (Context) DeclStmt(
3921 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3922 SourceLocation(), SourceLocation());
3923 }
3924 return nullptr;
3925}
3926
3927/// Build preinits statement for the given declarations.
3928static Stmt *buildPreInits(ASTContext &Context,
3929 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3930 if (!Captures.empty()) {
3931 SmallVector<Decl *, 16> PreInits;
3932 for (auto &Pair : Captures)
3933 PreInits.push_back(Pair.second->getDecl());
3934 return buildPreInits(Context, PreInits);
3935 }
3936 return nullptr;
3937}
3938
3939/// Build postupdate expression for the given list of postupdates expressions.
3940static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3941 Expr *PostUpdate = nullptr;
3942 if (!PostUpdates.empty()) {
3943 for (auto *E : PostUpdates) {
3944 Expr *ConvE = S.BuildCStyleCastExpr(
3945 E->getExprLoc(),
3946 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3947 E->getExprLoc(), E)
3948 .get();
3949 PostUpdate = PostUpdate
3950 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3951 PostUpdate, ConvE)
3952 .get()
3953 : ConvE;
3954 }
3955 }
3956 return PostUpdate;
3957}
3958
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003959/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003960/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3961/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003962static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003963CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3964 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3965 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003966 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003967 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003968 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003969 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003970 // Found 'collapse' clause - calculate collapse number.
3971 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003972 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003973 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003974 }
3975 if (OrderedLoopCountExpr) {
3976 // Found 'ordered' clause - calculate collapse number.
3977 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003978 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3979 if (Result.getLimitedValue() < NestedLoopCount) {
3980 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3981 diag::err_omp_wrong_ordered_loop_count)
3982 << OrderedLoopCountExpr->getSourceRange();
3983 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3984 diag::note_collapse_loop_count)
3985 << CollapseLoopCountExpr->getSourceRange();
3986 }
3987 NestedLoopCount = Result.getLimitedValue();
3988 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003989 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003990 // This is helper routine for loop directives (e.g., 'for', 'simd',
3991 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003992 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003993 SmallVector<LoopIterationSpace, 4> IterSpaces;
3994 IterSpaces.resize(NestedLoopCount);
3995 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003996 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003997 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003998 NestedLoopCount, CollapseLoopCountExpr,
3999 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004000 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004001 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004002 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004003 // OpenMP [2.8.1, simd construct, Restrictions]
4004 // All loops associated with the construct must be perfectly nested; that
4005 // is, there must be no intervening code nor any OpenMP directive between
4006 // any two loops.
4007 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004008 }
4009
Alexander Musmana5f070a2014-10-01 06:03:56 +00004010 Built.clear(/* size */ NestedLoopCount);
4011
4012 if (SemaRef.CurContext->isDependentContext())
4013 return NestedLoopCount;
4014
4015 // An example of what is generated for the following code:
4016 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004017 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004018 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004019 // for (k = 0; k < NK; ++k)
4020 // for (j = J0; j < NJ; j+=2) {
4021 // <loop body>
4022 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004023 //
4024 // We generate the code below.
4025 // Note: the loop body may be outlined in CodeGen.
4026 // Note: some counters may be C++ classes, operator- is used to find number of
4027 // iterations and operator+= to calculate counter value.
4028 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4029 // or i64 is currently supported).
4030 //
4031 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4032 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4033 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4034 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4035 // // similar updates for vars in clauses (e.g. 'linear')
4036 // <loop body (using local i and j)>
4037 // }
4038 // i = NI; // assign final values of counters
4039 // j = NJ;
4040 //
4041
4042 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4043 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004044 // Precondition tests if there is at least one iteration (all conditions are
4045 // true).
4046 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004047 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004048 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004049 32 /* Bits */, SemaRef
4050 .PerformImplicitConversion(
4051 N0->IgnoreImpCasts(), N0->getType(),
4052 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004053 .get(),
4054 SemaRef);
4055 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004056 64 /* Bits */, SemaRef
4057 .PerformImplicitConversion(
4058 N0->IgnoreImpCasts(), N0->getType(),
4059 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004060 .get(),
4061 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004062
4063 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4064 return NestedLoopCount;
4065
4066 auto &C = SemaRef.Context;
4067 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4068
4069 Scope *CurScope = DSA.getCurScope();
4070 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004071 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004072 PreCond =
4073 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4074 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004075 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004076 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004077 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004078 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4079 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004080 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004081 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004082 SemaRef
4083 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4084 Sema::AA_Converting,
4085 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004086 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004087 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004088 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004089 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004090 SemaRef
4091 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4092 Sema::AA_Converting,
4093 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004094 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004095 }
4096
4097 // Choose either the 32-bit or 64-bit version.
4098 ExprResult LastIteration = LastIteration64;
4099 if (LastIteration32.isUsable() &&
4100 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4101 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4102 FitsInto(
4103 32 /* Bits */,
4104 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4105 LastIteration64.get(), SemaRef)))
4106 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004107 QualType VType = LastIteration.get()->getType();
4108 QualType RealVType = VType;
4109 QualType StrideVType = VType;
4110 if (isOpenMPTaskLoopDirective(DKind)) {
4111 VType =
4112 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4113 StrideVType =
4114 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4115 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004116
4117 if (!LastIteration.isUsable())
4118 return 0;
4119
4120 // Save the number of iterations.
4121 ExprResult NumIterations = LastIteration;
4122 {
4123 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004124 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4125 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004126 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4127 if (!LastIteration.isUsable())
4128 return 0;
4129 }
4130
4131 // Calculate the last iteration number beforehand instead of doing this on
4132 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4133 llvm::APSInt Result;
4134 bool IsConstant =
4135 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4136 ExprResult CalcLastIteration;
4137 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004138 ExprResult SaveRef =
4139 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004140 LastIteration = SaveRef;
4141
4142 // Prepare SaveRef + 1.
4143 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004144 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004145 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4146 if (!NumIterations.isUsable())
4147 return 0;
4148 }
4149
4150 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4151
David Majnemer9d168222016-08-05 17:44:54 +00004152 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004153 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004154 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4155 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004156 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004157 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4158 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004159 SemaRef.AddInitializerToDecl(LBDecl,
4160 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4161 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004162
4163 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004164 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4165 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004166 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004167 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004168
4169 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4170 // This will be used to implement clause 'lastprivate'.
4171 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004172 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4173 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004174 SemaRef.AddInitializerToDecl(ILDecl,
4175 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4176 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004177
4178 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004179 VarDecl *STDecl =
4180 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4181 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004182 SemaRef.AddInitializerToDecl(STDecl,
4183 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4184 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004185
4186 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004187 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004188 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4189 UB.get(), LastIteration.get());
4190 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4191 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4192 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4193 CondOp.get());
4194 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004195
4196 // If we have a combined directive that combines 'distribute', 'for' or
4197 // 'simd' we need to be able to access the bounds of the schedule of the
4198 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4199 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4200 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004201
Carlo Bertolliffafe102017-04-20 00:39:39 +00004202 // Lower bound variable, initialized with zero.
4203 VarDecl *CombLBDecl =
4204 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4205 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4206 SemaRef.AddInitializerToDecl(
4207 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4208 /*DirectInit*/ false);
4209
4210 // Upper bound variable, initialized with last iteration number.
4211 VarDecl *CombUBDecl =
4212 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4213 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4214 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4215 /*DirectInit*/ false);
4216
4217 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4218 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4219 ExprResult CombCondOp =
4220 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4221 LastIteration.get(), CombUB.get());
4222 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4223 CombCondOp.get());
4224 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4225
4226 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004227 // We expect to have at least 2 more parameters than the 'parallel'
4228 // directive does - the lower and upper bounds of the previous schedule.
4229 assert(CD->getNumParams() >= 4 &&
4230 "Unexpected number of parameters in loop combined directive");
4231
4232 // Set the proper type for the bounds given what we learned from the
4233 // enclosed loops.
4234 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4235 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4236
4237 // Previous lower and upper bounds are obtained from the region
4238 // parameters.
4239 PrevLB =
4240 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4241 PrevUB =
4242 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4243 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004244 }
4245
4246 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004247 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004248 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004249 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004250 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4251 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004252 Expr *RHS =
4253 (isOpenMPWorksharingDirective(DKind) ||
4254 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4255 ? LB.get()
4256 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004257 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4258 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004259
4260 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4261 Expr *CombRHS =
4262 (isOpenMPWorksharingDirective(DKind) ||
4263 isOpenMPTaskLoopDirective(DKind) ||
4264 isOpenMPDistributeDirective(DKind))
4265 ? CombLB.get()
4266 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4267 CombInit =
4268 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4269 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4270 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004271 }
4272
Alexander Musmanc6388682014-12-15 07:07:06 +00004273 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004274 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004275 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004276 (isOpenMPWorksharingDirective(DKind) ||
4277 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004278 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4279 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4280 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004281 ExprResult CombCond;
4282 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4283 CombCond =
4284 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4285 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004286 // Loop increment (IV = IV + 1)
4287 SourceLocation IncLoc;
4288 ExprResult Inc =
4289 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4290 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4291 if (!Inc.isUsable())
4292 return 0;
4293 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004294 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4295 if (!Inc.isUsable())
4296 return 0;
4297
4298 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4299 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004300 // In combined construct, add combined version that use CombLB and CombUB
4301 // base variables for the update
4302 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004303 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4304 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004305 // LB + ST
4306 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4307 if (!NextLB.isUsable())
4308 return 0;
4309 // LB = LB + ST
4310 NextLB =
4311 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4312 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4313 if (!NextLB.isUsable())
4314 return 0;
4315 // UB + ST
4316 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4317 if (!NextUB.isUsable())
4318 return 0;
4319 // UB = UB + ST
4320 NextUB =
4321 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4322 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4323 if (!NextUB.isUsable())
4324 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004325 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4326 CombNextLB =
4327 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4328 if (!NextLB.isUsable())
4329 return 0;
4330 // LB = LB + ST
4331 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4332 CombNextLB.get());
4333 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4334 if (!CombNextLB.isUsable())
4335 return 0;
4336 // UB + ST
4337 CombNextUB =
4338 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4339 if (!CombNextUB.isUsable())
4340 return 0;
4341 // UB = UB + ST
4342 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4343 CombNextUB.get());
4344 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4345 if (!CombNextUB.isUsable())
4346 return 0;
4347 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004348 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004349
Carlo Bertolliffafe102017-04-20 00:39:39 +00004350 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004351 // directive with for as IV = IV + ST; ensure upper bound expression based
4352 // on PrevUB instead of NumIterations - used to implement 'for' when found
4353 // in combination with 'distribute', like in 'distribute parallel for'
4354 SourceLocation DistIncLoc;
4355 ExprResult DistCond, DistInc, PrevEUB;
4356 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4357 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4358 assert(DistCond.isUsable() && "distribute cond expr was not built");
4359
4360 DistInc =
4361 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4362 assert(DistInc.isUsable() && "distribute inc expr was not built");
4363 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4364 DistInc.get());
4365 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4366 assert(DistInc.isUsable() && "distribute inc expr was not built");
4367
4368 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4369 // construct
4370 SourceLocation DistEUBLoc;
4371 ExprResult IsUBGreater =
4372 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4373 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4374 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4375 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4376 CondOp.get());
4377 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4378 }
4379
Alexander Musmana5f070a2014-10-01 06:03:56 +00004380 // Build updates and final values of the loop counters.
4381 bool HasErrors = false;
4382 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004383 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004384 Built.Updates.resize(NestedLoopCount);
4385 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004386 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004387 {
4388 ExprResult Div;
4389 // Go from inner nested loop to outer.
4390 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4391 LoopIterationSpace &IS = IterSpaces[Cnt];
4392 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4393 // Build: Iter = (IV / Div) % IS.NumIters
4394 // where Div is product of previous iterations' IS.NumIters.
4395 ExprResult Iter;
4396 if (Div.isUsable()) {
4397 Iter =
4398 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4399 } else {
4400 Iter = IV;
4401 assert((Cnt == (int)NestedLoopCount - 1) &&
4402 "unusable div expected on first iteration only");
4403 }
4404
4405 if (Cnt != 0 && Iter.isUsable())
4406 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4407 IS.NumIterations);
4408 if (!Iter.isUsable()) {
4409 HasErrors = true;
4410 break;
4411 }
4412
Alexey Bataev39f915b82015-05-08 10:41:21 +00004413 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004414 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4415 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4416 IS.CounterVar->getExprLoc(),
4417 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004418 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004419 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004420 if (!Init.isUsable()) {
4421 HasErrors = true;
4422 break;
4423 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004424 ExprResult Update = BuildCounterUpdate(
4425 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4426 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004427 if (!Update.isUsable()) {
4428 HasErrors = true;
4429 break;
4430 }
4431
4432 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4433 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004434 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004435 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004436 if (!Final.isUsable()) {
4437 HasErrors = true;
4438 break;
4439 }
4440
4441 // Build Div for the next iteration: Div <- Div * IS.NumIters
4442 if (Cnt != 0) {
4443 if (Div.isUnset())
4444 Div = IS.NumIterations;
4445 else
4446 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4447 IS.NumIterations);
4448
4449 // Add parentheses (for debugging purposes only).
4450 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004451 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004452 if (!Div.isUsable()) {
4453 HasErrors = true;
4454 break;
4455 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004456 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004457 }
4458 if (!Update.isUsable() || !Final.isUsable()) {
4459 HasErrors = true;
4460 break;
4461 }
4462 // Save results
4463 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004464 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004465 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004466 Built.Updates[Cnt] = Update.get();
4467 Built.Finals[Cnt] = Final.get();
4468 }
4469 }
4470
4471 if (HasErrors)
4472 return 0;
4473
4474 // Save results
4475 Built.IterationVarRef = IV.get();
4476 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004477 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004478 Built.CalcLastIteration =
4479 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004480 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004481 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004482 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004483 Built.Init = Init.get();
4484 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004485 Built.LB = LB.get();
4486 Built.UB = UB.get();
4487 Built.IL = IL.get();
4488 Built.ST = ST.get();
4489 Built.EUB = EUB.get();
4490 Built.NLB = NextLB.get();
4491 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004492 Built.PrevLB = PrevLB.get();
4493 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004494 Built.DistInc = DistInc.get();
4495 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004496 Built.DistCombinedFields.LB = CombLB.get();
4497 Built.DistCombinedFields.UB = CombUB.get();
4498 Built.DistCombinedFields.EUB = CombEUB.get();
4499 Built.DistCombinedFields.Init = CombInit.get();
4500 Built.DistCombinedFields.Cond = CombCond.get();
4501 Built.DistCombinedFields.NLB = CombNextLB.get();
4502 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004503
Alexey Bataev8b427062016-05-25 12:36:08 +00004504 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4505 // Fill data for doacross depend clauses.
4506 for (auto Pair : DSA.getDoacrossDependClauses()) {
4507 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4508 Pair.first->setCounterValue(CounterVal);
4509 else {
4510 if (NestedLoopCount != Pair.second.size() ||
4511 NestedLoopCount != LoopMultipliers.size() + 1) {
4512 // Erroneous case - clause has some problems.
4513 Pair.first->setCounterValue(CounterVal);
4514 continue;
4515 }
4516 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4517 auto I = Pair.second.rbegin();
4518 auto IS = IterSpaces.rbegin();
4519 auto ILM = LoopMultipliers.rbegin();
4520 Expr *UpCounterVal = CounterVal;
4521 Expr *Multiplier = nullptr;
4522 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4523 if (I->first) {
4524 assert(IS->CounterStep);
4525 Expr *NormalizedOffset =
4526 SemaRef
4527 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4528 I->first, IS->CounterStep)
4529 .get();
4530 if (Multiplier) {
4531 NormalizedOffset =
4532 SemaRef
4533 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4534 NormalizedOffset, Multiplier)
4535 .get();
4536 }
4537 assert(I->second == OO_Plus || I->second == OO_Minus);
4538 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004539 UpCounterVal = SemaRef
4540 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4541 UpCounterVal, NormalizedOffset)
4542 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004543 }
4544 Multiplier = *ILM;
4545 ++I;
4546 ++IS;
4547 ++ILM;
4548 }
4549 Pair.first->setCounterValue(UpCounterVal);
4550 }
4551 }
4552
Alexey Bataevabfc0692014-06-25 06:52:00 +00004553 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004554}
4555
Alexey Bataev10e775f2015-07-30 11:36:16 +00004556static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004557 auto CollapseClauses =
4558 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4559 if (CollapseClauses.begin() != CollapseClauses.end())
4560 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004561 return nullptr;
4562}
4563
Alexey Bataev10e775f2015-07-30 11:36:16 +00004564static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004565 auto OrderedClauses =
4566 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4567 if (OrderedClauses.begin() != OrderedClauses.end())
4568 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004569 return nullptr;
4570}
4571
Kelvin Lic5609492016-07-15 04:39:07 +00004572static bool checkSimdlenSafelenSpecified(Sema &S,
4573 const ArrayRef<OMPClause *> Clauses) {
4574 OMPSafelenClause *Safelen = nullptr;
4575 OMPSimdlenClause *Simdlen = nullptr;
4576
4577 for (auto *Clause : Clauses) {
4578 if (Clause->getClauseKind() == OMPC_safelen)
4579 Safelen = cast<OMPSafelenClause>(Clause);
4580 else if (Clause->getClauseKind() == OMPC_simdlen)
4581 Simdlen = cast<OMPSimdlenClause>(Clause);
4582 if (Safelen && Simdlen)
4583 break;
4584 }
4585
4586 if (Simdlen && Safelen) {
4587 llvm::APSInt SimdlenRes, SafelenRes;
4588 auto SimdlenLength = Simdlen->getSimdlen();
4589 auto SafelenLength = Safelen->getSafelen();
4590 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4591 SimdlenLength->isInstantiationDependent() ||
4592 SimdlenLength->containsUnexpandedParameterPack())
4593 return false;
4594 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4595 SafelenLength->isInstantiationDependent() ||
4596 SafelenLength->containsUnexpandedParameterPack())
4597 return false;
4598 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4599 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4600 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4601 // If both simdlen and safelen clauses are specified, the value of the
4602 // simdlen parameter must be less than or equal to the value of the safelen
4603 // parameter.
4604 if (SimdlenRes > SafelenRes) {
4605 S.Diag(SimdlenLength->getExprLoc(),
4606 diag::err_omp_wrong_simdlen_safelen_values)
4607 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4608 return true;
4609 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004610 }
4611 return false;
4612}
4613
Alexey Bataev4acb8592014-07-07 13:01:15 +00004614StmtResult Sema::ActOnOpenMPSimdDirective(
4615 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4616 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004617 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004618 if (!AStmt)
4619 return StmtError();
4620
4621 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004622 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004623 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4624 // define the nested loops number.
4625 unsigned NestedLoopCount = CheckOpenMPLoop(
4626 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4627 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004628 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004629 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004630
Alexander Musmana5f070a2014-10-01 06:03:56 +00004631 assert((CurContext->isDependentContext() || B.builtAll()) &&
4632 "omp simd loop exprs were not built");
4633
Alexander Musman3276a272015-03-21 10:12:56 +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))
Alexander Musman3276a272015-03-21 10:12:56 +00004638 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004639 B.NumIterations, *this, CurScope,
4640 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +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
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004648 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004649 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4650 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004651}
4652
Alexey Bataev4acb8592014-07-07 13:01:15 +00004653StmtResult Sema::ActOnOpenMPForDirective(
4654 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4655 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004656 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004657 if (!AStmt)
4658 return StmtError();
4659
4660 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004661 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004662 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4663 // define the nested loops number.
4664 unsigned NestedLoopCount = CheckOpenMPLoop(
4665 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4666 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004667 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004668 return StmtError();
4669
Alexander Musmana5f070a2014-10-01 06:03:56 +00004670 assert((CurContext->isDependentContext() || B.builtAll()) &&
4671 "omp for loop exprs were not built");
4672
Alexey Bataev54acd402015-08-04 11:18:19 +00004673 if (!CurContext->isDependentContext()) {
4674 // Finalize the clauses that need pre-built expressions for CodeGen.
4675 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004676 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004677 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004678 B.NumIterations, *this, CurScope,
4679 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004680 return StmtError();
4681 }
4682 }
4683
Alexey Bataevf29276e2014-06-18 04:14:57 +00004684 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004685 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004686 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004687}
4688
Alexander Musmanf82886e2014-09-18 05:12:34 +00004689StmtResult Sema::ActOnOpenMPForSimdDirective(
4690 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4691 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004692 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004693 if (!AStmt)
4694 return StmtError();
4695
4696 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004697 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004698 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4699 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004700 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004701 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4702 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4703 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004704 if (NestedLoopCount == 0)
4705 return StmtError();
4706
Alexander Musmanc6388682014-12-15 07:07:06 +00004707 assert((CurContext->isDependentContext() || B.builtAll()) &&
4708 "omp for simd loop exprs were not built");
4709
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004710 if (!CurContext->isDependentContext()) {
4711 // Finalize the clauses that need pre-built expressions for CodeGen.
4712 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004713 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004714 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004715 B.NumIterations, *this, CurScope,
4716 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004717 return StmtError();
4718 }
4719 }
4720
Kelvin Lic5609492016-07-15 04:39:07 +00004721 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004722 return StmtError();
4723
Alexander Musmanf82886e2014-09-18 05:12:34 +00004724 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004725 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4726 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004727}
4728
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004729StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4730 Stmt *AStmt,
4731 SourceLocation StartLoc,
4732 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004733 if (!AStmt)
4734 return StmtError();
4735
4736 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004737 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004738 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004739 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004740 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004741 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004742 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004743 return StmtError();
4744 // All associated statements must be '#pragma omp section' except for
4745 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004746 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004747 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4748 if (SectionStmt)
4749 Diag(SectionStmt->getLocStart(),
4750 diag::err_omp_sections_substmt_not_section);
4751 return StmtError();
4752 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004753 cast<OMPSectionDirective>(SectionStmt)
4754 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004755 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004756 } else {
4757 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4758 return StmtError();
4759 }
4760
4761 getCurFunction()->setHasBranchProtectedScope();
4762
Alexey Bataev25e5b442015-09-15 12:52:43 +00004763 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4764 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004765}
4766
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004767StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4768 SourceLocation StartLoc,
4769 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004770 if (!AStmt)
4771 return StmtError();
4772
4773 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004774
4775 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004776 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004777
Alexey Bataev25e5b442015-09-15 12:52:43 +00004778 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4779 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004780}
4781
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004782StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4783 Stmt *AStmt,
4784 SourceLocation StartLoc,
4785 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004786 if (!AStmt)
4787 return StmtError();
4788
4789 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004790
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004791 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004792
Alexey Bataev3255bf32015-01-19 05:20:46 +00004793 // OpenMP [2.7.3, single Construct, Restrictions]
4794 // The copyprivate clause must not be used with the nowait clause.
4795 OMPClause *Nowait = nullptr;
4796 OMPClause *Copyprivate = nullptr;
4797 for (auto *Clause : Clauses) {
4798 if (Clause->getClauseKind() == OMPC_nowait)
4799 Nowait = Clause;
4800 else if (Clause->getClauseKind() == OMPC_copyprivate)
4801 Copyprivate = Clause;
4802 if (Copyprivate && Nowait) {
4803 Diag(Copyprivate->getLocStart(),
4804 diag::err_omp_single_copyprivate_with_nowait);
4805 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4806 return StmtError();
4807 }
4808 }
4809
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004810 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4811}
4812
Alexander Musman80c22892014-07-17 08:54:58 +00004813StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4814 SourceLocation StartLoc,
4815 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004816 if (!AStmt)
4817 return StmtError();
4818
4819 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004820
4821 getCurFunction()->setHasBranchProtectedScope();
4822
4823 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4824}
4825
Alexey Bataev28c75412015-12-15 08:19:24 +00004826StmtResult Sema::ActOnOpenMPCriticalDirective(
4827 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4828 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004829 if (!AStmt)
4830 return StmtError();
4831
4832 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004833
Alexey Bataev28c75412015-12-15 08:19:24 +00004834 bool ErrorFound = false;
4835 llvm::APSInt Hint;
4836 SourceLocation HintLoc;
4837 bool DependentHint = false;
4838 for (auto *C : Clauses) {
4839 if (C->getClauseKind() == OMPC_hint) {
4840 if (!DirName.getName()) {
4841 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4842 ErrorFound = true;
4843 }
4844 Expr *E = cast<OMPHintClause>(C)->getHint();
4845 if (E->isTypeDependent() || E->isValueDependent() ||
4846 E->isInstantiationDependent())
4847 DependentHint = true;
4848 else {
4849 Hint = E->EvaluateKnownConstInt(Context);
4850 HintLoc = C->getLocStart();
4851 }
4852 }
4853 }
4854 if (ErrorFound)
4855 return StmtError();
4856 auto Pair = DSAStack->getCriticalWithHint(DirName);
4857 if (Pair.first && DirName.getName() && !DependentHint) {
4858 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4859 Diag(StartLoc, diag::err_omp_critical_with_hint);
4860 if (HintLoc.isValid()) {
4861 Diag(HintLoc, diag::note_omp_critical_hint_here)
4862 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4863 } else
4864 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4865 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4866 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4867 << 1
4868 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4869 /*Radix=*/10, /*Signed=*/false);
4870 } else
4871 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4872 }
4873 }
4874
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004875 getCurFunction()->setHasBranchProtectedScope();
4876
Alexey Bataev28c75412015-12-15 08:19:24 +00004877 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4878 Clauses, AStmt);
4879 if (!Pair.first && DirName.getName() && !DependentHint)
4880 DSAStack->addCriticalWithHint(Dir, Hint);
4881 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004882}
4883
Alexey Bataev4acb8592014-07-07 13:01:15 +00004884StmtResult Sema::ActOnOpenMPParallelForDirective(
4885 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4886 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004887 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004888 if (!AStmt)
4889 return StmtError();
4890
Alexey Bataev4acb8592014-07-07 13:01:15 +00004891 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4892 // 1.2.2 OpenMP Language Terminology
4893 // Structured block - An executable statement with a single entry at the
4894 // top and a single exit at the bottom.
4895 // The point of exit cannot be a branch out of the structured block.
4896 // longjmp() and throw() must not violate the entry/exit criteria.
4897 CS->getCapturedDecl()->setNothrow();
4898
Alexander Musmanc6388682014-12-15 07:07:06 +00004899 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004900 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4901 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004902 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004903 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4904 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4905 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004906 if (NestedLoopCount == 0)
4907 return StmtError();
4908
Alexander Musmana5f070a2014-10-01 06:03:56 +00004909 assert((CurContext->isDependentContext() || B.builtAll()) &&
4910 "omp parallel for loop exprs were not built");
4911
Alexey Bataev54acd402015-08-04 11:18:19 +00004912 if (!CurContext->isDependentContext()) {
4913 // Finalize the clauses that need pre-built expressions for CodeGen.
4914 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004915 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004916 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004917 B.NumIterations, *this, CurScope,
4918 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004919 return StmtError();
4920 }
4921 }
4922
Alexey Bataev4acb8592014-07-07 13:01:15 +00004923 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004924 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004925 NestedLoopCount, Clauses, AStmt, B,
4926 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004927}
4928
Alexander Musmane4e893b2014-09-23 09:33:00 +00004929StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4930 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4931 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004932 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004933 if (!AStmt)
4934 return StmtError();
4935
Alexander Musmane4e893b2014-09-23 09:33:00 +00004936 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4937 // 1.2.2 OpenMP Language Terminology
4938 // Structured block - An executable statement with a single entry at the
4939 // top and a single exit at the bottom.
4940 // The point of exit cannot be a branch out of the structured block.
4941 // longjmp() and throw() must not violate the entry/exit criteria.
4942 CS->getCapturedDecl()->setNothrow();
4943
Alexander Musmanc6388682014-12-15 07:07:06 +00004944 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004945 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4946 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004947 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004948 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4949 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4950 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004951 if (NestedLoopCount == 0)
4952 return StmtError();
4953
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004954 if (!CurContext->isDependentContext()) {
4955 // Finalize the clauses that need pre-built expressions for CodeGen.
4956 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004957 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004958 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004959 B.NumIterations, *this, CurScope,
4960 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004961 return StmtError();
4962 }
4963 }
4964
Kelvin Lic5609492016-07-15 04:39:07 +00004965 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004966 return StmtError();
4967
Alexander Musmane4e893b2014-09-23 09:33:00 +00004968 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004969 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004970 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004971}
4972
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004973StmtResult
4974Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4975 Stmt *AStmt, SourceLocation StartLoc,
4976 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004977 if (!AStmt)
4978 return StmtError();
4979
4980 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004981 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004982 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004983 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004984 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004985 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004986 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004987 return StmtError();
4988 // All associated statements must be '#pragma omp section' except for
4989 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004990 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004991 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4992 if (SectionStmt)
4993 Diag(SectionStmt->getLocStart(),
4994 diag::err_omp_parallel_sections_substmt_not_section);
4995 return StmtError();
4996 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004997 cast<OMPSectionDirective>(SectionStmt)
4998 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004999 }
5000 } else {
5001 Diag(AStmt->getLocStart(),
5002 diag::err_omp_parallel_sections_not_compound_stmt);
5003 return StmtError();
5004 }
5005
5006 getCurFunction()->setHasBranchProtectedScope();
5007
Alexey Bataev25e5b442015-09-15 12:52:43 +00005008 return OMPParallelSectionsDirective::Create(
5009 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005010}
5011
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005012StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5013 Stmt *AStmt, SourceLocation StartLoc,
5014 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005015 if (!AStmt)
5016 return StmtError();
5017
David Majnemer9d168222016-08-05 17:44:54 +00005018 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005019 // 1.2.2 OpenMP Language Terminology
5020 // Structured block - An executable statement with a single entry at the
5021 // top and a single exit at the bottom.
5022 // The point of exit cannot be a branch out of the structured block.
5023 // longjmp() and throw() must not violate the entry/exit criteria.
5024 CS->getCapturedDecl()->setNothrow();
5025
5026 getCurFunction()->setHasBranchProtectedScope();
5027
Alexey Bataev25e5b442015-09-15 12:52:43 +00005028 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5029 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005030}
5031
Alexey Bataev68446b72014-07-18 07:47:19 +00005032StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5033 SourceLocation EndLoc) {
5034 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5035}
5036
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005037StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5038 SourceLocation EndLoc) {
5039 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5040}
5041
Alexey Bataev2df347a2014-07-18 10:17:07 +00005042StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5043 SourceLocation EndLoc) {
5044 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5045}
5046
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005047StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5048 SourceLocation StartLoc,
5049 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005050 if (!AStmt)
5051 return StmtError();
5052
5053 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005054
5055 getCurFunction()->setHasBranchProtectedScope();
5056
5057 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5058}
5059
Alexey Bataev6125da92014-07-21 11:26:11 +00005060StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5061 SourceLocation StartLoc,
5062 SourceLocation EndLoc) {
5063 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5064 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5065}
5066
Alexey Bataev346265e2015-09-25 10:37:12 +00005067StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5068 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005069 SourceLocation StartLoc,
5070 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005071 OMPClause *DependFound = nullptr;
5072 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005073 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005074 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005075 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005076 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005077 for (auto *C : Clauses) {
5078 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5079 DependFound = C;
5080 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5081 if (DependSourceClause) {
5082 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5083 << getOpenMPDirectiveName(OMPD_ordered)
5084 << getOpenMPClauseName(OMPC_depend) << 2;
5085 ErrorFound = true;
5086 } else
5087 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005088 if (DependSinkClause) {
5089 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5090 << 0;
5091 ErrorFound = true;
5092 }
5093 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5094 if (DependSourceClause) {
5095 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5096 << 1;
5097 ErrorFound = true;
5098 }
5099 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005100 }
5101 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005102 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005103 else if (C->getClauseKind() == OMPC_simd)
5104 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005105 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005106 if (!ErrorFound && !SC &&
5107 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005108 // OpenMP [2.8.1,simd Construct, Restrictions]
5109 // An ordered construct with the simd clause is the only OpenMP construct
5110 // that can appear in the simd region.
5111 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005112 ErrorFound = true;
5113 } else if (DependFound && (TC || SC)) {
5114 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5115 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5116 ErrorFound = true;
5117 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5118 Diag(DependFound->getLocStart(),
5119 diag::err_omp_ordered_directive_without_param);
5120 ErrorFound = true;
5121 } else if (TC || Clauses.empty()) {
5122 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5123 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5124 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5125 << (TC != nullptr);
5126 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5127 ErrorFound = true;
5128 }
5129 }
5130 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005131 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005132
5133 if (AStmt) {
5134 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5135
5136 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005137 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005138
5139 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005140}
5141
Alexey Bataev1d160b12015-03-13 12:27:31 +00005142namespace {
5143/// \brief Helper class for checking expression in 'omp atomic [update]'
5144/// construct.
5145class OpenMPAtomicUpdateChecker {
5146 /// \brief Error results for atomic update expressions.
5147 enum ExprAnalysisErrorCode {
5148 /// \brief A statement is not an expression statement.
5149 NotAnExpression,
5150 /// \brief Expression is not builtin binary or unary operation.
5151 NotABinaryOrUnaryExpression,
5152 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5153 NotAnUnaryIncDecExpression,
5154 /// \brief An expression is not of scalar type.
5155 NotAScalarType,
5156 /// \brief A binary operation is not an assignment operation.
5157 NotAnAssignmentOp,
5158 /// \brief RHS part of the binary operation is not a binary expression.
5159 NotABinaryExpression,
5160 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5161 /// expression.
5162 NotABinaryOperator,
5163 /// \brief RHS binary operation does not have reference to the updated LHS
5164 /// part.
5165 NotAnUpdateExpression,
5166 /// \brief No errors is found.
5167 NoError
5168 };
5169 /// \brief Reference to Sema.
5170 Sema &SemaRef;
5171 /// \brief A location for note diagnostics (when error is found).
5172 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005173 /// \brief 'x' lvalue part of the source atomic expression.
5174 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005175 /// \brief 'expr' rvalue part of the source atomic expression.
5176 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005177 /// \brief Helper expression of the form
5178 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5179 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5180 Expr *UpdateExpr;
5181 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5182 /// important for non-associative operations.
5183 bool IsXLHSInRHSPart;
5184 BinaryOperatorKind Op;
5185 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005186 /// \brief true if the source expression is a postfix unary operation, false
5187 /// if it is a prefix unary operation.
5188 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005189
5190public:
5191 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005192 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005193 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005194 /// \brief Check specified statement that it is suitable for 'atomic update'
5195 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005196 /// expression. If DiagId and NoteId == 0, then only check is performed
5197 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005198 /// \param DiagId Diagnostic which should be emitted if error is found.
5199 /// \param NoteId Diagnostic note for the main error message.
5200 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005201 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005202 /// \brief Return the 'x' lvalue part of the source atomic expression.
5203 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005204 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5205 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005206 /// \brief Return the update expression used in calculation of the updated
5207 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5208 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5209 Expr *getUpdateExpr() const { return UpdateExpr; }
5210 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5211 /// false otherwise.
5212 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5213
Alexey Bataevb78ca832015-04-01 03:33:17 +00005214 /// \brief true if the source expression is a postfix unary operation, false
5215 /// if it is a prefix unary operation.
5216 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5217
Alexey Bataev1d160b12015-03-13 12:27:31 +00005218private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005219 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5220 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005221};
5222} // namespace
5223
5224bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5225 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5226 ExprAnalysisErrorCode ErrorFound = NoError;
5227 SourceLocation ErrorLoc, NoteLoc;
5228 SourceRange ErrorRange, NoteRange;
5229 // Allowed constructs are:
5230 // x = x binop expr;
5231 // x = expr binop x;
5232 if (AtomicBinOp->getOpcode() == BO_Assign) {
5233 X = AtomicBinOp->getLHS();
5234 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5235 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5236 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5237 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5238 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005239 Op = AtomicInnerBinOp->getOpcode();
5240 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005241 auto *LHS = AtomicInnerBinOp->getLHS();
5242 auto *RHS = AtomicInnerBinOp->getRHS();
5243 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5244 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5245 /*Canonical=*/true);
5246 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5247 /*Canonical=*/true);
5248 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5249 /*Canonical=*/true);
5250 if (XId == LHSId) {
5251 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005252 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005253 } else if (XId == RHSId) {
5254 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005255 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005256 } else {
5257 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5258 ErrorRange = AtomicInnerBinOp->getSourceRange();
5259 NoteLoc = X->getExprLoc();
5260 NoteRange = X->getSourceRange();
5261 ErrorFound = NotAnUpdateExpression;
5262 }
5263 } else {
5264 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5265 ErrorRange = AtomicInnerBinOp->getSourceRange();
5266 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5267 NoteRange = SourceRange(NoteLoc, NoteLoc);
5268 ErrorFound = NotABinaryOperator;
5269 }
5270 } else {
5271 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5272 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5273 ErrorFound = NotABinaryExpression;
5274 }
5275 } else {
5276 ErrorLoc = AtomicBinOp->getExprLoc();
5277 ErrorRange = AtomicBinOp->getSourceRange();
5278 NoteLoc = AtomicBinOp->getOperatorLoc();
5279 NoteRange = SourceRange(NoteLoc, NoteLoc);
5280 ErrorFound = NotAnAssignmentOp;
5281 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005282 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005283 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5284 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5285 return true;
5286 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005287 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005288 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005289}
5290
5291bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5292 unsigned NoteId) {
5293 ExprAnalysisErrorCode ErrorFound = NoError;
5294 SourceLocation ErrorLoc, NoteLoc;
5295 SourceRange ErrorRange, NoteRange;
5296 // Allowed constructs are:
5297 // x++;
5298 // x--;
5299 // ++x;
5300 // --x;
5301 // x binop= expr;
5302 // x = x binop expr;
5303 // x = expr binop x;
5304 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5305 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5306 if (AtomicBody->getType()->isScalarType() ||
5307 AtomicBody->isInstantiationDependent()) {
5308 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5309 AtomicBody->IgnoreParenImpCasts())) {
5310 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005311 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005312 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005313 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005314 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005315 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005316 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005317 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5318 AtomicBody->IgnoreParenImpCasts())) {
5319 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005320 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005321 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005322 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5323 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005324 // Check for Unary Operation
5325 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005326 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005327 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5328 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005329 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005330 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5331 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005332 } else {
5333 ErrorFound = NotAnUnaryIncDecExpression;
5334 ErrorLoc = AtomicUnaryOp->getExprLoc();
5335 ErrorRange = AtomicUnaryOp->getSourceRange();
5336 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5337 NoteRange = SourceRange(NoteLoc, NoteLoc);
5338 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005339 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005340 ErrorFound = NotABinaryOrUnaryExpression;
5341 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5342 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5343 }
5344 } else {
5345 ErrorFound = NotAScalarType;
5346 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5347 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5348 }
5349 } else {
5350 ErrorFound = NotAnExpression;
5351 NoteLoc = ErrorLoc = S->getLocStart();
5352 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5353 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005354 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005355 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5356 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5357 return true;
5358 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005359 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005360 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005361 // Build an update expression of form 'OpaqueValueExpr(x) binop
5362 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5363 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5364 auto *OVEX = new (SemaRef.getASTContext())
5365 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5366 auto *OVEExpr = new (SemaRef.getASTContext())
5367 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5368 auto Update =
5369 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5370 IsXLHSInRHSPart ? OVEExpr : OVEX);
5371 if (Update.isInvalid())
5372 return true;
5373 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5374 Sema::AA_Casting);
5375 if (Update.isInvalid())
5376 return true;
5377 UpdateExpr = Update.get();
5378 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005379 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005380}
5381
Alexey Bataev0162e452014-07-22 10:10:35 +00005382StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5383 Stmt *AStmt,
5384 SourceLocation StartLoc,
5385 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005386 if (!AStmt)
5387 return StmtError();
5388
David Majnemer9d168222016-08-05 17:44:54 +00005389 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005390 // 1.2.2 OpenMP Language Terminology
5391 // Structured block - An executable statement with a single entry at the
5392 // top and a single exit at the bottom.
5393 // The point of exit cannot be a branch out of the structured block.
5394 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005395 OpenMPClauseKind AtomicKind = OMPC_unknown;
5396 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005397 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005398 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005399 C->getClauseKind() == OMPC_update ||
5400 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005401 if (AtomicKind != OMPC_unknown) {
5402 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5403 << SourceRange(C->getLocStart(), C->getLocEnd());
5404 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5405 << getOpenMPClauseName(AtomicKind);
5406 } else {
5407 AtomicKind = C->getClauseKind();
5408 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005409 }
5410 }
5411 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005412
Alexey Bataev459dec02014-07-24 06:46:57 +00005413 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005414 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5415 Body = EWC->getSubExpr();
5416
Alexey Bataev62cec442014-11-18 10:14:22 +00005417 Expr *X = nullptr;
5418 Expr *V = nullptr;
5419 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005420 Expr *UE = nullptr;
5421 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005422 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005423 // OpenMP [2.12.6, atomic Construct]
5424 // In the next expressions:
5425 // * x and v (as applicable) are both l-value expressions with scalar type.
5426 // * During the execution of an atomic region, multiple syntactic
5427 // occurrences of x must designate the same storage location.
5428 // * Neither of v and expr (as applicable) may access the storage location
5429 // designated by x.
5430 // * Neither of x and expr (as applicable) may access the storage location
5431 // designated by v.
5432 // * expr is an expression with scalar type.
5433 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5434 // * binop, binop=, ++, and -- are not overloaded operators.
5435 // * The expression x binop expr must be numerically equivalent to x binop
5436 // (expr). This requirement is satisfied if the operators in expr have
5437 // precedence greater than binop, or by using parentheses around expr or
5438 // subexpressions of expr.
5439 // * The expression expr binop x must be numerically equivalent to (expr)
5440 // binop x. This requirement is satisfied if the operators in expr have
5441 // precedence equal to or greater than binop, or by using parentheses around
5442 // expr or subexpressions of expr.
5443 // * For forms that allow multiple occurrences of x, the number of times
5444 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005445 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005446 enum {
5447 NotAnExpression,
5448 NotAnAssignmentOp,
5449 NotAScalarType,
5450 NotAnLValue,
5451 NoError
5452 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005453 SourceLocation ErrorLoc, NoteLoc;
5454 SourceRange ErrorRange, NoteRange;
5455 // If clause is read:
5456 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005457 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5458 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005459 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5460 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5461 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5462 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5463 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5464 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5465 if (!X->isLValue() || !V->isLValue()) {
5466 auto NotLValueExpr = X->isLValue() ? V : X;
5467 ErrorFound = NotAnLValue;
5468 ErrorLoc = AtomicBinOp->getExprLoc();
5469 ErrorRange = AtomicBinOp->getSourceRange();
5470 NoteLoc = NotLValueExpr->getExprLoc();
5471 NoteRange = NotLValueExpr->getSourceRange();
5472 }
5473 } else if (!X->isInstantiationDependent() ||
5474 !V->isInstantiationDependent()) {
5475 auto NotScalarExpr =
5476 (X->isInstantiationDependent() || X->getType()->isScalarType())
5477 ? V
5478 : X;
5479 ErrorFound = NotAScalarType;
5480 ErrorLoc = AtomicBinOp->getExprLoc();
5481 ErrorRange = AtomicBinOp->getSourceRange();
5482 NoteLoc = NotScalarExpr->getExprLoc();
5483 NoteRange = NotScalarExpr->getSourceRange();
5484 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005485 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005486 ErrorFound = NotAnAssignmentOp;
5487 ErrorLoc = AtomicBody->getExprLoc();
5488 ErrorRange = AtomicBody->getSourceRange();
5489 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5490 : AtomicBody->getExprLoc();
5491 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5492 : AtomicBody->getSourceRange();
5493 }
5494 } else {
5495 ErrorFound = NotAnExpression;
5496 NoteLoc = ErrorLoc = Body->getLocStart();
5497 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005498 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005499 if (ErrorFound != NoError) {
5500 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5501 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005502 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5503 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005504 return StmtError();
5505 } else if (CurContext->isDependentContext())
5506 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005507 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005508 enum {
5509 NotAnExpression,
5510 NotAnAssignmentOp,
5511 NotAScalarType,
5512 NotAnLValue,
5513 NoError
5514 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005515 SourceLocation ErrorLoc, NoteLoc;
5516 SourceRange ErrorRange, NoteRange;
5517 // If clause is write:
5518 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005519 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5520 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005521 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5522 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005523 X = AtomicBinOp->getLHS();
5524 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005525 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5526 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5527 if (!X->isLValue()) {
5528 ErrorFound = NotAnLValue;
5529 ErrorLoc = AtomicBinOp->getExprLoc();
5530 ErrorRange = AtomicBinOp->getSourceRange();
5531 NoteLoc = X->getExprLoc();
5532 NoteRange = X->getSourceRange();
5533 }
5534 } else if (!X->isInstantiationDependent() ||
5535 !E->isInstantiationDependent()) {
5536 auto NotScalarExpr =
5537 (X->isInstantiationDependent() || X->getType()->isScalarType())
5538 ? E
5539 : X;
5540 ErrorFound = NotAScalarType;
5541 ErrorLoc = AtomicBinOp->getExprLoc();
5542 ErrorRange = AtomicBinOp->getSourceRange();
5543 NoteLoc = NotScalarExpr->getExprLoc();
5544 NoteRange = NotScalarExpr->getSourceRange();
5545 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005546 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005547 ErrorFound = NotAnAssignmentOp;
5548 ErrorLoc = AtomicBody->getExprLoc();
5549 ErrorRange = AtomicBody->getSourceRange();
5550 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5551 : AtomicBody->getExprLoc();
5552 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5553 : AtomicBody->getSourceRange();
5554 }
5555 } else {
5556 ErrorFound = NotAnExpression;
5557 NoteLoc = ErrorLoc = Body->getLocStart();
5558 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005559 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005560 if (ErrorFound != NoError) {
5561 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5562 << ErrorRange;
5563 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5564 << NoteRange;
5565 return StmtError();
5566 } else if (CurContext->isDependentContext())
5567 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005568 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005569 // If clause is update:
5570 // x++;
5571 // x--;
5572 // ++x;
5573 // --x;
5574 // x binop= expr;
5575 // x = x binop expr;
5576 // x = expr binop x;
5577 OpenMPAtomicUpdateChecker Checker(*this);
5578 if (Checker.checkStatement(
5579 Body, (AtomicKind == OMPC_update)
5580 ? diag::err_omp_atomic_update_not_expression_statement
5581 : diag::err_omp_atomic_not_expression_statement,
5582 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005583 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005584 if (!CurContext->isDependentContext()) {
5585 E = Checker.getExpr();
5586 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005587 UE = Checker.getUpdateExpr();
5588 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005589 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005590 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005591 enum {
5592 NotAnAssignmentOp,
5593 NotACompoundStatement,
5594 NotTwoSubstatements,
5595 NotASpecificExpression,
5596 NoError
5597 } ErrorFound = NoError;
5598 SourceLocation ErrorLoc, NoteLoc;
5599 SourceRange ErrorRange, NoteRange;
5600 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5601 // If clause is a capture:
5602 // v = x++;
5603 // v = x--;
5604 // v = ++x;
5605 // v = --x;
5606 // v = x binop= expr;
5607 // v = x = x binop expr;
5608 // v = x = expr binop x;
5609 auto *AtomicBinOp =
5610 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5611 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5612 V = AtomicBinOp->getLHS();
5613 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5614 OpenMPAtomicUpdateChecker Checker(*this);
5615 if (Checker.checkStatement(
5616 Body, diag::err_omp_atomic_capture_not_expression_statement,
5617 diag::note_omp_atomic_update))
5618 return StmtError();
5619 E = Checker.getExpr();
5620 X = Checker.getX();
5621 UE = Checker.getUpdateExpr();
5622 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5623 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005624 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005625 ErrorLoc = AtomicBody->getExprLoc();
5626 ErrorRange = AtomicBody->getSourceRange();
5627 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5628 : AtomicBody->getExprLoc();
5629 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5630 : AtomicBody->getSourceRange();
5631 ErrorFound = NotAnAssignmentOp;
5632 }
5633 if (ErrorFound != NoError) {
5634 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5635 << ErrorRange;
5636 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5637 return StmtError();
5638 } else if (CurContext->isDependentContext()) {
5639 UE = V = E = X = nullptr;
5640 }
5641 } else {
5642 // If clause is a capture:
5643 // { v = x; x = expr; }
5644 // { v = x; x++; }
5645 // { v = x; x--; }
5646 // { v = x; ++x; }
5647 // { v = x; --x; }
5648 // { v = x; x binop= expr; }
5649 // { v = x; x = x binop expr; }
5650 // { v = x; x = expr binop x; }
5651 // { x++; v = x; }
5652 // { x--; v = x; }
5653 // { ++x; v = x; }
5654 // { --x; v = x; }
5655 // { x binop= expr; v = x; }
5656 // { x = x binop expr; v = x; }
5657 // { x = expr binop x; v = x; }
5658 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5659 // Check that this is { expr1; expr2; }
5660 if (CS->size() == 2) {
5661 auto *First = CS->body_front();
5662 auto *Second = CS->body_back();
5663 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5664 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5665 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5666 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5667 // Need to find what subexpression is 'v' and what is 'x'.
5668 OpenMPAtomicUpdateChecker Checker(*this);
5669 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5670 BinaryOperator *BinOp = nullptr;
5671 if (IsUpdateExprFound) {
5672 BinOp = dyn_cast<BinaryOperator>(First);
5673 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5674 }
5675 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5676 // { v = x; x++; }
5677 // { v = x; x--; }
5678 // { v = x; ++x; }
5679 // { v = x; --x; }
5680 // { v = x; x binop= expr; }
5681 // { v = x; x = x binop expr; }
5682 // { v = x; x = expr binop x; }
5683 // Check that the first expression has form v = x.
5684 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5685 llvm::FoldingSetNodeID XId, PossibleXId;
5686 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5687 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5688 IsUpdateExprFound = XId == PossibleXId;
5689 if (IsUpdateExprFound) {
5690 V = BinOp->getLHS();
5691 X = Checker.getX();
5692 E = Checker.getExpr();
5693 UE = Checker.getUpdateExpr();
5694 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005695 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005696 }
5697 }
5698 if (!IsUpdateExprFound) {
5699 IsUpdateExprFound = !Checker.checkStatement(First);
5700 BinOp = nullptr;
5701 if (IsUpdateExprFound) {
5702 BinOp = dyn_cast<BinaryOperator>(Second);
5703 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5704 }
5705 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5706 // { x++; v = x; }
5707 // { x--; v = x; }
5708 // { ++x; v = x; }
5709 // { --x; v = x; }
5710 // { x binop= expr; v = x; }
5711 // { x = x binop expr; v = x; }
5712 // { x = expr binop x; v = x; }
5713 // Check that the second expression has form v = x.
5714 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5715 llvm::FoldingSetNodeID XId, PossibleXId;
5716 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5717 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5718 IsUpdateExprFound = XId == PossibleXId;
5719 if (IsUpdateExprFound) {
5720 V = BinOp->getLHS();
5721 X = Checker.getX();
5722 E = Checker.getExpr();
5723 UE = Checker.getUpdateExpr();
5724 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005725 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005726 }
5727 }
5728 }
5729 if (!IsUpdateExprFound) {
5730 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005731 auto *FirstExpr = dyn_cast<Expr>(First);
5732 auto *SecondExpr = dyn_cast<Expr>(Second);
5733 if (!FirstExpr || !SecondExpr ||
5734 !(FirstExpr->isInstantiationDependent() ||
5735 SecondExpr->isInstantiationDependent())) {
5736 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5737 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005738 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005739 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5740 : First->getLocStart();
5741 NoteRange = ErrorRange = FirstBinOp
5742 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005743 : SourceRange(ErrorLoc, ErrorLoc);
5744 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005745 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5746 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5747 ErrorFound = NotAnAssignmentOp;
5748 NoteLoc = ErrorLoc = SecondBinOp
5749 ? SecondBinOp->getOperatorLoc()
5750 : Second->getLocStart();
5751 NoteRange = ErrorRange =
5752 SecondBinOp ? SecondBinOp->getSourceRange()
5753 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005754 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005755 auto *PossibleXRHSInFirst =
5756 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5757 auto *PossibleXLHSInSecond =
5758 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5759 llvm::FoldingSetNodeID X1Id, X2Id;
5760 PossibleXRHSInFirst->Profile(X1Id, Context,
5761 /*Canonical=*/true);
5762 PossibleXLHSInSecond->Profile(X2Id, Context,
5763 /*Canonical=*/true);
5764 IsUpdateExprFound = X1Id == X2Id;
5765 if (IsUpdateExprFound) {
5766 V = FirstBinOp->getLHS();
5767 X = SecondBinOp->getLHS();
5768 E = SecondBinOp->getRHS();
5769 UE = nullptr;
5770 IsXLHSInRHSPart = false;
5771 IsPostfixUpdate = true;
5772 } else {
5773 ErrorFound = NotASpecificExpression;
5774 ErrorLoc = FirstBinOp->getExprLoc();
5775 ErrorRange = FirstBinOp->getSourceRange();
5776 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5777 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5778 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005779 }
5780 }
5781 }
5782 }
5783 } else {
5784 NoteLoc = ErrorLoc = Body->getLocStart();
5785 NoteRange = ErrorRange =
5786 SourceRange(Body->getLocStart(), Body->getLocStart());
5787 ErrorFound = NotTwoSubstatements;
5788 }
5789 } else {
5790 NoteLoc = ErrorLoc = Body->getLocStart();
5791 NoteRange = ErrorRange =
5792 SourceRange(Body->getLocStart(), Body->getLocStart());
5793 ErrorFound = NotACompoundStatement;
5794 }
5795 if (ErrorFound != NoError) {
5796 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5797 << ErrorRange;
5798 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5799 return StmtError();
5800 } else if (CurContext->isDependentContext()) {
5801 UE = V = E = X = nullptr;
5802 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005803 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005804 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005805
5806 getCurFunction()->setHasBranchProtectedScope();
5807
Alexey Bataev62cec442014-11-18 10:14:22 +00005808 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005809 X, V, E, UE, IsXLHSInRHSPart,
5810 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005811}
5812
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005813StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5814 Stmt *AStmt,
5815 SourceLocation StartLoc,
5816 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005817 if (!AStmt)
5818 return StmtError();
5819
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005820 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5821 // 1.2.2 OpenMP Language Terminology
5822 // Structured block - An executable statement with a single entry at the
5823 // top and a single exit at the bottom.
5824 // The point of exit cannot be a branch out of the structured block.
5825 // longjmp() and throw() must not violate the entry/exit criteria.
5826 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005827
Alexey Bataev13314bf2014-10-09 04:18:56 +00005828 // OpenMP [2.16, Nesting of Regions]
5829 // If specified, a teams construct must be contained within a target
5830 // construct. That target construct must contain no statements or directives
5831 // outside of the teams construct.
5832 if (DSAStack->hasInnerTeamsRegion()) {
5833 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5834 bool OMPTeamsFound = true;
5835 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5836 auto I = CS->body_begin();
5837 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005838 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005839 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5840 OMPTeamsFound = false;
5841 break;
5842 }
5843 ++I;
5844 }
5845 assert(I != CS->body_end() && "Not found statement");
5846 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005847 } else {
5848 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5849 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005850 }
5851 if (!OMPTeamsFound) {
5852 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5853 Diag(DSAStack->getInnerTeamsRegionLoc(),
5854 diag::note_omp_nested_teams_construct_here);
5855 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5856 << isa<OMPExecutableDirective>(S);
5857 return StmtError();
5858 }
5859 }
5860
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005861 getCurFunction()->setHasBranchProtectedScope();
5862
5863 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5864}
5865
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005866StmtResult
5867Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5868 Stmt *AStmt, SourceLocation StartLoc,
5869 SourceLocation EndLoc) {
5870 if (!AStmt)
5871 return StmtError();
5872
5873 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5874 // 1.2.2 OpenMP Language Terminology
5875 // Structured block - An executable statement with a single entry at the
5876 // top and a single exit at the bottom.
5877 // The point of exit cannot be a branch out of the structured block.
5878 // longjmp() and throw() must not violate the entry/exit criteria.
5879 CS->getCapturedDecl()->setNothrow();
5880
5881 getCurFunction()->setHasBranchProtectedScope();
5882
5883 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5884 AStmt);
5885}
5886
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005887StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5889 SourceLocation EndLoc,
5890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5891 if (!AStmt)
5892 return StmtError();
5893
5894 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5895 // 1.2.2 OpenMP Language Terminology
5896 // Structured block - An executable statement with a single entry at the
5897 // top and a single exit at the bottom.
5898 // The point of exit cannot be a branch out of the structured block.
5899 // longjmp() and throw() must not violate the entry/exit criteria.
5900 CS->getCapturedDecl()->setNothrow();
5901
5902 OMPLoopDirective::HelperExprs B;
5903 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5904 // define the nested loops number.
5905 unsigned NestedLoopCount =
5906 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5907 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5908 VarsWithImplicitDSA, B);
5909 if (NestedLoopCount == 0)
5910 return StmtError();
5911
5912 assert((CurContext->isDependentContext() || B.builtAll()) &&
5913 "omp target parallel for loop exprs were not built");
5914
5915 if (!CurContext->isDependentContext()) {
5916 // Finalize the clauses that need pre-built expressions for CodeGen.
5917 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005918 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005919 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005920 B.NumIterations, *this, CurScope,
5921 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005922 return StmtError();
5923 }
5924 }
5925
5926 getCurFunction()->setHasBranchProtectedScope();
5927 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5928 NestedLoopCount, Clauses, AStmt,
5929 B, DSAStack->isCancelRegion());
5930}
5931
Alexey Bataev95b64a92017-05-30 16:00:04 +00005932/// Check for existence of a map clause in the list of clauses.
5933static bool hasClauses(ArrayRef<OMPClause *> Clauses,
5934 const OpenMPClauseKind K) {
5935 return llvm::any_of(
5936 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
5937}
Samuel Antaodf67fc42016-01-19 19:15:56 +00005938
Alexey Bataev95b64a92017-05-30 16:00:04 +00005939template <typename... Params>
5940static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
5941 const Params... ClauseTypes) {
5942 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00005943}
5944
Michael Wong65f367f2015-07-21 13:44:28 +00005945StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5946 Stmt *AStmt,
5947 SourceLocation StartLoc,
5948 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005949 if (!AStmt)
5950 return StmtError();
5951
5952 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5953
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005954 // OpenMP [2.10.1, Restrictions, p. 97]
5955 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00005956 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
5957 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
5958 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00005959 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005960 return StmtError();
5961 }
5962
Michael Wong65f367f2015-07-21 13:44:28 +00005963 getCurFunction()->setHasBranchProtectedScope();
5964
5965 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5966 AStmt);
5967}
5968
Samuel Antaodf67fc42016-01-19 19:15:56 +00005969StmtResult
5970Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5971 SourceLocation StartLoc,
5972 SourceLocation EndLoc) {
5973 // OpenMP [2.10.2, Restrictions, p. 99]
5974 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00005975 if (!hasClauses(Clauses, OMPC_map)) {
5976 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
5977 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00005978 return StmtError();
5979 }
5980
5981 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5982 Clauses);
5983}
5984
Samuel Antao72590762016-01-19 20:04:50 +00005985StmtResult
5986Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5987 SourceLocation StartLoc,
5988 SourceLocation EndLoc) {
5989 // OpenMP [2.10.3, Restrictions, p. 102]
5990 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00005991 if (!hasClauses(Clauses, OMPC_map)) {
5992 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
5993 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00005994 return StmtError();
5995 }
5996
5997 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5998}
5999
Samuel Antao686c70c2016-05-26 17:30:50 +00006000StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6001 SourceLocation StartLoc,
6002 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006003 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006004 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6005 return StmtError();
6006 }
6007 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6008}
6009
Alexey Bataev13314bf2014-10-09 04:18:56 +00006010StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6011 Stmt *AStmt, SourceLocation StartLoc,
6012 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006013 if (!AStmt)
6014 return StmtError();
6015
Alexey Bataev13314bf2014-10-09 04:18:56 +00006016 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6017 // 1.2.2 OpenMP Language Terminology
6018 // Structured block - An executable statement with a single entry at the
6019 // top and a single exit at the bottom.
6020 // The point of exit cannot be a branch out of the structured block.
6021 // longjmp() and throw() must not violate the entry/exit criteria.
6022 CS->getCapturedDecl()->setNothrow();
6023
6024 getCurFunction()->setHasBranchProtectedScope();
6025
6026 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6027}
6028
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006029StmtResult
6030Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6031 SourceLocation EndLoc,
6032 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006033 if (DSAStack->isParentNowaitRegion()) {
6034 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6035 return StmtError();
6036 }
6037 if (DSAStack->isParentOrderedRegion()) {
6038 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6039 return StmtError();
6040 }
6041 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6042 CancelRegion);
6043}
6044
Alexey Bataev87933c72015-09-18 08:07:34 +00006045StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6046 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006047 SourceLocation EndLoc,
6048 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006049 if (DSAStack->isParentNowaitRegion()) {
6050 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6051 return StmtError();
6052 }
6053 if (DSAStack->isParentOrderedRegion()) {
6054 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6055 return StmtError();
6056 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006057 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006058 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6059 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006060}
6061
Alexey Bataev382967a2015-12-08 12:06:20 +00006062static bool checkGrainsizeNumTasksClauses(Sema &S,
6063 ArrayRef<OMPClause *> Clauses) {
6064 OMPClause *PrevClause = nullptr;
6065 bool ErrorFound = false;
6066 for (auto *C : Clauses) {
6067 if (C->getClauseKind() == OMPC_grainsize ||
6068 C->getClauseKind() == OMPC_num_tasks) {
6069 if (!PrevClause)
6070 PrevClause = C;
6071 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6072 S.Diag(C->getLocStart(),
6073 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6074 << getOpenMPClauseName(C->getClauseKind())
6075 << getOpenMPClauseName(PrevClause->getClauseKind());
6076 S.Diag(PrevClause->getLocStart(),
6077 diag::note_omp_previous_grainsize_num_tasks)
6078 << getOpenMPClauseName(PrevClause->getClauseKind());
6079 ErrorFound = true;
6080 }
6081 }
6082 }
6083 return ErrorFound;
6084}
6085
Alexey Bataev49f6e782015-12-01 04:18:41 +00006086StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6087 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6088 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006089 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006090 if (!AStmt)
6091 return StmtError();
6092
6093 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6094 OMPLoopDirective::HelperExprs B;
6095 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6096 // define the nested loops number.
6097 unsigned NestedLoopCount =
6098 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006099 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006100 VarsWithImplicitDSA, B);
6101 if (NestedLoopCount == 0)
6102 return StmtError();
6103
6104 assert((CurContext->isDependentContext() || B.builtAll()) &&
6105 "omp for loop exprs were not built");
6106
Alexey Bataev382967a2015-12-08 12:06:20 +00006107 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6108 // The grainsize clause and num_tasks clause are mutually exclusive and may
6109 // not appear on the same taskloop directive.
6110 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6111 return StmtError();
6112
Alexey Bataev49f6e782015-12-01 04:18:41 +00006113 getCurFunction()->setHasBranchProtectedScope();
6114 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6115 NestedLoopCount, Clauses, AStmt, B);
6116}
6117
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006118StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6119 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6120 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006121 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006122 if (!AStmt)
6123 return StmtError();
6124
6125 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6126 OMPLoopDirective::HelperExprs B;
6127 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6128 // define the nested loops number.
6129 unsigned NestedLoopCount =
6130 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6131 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6132 VarsWithImplicitDSA, B);
6133 if (NestedLoopCount == 0)
6134 return StmtError();
6135
6136 assert((CurContext->isDependentContext() || B.builtAll()) &&
6137 "omp for loop exprs were not built");
6138
Alexey Bataev5a3af132016-03-29 08:58:54 +00006139 if (!CurContext->isDependentContext()) {
6140 // Finalize the clauses that need pre-built expressions for CodeGen.
6141 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006142 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006143 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006144 B.NumIterations, *this, CurScope,
6145 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006146 return StmtError();
6147 }
6148 }
6149
Alexey Bataev382967a2015-12-08 12:06:20 +00006150 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6151 // The grainsize clause and num_tasks clause are mutually exclusive and may
6152 // not appear on the same taskloop directive.
6153 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6154 return StmtError();
6155
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006156 getCurFunction()->setHasBranchProtectedScope();
6157 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6158 NestedLoopCount, Clauses, AStmt, B);
6159}
6160
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006161StmtResult Sema::ActOnOpenMPDistributeDirective(
6162 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6163 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006164 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006165 if (!AStmt)
6166 return StmtError();
6167
6168 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6169 OMPLoopDirective::HelperExprs B;
6170 // In presence of clause 'collapse' with number of loops, it will
6171 // define the nested loops number.
6172 unsigned NestedLoopCount =
6173 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6174 nullptr /*ordered not a clause on distribute*/, AStmt,
6175 *this, *DSAStack, VarsWithImplicitDSA, B);
6176 if (NestedLoopCount == 0)
6177 return StmtError();
6178
6179 assert((CurContext->isDependentContext() || B.builtAll()) &&
6180 "omp for loop exprs were not built");
6181
6182 getCurFunction()->setHasBranchProtectedScope();
6183 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6184 NestedLoopCount, Clauses, AStmt, B);
6185}
6186
Carlo Bertolli9925f152016-06-27 14:55:37 +00006187StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6188 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6189 SourceLocation EndLoc,
6190 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6191 if (!AStmt)
6192 return StmtError();
6193
6194 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6195 // 1.2.2 OpenMP Language Terminology
6196 // Structured block - An executable statement with a single entry at the
6197 // top and a single exit at the bottom.
6198 // The point of exit cannot be a branch out of the structured block.
6199 // longjmp() and throw() must not violate the entry/exit criteria.
6200 CS->getCapturedDecl()->setNothrow();
6201
6202 OMPLoopDirective::HelperExprs B;
6203 // In presence of clause 'collapse' with number of loops, it will
6204 // define the nested loops number.
6205 unsigned NestedLoopCount = CheckOpenMPLoop(
6206 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6207 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6208 VarsWithImplicitDSA, B);
6209 if (NestedLoopCount == 0)
6210 return StmtError();
6211
6212 assert((CurContext->isDependentContext() || B.builtAll()) &&
6213 "omp for loop exprs were not built");
6214
6215 getCurFunction()->setHasBranchProtectedScope();
6216 return OMPDistributeParallelForDirective::Create(
6217 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6218}
6219
Kelvin Li4a39add2016-07-05 05:00:15 +00006220StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6221 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6222 SourceLocation EndLoc,
6223 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6224 if (!AStmt)
6225 return StmtError();
6226
6227 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6228 // 1.2.2 OpenMP Language Terminology
6229 // Structured block - An executable statement with a single entry at the
6230 // top and a single exit at the bottom.
6231 // The point of exit cannot be a branch out of the structured block.
6232 // longjmp() and throw() must not violate the entry/exit criteria.
6233 CS->getCapturedDecl()->setNothrow();
6234
6235 OMPLoopDirective::HelperExprs B;
6236 // In presence of clause 'collapse' with number of loops, it will
6237 // define the nested loops number.
6238 unsigned NestedLoopCount = CheckOpenMPLoop(
6239 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6240 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6241 VarsWithImplicitDSA, B);
6242 if (NestedLoopCount == 0)
6243 return StmtError();
6244
6245 assert((CurContext->isDependentContext() || B.builtAll()) &&
6246 "omp for loop exprs were not built");
6247
Kelvin Lic5609492016-07-15 04:39:07 +00006248 if (checkSimdlenSafelenSpecified(*this, Clauses))
6249 return StmtError();
6250
Kelvin Li4a39add2016-07-05 05:00:15 +00006251 getCurFunction()->setHasBranchProtectedScope();
6252 return OMPDistributeParallelForSimdDirective::Create(
6253 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6254}
6255
Kelvin Li787f3fc2016-07-06 04:45:38 +00006256StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6257 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6258 SourceLocation EndLoc,
6259 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6260 if (!AStmt)
6261 return StmtError();
6262
6263 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6264 // 1.2.2 OpenMP Language Terminology
6265 // Structured block - An executable statement with a single entry at the
6266 // top and a single exit at the bottom.
6267 // The point of exit cannot be a branch out of the structured block.
6268 // longjmp() and throw() must not violate the entry/exit criteria.
6269 CS->getCapturedDecl()->setNothrow();
6270
6271 OMPLoopDirective::HelperExprs B;
6272 // In presence of clause 'collapse' with number of loops, it will
6273 // define the nested loops number.
6274 unsigned NestedLoopCount =
6275 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6276 nullptr /*ordered not a clause on distribute*/, AStmt,
6277 *this, *DSAStack, VarsWithImplicitDSA, B);
6278 if (NestedLoopCount == 0)
6279 return StmtError();
6280
6281 assert((CurContext->isDependentContext() || B.builtAll()) &&
6282 "omp for loop exprs were not built");
6283
Kelvin Lic5609492016-07-15 04:39:07 +00006284 if (checkSimdlenSafelenSpecified(*this, Clauses))
6285 return StmtError();
6286
Kelvin Li787f3fc2016-07-06 04:45:38 +00006287 getCurFunction()->setHasBranchProtectedScope();
6288 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6289 NestedLoopCount, Clauses, AStmt, B);
6290}
6291
Kelvin Lia579b912016-07-14 02:54:56 +00006292StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6293 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6294 SourceLocation EndLoc,
6295 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6296 if (!AStmt)
6297 return StmtError();
6298
6299 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6300 // 1.2.2 OpenMP Language Terminology
6301 // Structured block - An executable statement with a single entry at the
6302 // top and a single exit at the bottom.
6303 // The point of exit cannot be a branch out of the structured block.
6304 // longjmp() and throw() must not violate the entry/exit criteria.
6305 CS->getCapturedDecl()->setNothrow();
6306
6307 OMPLoopDirective::HelperExprs B;
6308 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6309 // define the nested loops number.
6310 unsigned NestedLoopCount = CheckOpenMPLoop(
6311 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6312 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6313 VarsWithImplicitDSA, B);
6314 if (NestedLoopCount == 0)
6315 return StmtError();
6316
6317 assert((CurContext->isDependentContext() || B.builtAll()) &&
6318 "omp target parallel for simd loop exprs were not built");
6319
6320 if (!CurContext->isDependentContext()) {
6321 // Finalize the clauses that need pre-built expressions for CodeGen.
6322 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006323 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006324 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6325 B.NumIterations, *this, CurScope,
6326 DSAStack))
6327 return StmtError();
6328 }
6329 }
Kelvin Lic5609492016-07-15 04:39:07 +00006330 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006331 return StmtError();
6332
6333 getCurFunction()->setHasBranchProtectedScope();
6334 return OMPTargetParallelForSimdDirective::Create(
6335 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6336}
6337
Kelvin Li986330c2016-07-20 22:57:10 +00006338StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6339 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6340 SourceLocation EndLoc,
6341 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6342 if (!AStmt)
6343 return StmtError();
6344
6345 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6346 // 1.2.2 OpenMP Language Terminology
6347 // Structured block - An executable statement with a single entry at the
6348 // top and a single exit at the bottom.
6349 // The point of exit cannot be a branch out of the structured block.
6350 // longjmp() and throw() must not violate the entry/exit criteria.
6351 CS->getCapturedDecl()->setNothrow();
6352
6353 OMPLoopDirective::HelperExprs B;
6354 // In presence of clause 'collapse' with number of loops, it will define the
6355 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006356 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006357 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6358 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6359 VarsWithImplicitDSA, B);
6360 if (NestedLoopCount == 0)
6361 return StmtError();
6362
6363 assert((CurContext->isDependentContext() || B.builtAll()) &&
6364 "omp target simd loop exprs were not built");
6365
6366 if (!CurContext->isDependentContext()) {
6367 // Finalize the clauses that need pre-built expressions for CodeGen.
6368 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006369 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006370 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6371 B.NumIterations, *this, CurScope,
6372 DSAStack))
6373 return StmtError();
6374 }
6375 }
6376
6377 if (checkSimdlenSafelenSpecified(*this, Clauses))
6378 return StmtError();
6379
6380 getCurFunction()->setHasBranchProtectedScope();
6381 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6382 NestedLoopCount, Clauses, AStmt, B);
6383}
6384
Kelvin Li02532872016-08-05 14:37:37 +00006385StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6387 SourceLocation EndLoc,
6388 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6389 if (!AStmt)
6390 return StmtError();
6391
6392 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6393 // 1.2.2 OpenMP Language Terminology
6394 // Structured block - An executable statement with a single entry at the
6395 // top and a single exit at the bottom.
6396 // The point of exit cannot be a branch out of the structured block.
6397 // longjmp() and throw() must not violate the entry/exit criteria.
6398 CS->getCapturedDecl()->setNothrow();
6399
6400 OMPLoopDirective::HelperExprs B;
6401 // In presence of clause 'collapse' with number of loops, it will
6402 // define the nested loops number.
6403 unsigned NestedLoopCount =
6404 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6405 nullptr /*ordered not a clause on distribute*/, AStmt,
6406 *this, *DSAStack, VarsWithImplicitDSA, B);
6407 if (NestedLoopCount == 0)
6408 return StmtError();
6409
6410 assert((CurContext->isDependentContext() || B.builtAll()) &&
6411 "omp teams distribute loop exprs were not built");
6412
6413 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006414 return OMPTeamsDistributeDirective::Create(
6415 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006416}
6417
Kelvin Li4e325f72016-10-25 12:50:55 +00006418StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6419 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6420 SourceLocation EndLoc,
6421 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6422 if (!AStmt)
6423 return StmtError();
6424
6425 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6426 // 1.2.2 OpenMP Language Terminology
6427 // Structured block - An executable statement with a single entry at the
6428 // top and a single exit at the bottom.
6429 // The point of exit cannot be a branch out of the structured block.
6430 // longjmp() and throw() must not violate the entry/exit criteria.
6431 CS->getCapturedDecl()->setNothrow();
6432
6433 OMPLoopDirective::HelperExprs B;
6434 // In presence of clause 'collapse' with number of loops, it will
6435 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006436 unsigned NestedLoopCount = CheckOpenMPLoop(
6437 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6438 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6439 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006440
6441 if (NestedLoopCount == 0)
6442 return StmtError();
6443
6444 assert((CurContext->isDependentContext() || B.builtAll()) &&
6445 "omp teams distribute simd loop exprs were not built");
6446
6447 if (!CurContext->isDependentContext()) {
6448 // Finalize the clauses that need pre-built expressions for CodeGen.
6449 for (auto C : Clauses) {
6450 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6451 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6452 B.NumIterations, *this, CurScope,
6453 DSAStack))
6454 return StmtError();
6455 }
6456 }
6457
6458 if (checkSimdlenSafelenSpecified(*this, Clauses))
6459 return StmtError();
6460
6461 getCurFunction()->setHasBranchProtectedScope();
6462 return OMPTeamsDistributeSimdDirective::Create(
6463 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6464}
6465
Kelvin Li579e41c2016-11-30 23:51:03 +00006466StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6467 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6468 SourceLocation EndLoc,
6469 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6470 if (!AStmt)
6471 return StmtError();
6472
6473 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6474 // 1.2.2 OpenMP Language Terminology
6475 // Structured block - An executable statement with a single entry at the
6476 // top and a single exit at the bottom.
6477 // The point of exit cannot be a branch out of the structured block.
6478 // longjmp() and throw() must not violate the entry/exit criteria.
6479 CS->getCapturedDecl()->setNothrow();
6480
6481 OMPLoopDirective::HelperExprs B;
6482 // In presence of clause 'collapse' with number of loops, it will
6483 // define the nested loops number.
6484 auto NestedLoopCount = CheckOpenMPLoop(
6485 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6486 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6487 VarsWithImplicitDSA, B);
6488
6489 if (NestedLoopCount == 0)
6490 return StmtError();
6491
6492 assert((CurContext->isDependentContext() || B.builtAll()) &&
6493 "omp for loop exprs were not built");
6494
6495 if (!CurContext->isDependentContext()) {
6496 // Finalize the clauses that need pre-built expressions for CodeGen.
6497 for (auto C : Clauses) {
6498 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6499 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6500 B.NumIterations, *this, CurScope,
6501 DSAStack))
6502 return StmtError();
6503 }
6504 }
6505
6506 if (checkSimdlenSafelenSpecified(*this, Clauses))
6507 return StmtError();
6508
6509 getCurFunction()->setHasBranchProtectedScope();
6510 return OMPTeamsDistributeParallelForSimdDirective::Create(
6511 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6512}
6513
Kelvin Li7ade93f2016-12-09 03:24:30 +00006514StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6515 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6516 SourceLocation EndLoc,
6517 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6518 if (!AStmt)
6519 return StmtError();
6520
6521 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6522 // 1.2.2 OpenMP Language Terminology
6523 // Structured block - An executable statement with a single entry at the
6524 // top and a single exit at the bottom.
6525 // The point of exit cannot be a branch out of the structured block.
6526 // longjmp() and throw() must not violate the entry/exit criteria.
6527 CS->getCapturedDecl()->setNothrow();
6528
6529 OMPLoopDirective::HelperExprs B;
6530 // In presence of clause 'collapse' with number of loops, it will
6531 // define the nested loops number.
6532 unsigned NestedLoopCount = CheckOpenMPLoop(
6533 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6534 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6535 VarsWithImplicitDSA, B);
6536
6537 if (NestedLoopCount == 0)
6538 return StmtError();
6539
6540 assert((CurContext->isDependentContext() || B.builtAll()) &&
6541 "omp for loop exprs were not built");
6542
6543 if (!CurContext->isDependentContext()) {
6544 // Finalize the clauses that need pre-built expressions for CodeGen.
6545 for (auto C : Clauses) {
6546 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6547 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6548 B.NumIterations, *this, CurScope,
6549 DSAStack))
6550 return StmtError();
6551 }
6552 }
6553
6554 getCurFunction()->setHasBranchProtectedScope();
6555 return OMPTeamsDistributeParallelForDirective::Create(
6556 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6557}
6558
Kelvin Libf594a52016-12-17 05:48:59 +00006559StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6560 Stmt *AStmt,
6561 SourceLocation StartLoc,
6562 SourceLocation EndLoc) {
6563 if (!AStmt)
6564 return StmtError();
6565
6566 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6567 // 1.2.2 OpenMP Language Terminology
6568 // Structured block - An executable statement with a single entry at the
6569 // top and a single exit at the bottom.
6570 // The point of exit cannot be a branch out of the structured block.
6571 // longjmp() and throw() must not violate the entry/exit criteria.
6572 CS->getCapturedDecl()->setNothrow();
6573
6574 getCurFunction()->setHasBranchProtectedScope();
6575
6576 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6577 AStmt);
6578}
6579
Kelvin Li83c451e2016-12-25 04:52:54 +00006580StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6581 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6582 SourceLocation EndLoc,
6583 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6584 if (!AStmt)
6585 return StmtError();
6586
6587 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6588 // 1.2.2 OpenMP Language Terminology
6589 // Structured block - An executable statement with a single entry at the
6590 // top and a single exit at the bottom.
6591 // The point of exit cannot be a branch out of the structured block.
6592 // longjmp() and throw() must not violate the entry/exit criteria.
6593 CS->getCapturedDecl()->setNothrow();
6594
6595 OMPLoopDirective::HelperExprs B;
6596 // In presence of clause 'collapse' with number of loops, it will
6597 // define the nested loops number.
6598 auto NestedLoopCount = CheckOpenMPLoop(
6599 OMPD_target_teams_distribute,
6600 getCollapseNumberExpr(Clauses),
6601 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6602 VarsWithImplicitDSA, B);
6603 if (NestedLoopCount == 0)
6604 return StmtError();
6605
6606 assert((CurContext->isDependentContext() || B.builtAll()) &&
6607 "omp target teams distribute loop exprs were not built");
6608
6609 getCurFunction()->setHasBranchProtectedScope();
6610 return OMPTargetTeamsDistributeDirective::Create(
6611 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6612}
6613
Kelvin Li80e8f562016-12-29 22:16:30 +00006614StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6615 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6616 SourceLocation EndLoc,
6617 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6618 if (!AStmt)
6619 return StmtError();
6620
6621 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6622 // 1.2.2 OpenMP Language Terminology
6623 // Structured block - An executable statement with a single entry at the
6624 // top and a single exit at the bottom.
6625 // The point of exit cannot be a branch out of the structured block.
6626 // longjmp() and throw() must not violate the entry/exit criteria.
6627 CS->getCapturedDecl()->setNothrow();
6628
6629 OMPLoopDirective::HelperExprs B;
6630 // In presence of clause 'collapse' with number of loops, it will
6631 // define the nested loops number.
6632 auto NestedLoopCount = CheckOpenMPLoop(
6633 OMPD_target_teams_distribute_parallel_for,
6634 getCollapseNumberExpr(Clauses),
6635 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6636 VarsWithImplicitDSA, B);
6637 if (NestedLoopCount == 0)
6638 return StmtError();
6639
6640 assert((CurContext->isDependentContext() || B.builtAll()) &&
6641 "omp target teams distribute parallel for loop exprs were not built");
6642
6643 if (!CurContext->isDependentContext()) {
6644 // Finalize the clauses that need pre-built expressions for CodeGen.
6645 for (auto C : Clauses) {
6646 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6647 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6648 B.NumIterations, *this, CurScope,
6649 DSAStack))
6650 return StmtError();
6651 }
6652 }
6653
6654 getCurFunction()->setHasBranchProtectedScope();
6655 return OMPTargetTeamsDistributeParallelForDirective::Create(
6656 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6657}
6658
Kelvin Li1851df52017-01-03 05:23:48 +00006659StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6661 SourceLocation EndLoc,
6662 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6663 if (!AStmt)
6664 return StmtError();
6665
6666 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6667 // 1.2.2 OpenMP Language Terminology
6668 // Structured block - An executable statement with a single entry at the
6669 // top and a single exit at the bottom.
6670 // The point of exit cannot be a branch out of the structured block.
6671 // longjmp() and throw() must not violate the entry/exit criteria.
6672 CS->getCapturedDecl()->setNothrow();
6673
6674 OMPLoopDirective::HelperExprs B;
6675 // In presence of clause 'collapse' with number of loops, it will
6676 // define the nested loops number.
6677 auto NestedLoopCount = CheckOpenMPLoop(
6678 OMPD_target_teams_distribute_parallel_for_simd,
6679 getCollapseNumberExpr(Clauses),
6680 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6681 VarsWithImplicitDSA, B);
6682 if (NestedLoopCount == 0)
6683 return StmtError();
6684
6685 assert((CurContext->isDependentContext() || B.builtAll()) &&
6686 "omp target teams distribute parallel for simd loop exprs were not "
6687 "built");
6688
6689 if (!CurContext->isDependentContext()) {
6690 // Finalize the clauses that need pre-built expressions for CodeGen.
6691 for (auto C : Clauses) {
6692 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6693 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6694 B.NumIterations, *this, CurScope,
6695 DSAStack))
6696 return StmtError();
6697 }
6698 }
6699
6700 getCurFunction()->setHasBranchProtectedScope();
6701 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6702 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6703}
6704
Kelvin Lida681182017-01-10 18:08:18 +00006705StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6706 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6707 SourceLocation EndLoc,
6708 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6709 if (!AStmt)
6710 return StmtError();
6711
6712 auto *CS = cast<CapturedStmt>(AStmt);
6713 // 1.2.2 OpenMP Language Terminology
6714 // Structured block - An executable statement with a single entry at the
6715 // top and a single exit at the bottom.
6716 // The point of exit cannot be a branch out of the structured block.
6717 // longjmp() and throw() must not violate the entry/exit criteria.
6718 CS->getCapturedDecl()->setNothrow();
6719
6720 OMPLoopDirective::HelperExprs B;
6721 // In presence of clause 'collapse' with number of loops, it will
6722 // define the nested loops number.
6723 auto NestedLoopCount = CheckOpenMPLoop(
6724 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6725 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6726 VarsWithImplicitDSA, B);
6727 if (NestedLoopCount == 0)
6728 return StmtError();
6729
6730 assert((CurContext->isDependentContext() || B.builtAll()) &&
6731 "omp target teams distribute simd loop exprs were not built");
6732
6733 getCurFunction()->setHasBranchProtectedScope();
6734 return OMPTargetTeamsDistributeSimdDirective::Create(
6735 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6736}
6737
Alexey Bataeved09d242014-05-28 05:53:51 +00006738OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006739 SourceLocation StartLoc,
6740 SourceLocation LParenLoc,
6741 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006742 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006743 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006744 case OMPC_final:
6745 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6746 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006747 case OMPC_num_threads:
6748 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6749 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006750 case OMPC_safelen:
6751 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6752 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006753 case OMPC_simdlen:
6754 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6755 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006756 case OMPC_collapse:
6757 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6758 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006759 case OMPC_ordered:
6760 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6761 break;
Michael Wonge710d542015-08-07 16:16:36 +00006762 case OMPC_device:
6763 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6764 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006765 case OMPC_num_teams:
6766 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6767 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006768 case OMPC_thread_limit:
6769 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6770 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006771 case OMPC_priority:
6772 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6773 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006774 case OMPC_grainsize:
6775 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6776 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006777 case OMPC_num_tasks:
6778 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6779 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006780 case OMPC_hint:
6781 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6782 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006783 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006784 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006785 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006786 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006787 case OMPC_private:
6788 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006789 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006790 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006791 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006792 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006793 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006794 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006795 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006796 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006797 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006798 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006799 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006800 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006801 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006802 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006803 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006804 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006805 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006806 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006807 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006808 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006809 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006810 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006811 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006812 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006813 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006814 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006815 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006816 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006817 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006818 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006819 llvm_unreachable("Clause is not allowed.");
6820 }
6821 return Res;
6822}
6823
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006824// An OpenMP directive such as 'target parallel' has two captured regions:
6825// for the 'target' and 'parallel' respectively. This function returns
6826// the region in which to capture expressions associated with a clause.
6827// A return value of OMPD_unknown signifies that the expression should not
6828// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006829static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6830 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6831 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006832 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6833
6834 switch (CKind) {
6835 case OMPC_if:
6836 switch (DKind) {
6837 case OMPD_target_parallel:
6838 // If this clause applies to the nested 'parallel' region, capture within
6839 // the 'target' region, otherwise do not capture.
6840 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6841 CaptureRegion = OMPD_target;
6842 break;
6843 case OMPD_cancel:
6844 case OMPD_parallel:
6845 case OMPD_parallel_sections:
6846 case OMPD_parallel_for:
6847 case OMPD_parallel_for_simd:
6848 case OMPD_target:
6849 case OMPD_target_simd:
6850 case OMPD_target_parallel_for:
6851 case OMPD_target_parallel_for_simd:
6852 case OMPD_target_teams:
6853 case OMPD_target_teams_distribute:
6854 case OMPD_target_teams_distribute_simd:
6855 case OMPD_target_teams_distribute_parallel_for:
6856 case OMPD_target_teams_distribute_parallel_for_simd:
6857 case OMPD_teams_distribute_parallel_for:
6858 case OMPD_teams_distribute_parallel_for_simd:
6859 case OMPD_distribute_parallel_for:
6860 case OMPD_distribute_parallel_for_simd:
6861 case OMPD_task:
6862 case OMPD_taskloop:
6863 case OMPD_taskloop_simd:
6864 case OMPD_target_data:
6865 case OMPD_target_enter_data:
6866 case OMPD_target_exit_data:
6867 case OMPD_target_update:
6868 // Do not capture if-clause expressions.
6869 break;
6870 case OMPD_threadprivate:
6871 case OMPD_taskyield:
6872 case OMPD_barrier:
6873 case OMPD_taskwait:
6874 case OMPD_cancellation_point:
6875 case OMPD_flush:
6876 case OMPD_declare_reduction:
6877 case OMPD_declare_simd:
6878 case OMPD_declare_target:
6879 case OMPD_end_declare_target:
6880 case OMPD_teams:
6881 case OMPD_simd:
6882 case OMPD_for:
6883 case OMPD_for_simd:
6884 case OMPD_sections:
6885 case OMPD_section:
6886 case OMPD_single:
6887 case OMPD_master:
6888 case OMPD_critical:
6889 case OMPD_taskgroup:
6890 case OMPD_distribute:
6891 case OMPD_ordered:
6892 case OMPD_atomic:
6893 case OMPD_distribute_simd:
6894 case OMPD_teams_distribute:
6895 case OMPD_teams_distribute_simd:
6896 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6897 case OMPD_unknown:
6898 llvm_unreachable("Unknown OpenMP directive");
6899 }
6900 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006901 case OMPC_num_threads:
6902 switch (DKind) {
6903 case OMPD_target_parallel:
6904 CaptureRegion = OMPD_target;
6905 break;
6906 case OMPD_cancel:
6907 case OMPD_parallel:
6908 case OMPD_parallel_sections:
6909 case OMPD_parallel_for:
6910 case OMPD_parallel_for_simd:
6911 case OMPD_target:
6912 case OMPD_target_simd:
6913 case OMPD_target_parallel_for:
6914 case OMPD_target_parallel_for_simd:
6915 case OMPD_target_teams:
6916 case OMPD_target_teams_distribute:
6917 case OMPD_target_teams_distribute_simd:
6918 case OMPD_target_teams_distribute_parallel_for:
6919 case OMPD_target_teams_distribute_parallel_for_simd:
6920 case OMPD_teams_distribute_parallel_for:
6921 case OMPD_teams_distribute_parallel_for_simd:
6922 case OMPD_distribute_parallel_for:
6923 case OMPD_distribute_parallel_for_simd:
6924 case OMPD_task:
6925 case OMPD_taskloop:
6926 case OMPD_taskloop_simd:
6927 case OMPD_target_data:
6928 case OMPD_target_enter_data:
6929 case OMPD_target_exit_data:
6930 case OMPD_target_update:
6931 // Do not capture num_threads-clause expressions.
6932 break;
6933 case OMPD_threadprivate:
6934 case OMPD_taskyield:
6935 case OMPD_barrier:
6936 case OMPD_taskwait:
6937 case OMPD_cancellation_point:
6938 case OMPD_flush:
6939 case OMPD_declare_reduction:
6940 case OMPD_declare_simd:
6941 case OMPD_declare_target:
6942 case OMPD_end_declare_target:
6943 case OMPD_teams:
6944 case OMPD_simd:
6945 case OMPD_for:
6946 case OMPD_for_simd:
6947 case OMPD_sections:
6948 case OMPD_section:
6949 case OMPD_single:
6950 case OMPD_master:
6951 case OMPD_critical:
6952 case OMPD_taskgroup:
6953 case OMPD_distribute:
6954 case OMPD_ordered:
6955 case OMPD_atomic:
6956 case OMPD_distribute_simd:
6957 case OMPD_teams_distribute:
6958 case OMPD_teams_distribute_simd:
6959 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6960 case OMPD_unknown:
6961 llvm_unreachable("Unknown OpenMP directive");
6962 }
6963 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00006964 case OMPC_num_teams:
6965 switch (DKind) {
6966 case OMPD_target_teams:
6967 CaptureRegion = OMPD_target;
6968 break;
6969 case OMPD_cancel:
6970 case OMPD_parallel:
6971 case OMPD_parallel_sections:
6972 case OMPD_parallel_for:
6973 case OMPD_parallel_for_simd:
6974 case OMPD_target:
6975 case OMPD_target_simd:
6976 case OMPD_target_parallel:
6977 case OMPD_target_parallel_for:
6978 case OMPD_target_parallel_for_simd:
6979 case OMPD_target_teams_distribute:
6980 case OMPD_target_teams_distribute_simd:
6981 case OMPD_target_teams_distribute_parallel_for:
6982 case OMPD_target_teams_distribute_parallel_for_simd:
6983 case OMPD_teams_distribute_parallel_for:
6984 case OMPD_teams_distribute_parallel_for_simd:
6985 case OMPD_distribute_parallel_for:
6986 case OMPD_distribute_parallel_for_simd:
6987 case OMPD_task:
6988 case OMPD_taskloop:
6989 case OMPD_taskloop_simd:
6990 case OMPD_target_data:
6991 case OMPD_target_enter_data:
6992 case OMPD_target_exit_data:
6993 case OMPD_target_update:
6994 case OMPD_teams:
6995 case OMPD_teams_distribute:
6996 case OMPD_teams_distribute_simd:
6997 // Do not capture num_teams-clause expressions.
6998 break;
6999 case OMPD_threadprivate:
7000 case OMPD_taskyield:
7001 case OMPD_barrier:
7002 case OMPD_taskwait:
7003 case OMPD_cancellation_point:
7004 case OMPD_flush:
7005 case OMPD_declare_reduction:
7006 case OMPD_declare_simd:
7007 case OMPD_declare_target:
7008 case OMPD_end_declare_target:
7009 case OMPD_simd:
7010 case OMPD_for:
7011 case OMPD_for_simd:
7012 case OMPD_sections:
7013 case OMPD_section:
7014 case OMPD_single:
7015 case OMPD_master:
7016 case OMPD_critical:
7017 case OMPD_taskgroup:
7018 case OMPD_distribute:
7019 case OMPD_ordered:
7020 case OMPD_atomic:
7021 case OMPD_distribute_simd:
7022 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7023 case OMPD_unknown:
7024 llvm_unreachable("Unknown OpenMP directive");
7025 }
7026 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007027 case OMPC_thread_limit:
7028 switch (DKind) {
7029 case OMPD_target_teams:
7030 CaptureRegion = OMPD_target;
7031 break;
7032 case OMPD_cancel:
7033 case OMPD_parallel:
7034 case OMPD_parallel_sections:
7035 case OMPD_parallel_for:
7036 case OMPD_parallel_for_simd:
7037 case OMPD_target:
7038 case OMPD_target_simd:
7039 case OMPD_target_parallel:
7040 case OMPD_target_parallel_for:
7041 case OMPD_target_parallel_for_simd:
7042 case OMPD_target_teams_distribute:
7043 case OMPD_target_teams_distribute_simd:
7044 case OMPD_target_teams_distribute_parallel_for:
7045 case OMPD_target_teams_distribute_parallel_for_simd:
7046 case OMPD_teams_distribute_parallel_for:
7047 case OMPD_teams_distribute_parallel_for_simd:
7048 case OMPD_distribute_parallel_for:
7049 case OMPD_distribute_parallel_for_simd:
7050 case OMPD_task:
7051 case OMPD_taskloop:
7052 case OMPD_taskloop_simd:
7053 case OMPD_target_data:
7054 case OMPD_target_enter_data:
7055 case OMPD_target_exit_data:
7056 case OMPD_target_update:
7057 case OMPD_teams:
7058 case OMPD_teams_distribute:
7059 case OMPD_teams_distribute_simd:
7060 // Do not capture thread_limit-clause expressions.
7061 break;
7062 case OMPD_threadprivate:
7063 case OMPD_taskyield:
7064 case OMPD_barrier:
7065 case OMPD_taskwait:
7066 case OMPD_cancellation_point:
7067 case OMPD_flush:
7068 case OMPD_declare_reduction:
7069 case OMPD_declare_simd:
7070 case OMPD_declare_target:
7071 case OMPD_end_declare_target:
7072 case OMPD_simd:
7073 case OMPD_for:
7074 case OMPD_for_simd:
7075 case OMPD_sections:
7076 case OMPD_section:
7077 case OMPD_single:
7078 case OMPD_master:
7079 case OMPD_critical:
7080 case OMPD_taskgroup:
7081 case OMPD_distribute:
7082 case OMPD_ordered:
7083 case OMPD_atomic:
7084 case OMPD_distribute_simd:
7085 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7086 case OMPD_unknown:
7087 llvm_unreachable("Unknown OpenMP directive");
7088 }
7089 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007090 case OMPC_schedule:
7091 case OMPC_dist_schedule:
7092 case OMPC_firstprivate:
7093 case OMPC_lastprivate:
7094 case OMPC_reduction:
7095 case OMPC_linear:
7096 case OMPC_default:
7097 case OMPC_proc_bind:
7098 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007099 case OMPC_safelen:
7100 case OMPC_simdlen:
7101 case OMPC_collapse:
7102 case OMPC_private:
7103 case OMPC_shared:
7104 case OMPC_aligned:
7105 case OMPC_copyin:
7106 case OMPC_copyprivate:
7107 case OMPC_ordered:
7108 case OMPC_nowait:
7109 case OMPC_untied:
7110 case OMPC_mergeable:
7111 case OMPC_threadprivate:
7112 case OMPC_flush:
7113 case OMPC_read:
7114 case OMPC_write:
7115 case OMPC_update:
7116 case OMPC_capture:
7117 case OMPC_seq_cst:
7118 case OMPC_depend:
7119 case OMPC_device:
7120 case OMPC_threads:
7121 case OMPC_simd:
7122 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007123 case OMPC_priority:
7124 case OMPC_grainsize:
7125 case OMPC_nogroup:
7126 case OMPC_num_tasks:
7127 case OMPC_hint:
7128 case OMPC_defaultmap:
7129 case OMPC_unknown:
7130 case OMPC_uniform:
7131 case OMPC_to:
7132 case OMPC_from:
7133 case OMPC_use_device_ptr:
7134 case OMPC_is_device_ptr:
7135 llvm_unreachable("Unexpected OpenMP clause.");
7136 }
7137 return CaptureRegion;
7138}
7139
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007140OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7141 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007142 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007143 SourceLocation NameModifierLoc,
7144 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007145 SourceLocation EndLoc) {
7146 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007147 Stmt *HelperValStmt = nullptr;
7148 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007149 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7150 !Condition->isInstantiationDependent() &&
7151 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007152 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007153 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007154 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007155
Richard Smith03a4aa32016-06-23 19:02:52 +00007156 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007157
7158 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7159 CaptureRegion =
7160 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7161 if (CaptureRegion != OMPD_unknown) {
7162 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7163 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7164 HelperValStmt = buildPreInits(Context, Captures);
7165 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007166 }
7167
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007168 return new (Context)
7169 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7170 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007171}
7172
Alexey Bataev3778b602014-07-17 07:32:53 +00007173OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7174 SourceLocation StartLoc,
7175 SourceLocation LParenLoc,
7176 SourceLocation EndLoc) {
7177 Expr *ValExpr = Condition;
7178 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7179 !Condition->isInstantiationDependent() &&
7180 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007181 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007182 if (Val.isInvalid())
7183 return nullptr;
7184
Richard Smith03a4aa32016-06-23 19:02:52 +00007185 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007186 }
7187
7188 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7189}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007190ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7191 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007192 if (!Op)
7193 return ExprError();
7194
7195 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7196 public:
7197 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007198 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007199 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7200 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007201 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7202 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007203 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7204 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007205 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7206 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007207 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7208 QualType T,
7209 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007210 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7211 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007212 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7213 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007214 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007215 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007216 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007217 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7218 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007219 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7220 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007221 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7222 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007223 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007224 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007225 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007226 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7227 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007228 llvm_unreachable("conversion functions are permitted");
7229 }
7230 } ConvertDiagnoser;
7231 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7232}
7233
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007234static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007235 OpenMPClauseKind CKind,
7236 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007237 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7238 !ValExpr->isInstantiationDependent()) {
7239 SourceLocation Loc = ValExpr->getExprLoc();
7240 ExprResult Value =
7241 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7242 if (Value.isInvalid())
7243 return false;
7244
7245 ValExpr = Value.get();
7246 // The expression must evaluate to a non-negative integer value.
7247 llvm::APSInt Result;
7248 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007249 Result.isSigned() &&
7250 !((!StrictlyPositive && Result.isNonNegative()) ||
7251 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007252 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007253 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7254 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007255 return false;
7256 }
7257 }
7258 return true;
7259}
7260
Alexey Bataev568a8332014-03-06 06:15:19 +00007261OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7262 SourceLocation StartLoc,
7263 SourceLocation LParenLoc,
7264 SourceLocation EndLoc) {
7265 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007266 Stmt *HelperValStmt = nullptr;
7267 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007268
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007269 // OpenMP [2.5, Restrictions]
7270 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007271 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7272 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007273 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007274
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007275 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7276 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7277 if (CaptureRegion != OMPD_unknown) {
7278 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7279 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7280 HelperValStmt = buildPreInits(Context, Captures);
7281 }
7282
7283 return new (Context) OMPNumThreadsClause(
7284 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007285}
7286
Alexey Bataev62c87d22014-03-21 04:51:18 +00007287ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007288 OpenMPClauseKind CKind,
7289 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007290 if (!E)
7291 return ExprError();
7292 if (E->isValueDependent() || E->isTypeDependent() ||
7293 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007294 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007295 llvm::APSInt Result;
7296 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7297 if (ICE.isInvalid())
7298 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007299 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7300 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007301 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007302 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7303 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007304 return ExprError();
7305 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007306 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7307 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7308 << E->getSourceRange();
7309 return ExprError();
7310 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007311 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7312 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007313 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007314 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007315 return ICE;
7316}
7317
7318OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7319 SourceLocation LParenLoc,
7320 SourceLocation EndLoc) {
7321 // OpenMP [2.8.1, simd construct, Description]
7322 // The parameter of the safelen clause must be a constant
7323 // positive integer expression.
7324 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7325 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007326 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007327 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007328 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007329}
7330
Alexey Bataev66b15b52015-08-21 11:14:16 +00007331OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7332 SourceLocation LParenLoc,
7333 SourceLocation EndLoc) {
7334 // OpenMP [2.8.1, simd construct, Description]
7335 // The parameter of the simdlen clause must be a constant
7336 // positive integer expression.
7337 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7338 if (Simdlen.isInvalid())
7339 return nullptr;
7340 return new (Context)
7341 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7342}
7343
Alexander Musman64d33f12014-06-04 07:53:32 +00007344OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7345 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007346 SourceLocation LParenLoc,
7347 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007348 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007349 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007350 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007351 // The parameter of the collapse clause must be a constant
7352 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007353 ExprResult NumForLoopsResult =
7354 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7355 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007356 return nullptr;
7357 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007358 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007359}
7360
Alexey Bataev10e775f2015-07-30 11:36:16 +00007361OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7362 SourceLocation EndLoc,
7363 SourceLocation LParenLoc,
7364 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007365 // OpenMP [2.7.1, loop construct, Description]
7366 // OpenMP [2.8.1, simd construct, Description]
7367 // OpenMP [2.9.6, distribute construct, Description]
7368 // The parameter of the ordered clause must be a constant
7369 // positive integer expression if any.
7370 if (NumForLoops && LParenLoc.isValid()) {
7371 ExprResult NumForLoopsResult =
7372 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7373 if (NumForLoopsResult.isInvalid())
7374 return nullptr;
7375 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007376 } else
7377 NumForLoops = nullptr;
7378 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007379 return new (Context)
7380 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7381}
7382
Alexey Bataeved09d242014-05-28 05:53:51 +00007383OMPClause *Sema::ActOnOpenMPSimpleClause(
7384 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7385 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007386 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007387 switch (Kind) {
7388 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007389 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007390 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7391 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007392 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007393 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007394 Res = ActOnOpenMPProcBindClause(
7395 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7396 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007397 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007398 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007399 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007400 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007401 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007402 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007403 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007404 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007405 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007406 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007407 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007408 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007409 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007410 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007411 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007412 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007413 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007414 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007415 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007416 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007417 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007418 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007419 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007420 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007421 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007422 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007423 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007424 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007425 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007426 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007427 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007428 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007429 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007430 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007431 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007432 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007433 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007434 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007435 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007436 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007437 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007438 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007439 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007440 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007441 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007442 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007443 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007444 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007445 llvm_unreachable("Clause is not allowed.");
7446 }
7447 return Res;
7448}
7449
Alexey Bataev6402bca2015-12-28 07:25:51 +00007450static std::string
7451getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7452 ArrayRef<unsigned> Exclude = llvm::None) {
7453 std::string Values;
7454 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7455 unsigned Skipped = Exclude.size();
7456 auto S = Exclude.begin(), E = Exclude.end();
7457 for (unsigned i = First; i < Last; ++i) {
7458 if (std::find(S, E, i) != E) {
7459 --Skipped;
7460 continue;
7461 }
7462 Values += "'";
7463 Values += getOpenMPSimpleClauseTypeName(K, i);
7464 Values += "'";
7465 if (i == Bound - Skipped)
7466 Values += " or ";
7467 else if (i != Bound + 1 - Skipped)
7468 Values += ", ";
7469 }
7470 return Values;
7471}
7472
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007473OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7474 SourceLocation KindKwLoc,
7475 SourceLocation StartLoc,
7476 SourceLocation LParenLoc,
7477 SourceLocation EndLoc) {
7478 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007479 static_assert(OMPC_DEFAULT_unknown > 0,
7480 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007481 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007482 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7483 /*Last=*/OMPC_DEFAULT_unknown)
7484 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007485 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007486 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007487 switch (Kind) {
7488 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007489 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007490 break;
7491 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007492 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007493 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007494 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007495 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007496 break;
7497 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007498 return new (Context)
7499 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007500}
7501
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007502OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7503 SourceLocation KindKwLoc,
7504 SourceLocation StartLoc,
7505 SourceLocation LParenLoc,
7506 SourceLocation EndLoc) {
7507 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007508 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007509 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7510 /*Last=*/OMPC_PROC_BIND_unknown)
7511 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007512 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007513 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007514 return new (Context)
7515 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007516}
7517
Alexey Bataev56dafe82014-06-20 07:16:17 +00007518OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007519 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007520 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007521 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007522 SourceLocation EndLoc) {
7523 OMPClause *Res = nullptr;
7524 switch (Kind) {
7525 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007526 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7527 assert(Argument.size() == NumberOfElements &&
7528 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007529 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007530 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7531 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7532 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7533 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7534 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007535 break;
7536 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007537 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7538 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7539 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7540 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007541 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007542 case OMPC_dist_schedule:
7543 Res = ActOnOpenMPDistScheduleClause(
7544 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7545 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7546 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007547 case OMPC_defaultmap:
7548 enum { Modifier, DefaultmapKind };
7549 Res = ActOnOpenMPDefaultmapClause(
7550 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7551 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007552 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7553 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007554 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007555 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007556 case OMPC_num_threads:
7557 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007558 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007559 case OMPC_collapse:
7560 case OMPC_default:
7561 case OMPC_proc_bind:
7562 case OMPC_private:
7563 case OMPC_firstprivate:
7564 case OMPC_lastprivate:
7565 case OMPC_shared:
7566 case OMPC_reduction:
7567 case OMPC_linear:
7568 case OMPC_aligned:
7569 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007570 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007571 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007572 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007573 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007574 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007575 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007576 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007577 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007578 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007579 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007580 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007581 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007582 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007583 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007584 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007585 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007586 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007587 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007588 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007589 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007590 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007591 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007592 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007593 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007594 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007595 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007596 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007597 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007598 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007599 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007600 llvm_unreachable("Clause is not allowed.");
7601 }
7602 return Res;
7603}
7604
Alexey Bataev6402bca2015-12-28 07:25:51 +00007605static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7606 OpenMPScheduleClauseModifier M2,
7607 SourceLocation M1Loc, SourceLocation M2Loc) {
7608 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7609 SmallVector<unsigned, 2> Excluded;
7610 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7611 Excluded.push_back(M2);
7612 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7613 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7614 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7615 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7616 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7617 << getListOfPossibleValues(OMPC_schedule,
7618 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7619 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7620 Excluded)
7621 << getOpenMPClauseName(OMPC_schedule);
7622 return true;
7623 }
7624 return false;
7625}
7626
Alexey Bataev56dafe82014-06-20 07:16:17 +00007627OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007628 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007629 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007630 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7631 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7632 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7633 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7634 return nullptr;
7635 // OpenMP, 2.7.1, Loop Construct, Restrictions
7636 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7637 // but not both.
7638 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7639 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7640 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7641 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7642 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7643 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7644 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7645 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7646 return nullptr;
7647 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007648 if (Kind == OMPC_SCHEDULE_unknown) {
7649 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007650 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7651 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7652 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7653 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7654 Exclude);
7655 } else {
7656 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7657 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007658 }
7659 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7660 << Values << getOpenMPClauseName(OMPC_schedule);
7661 return nullptr;
7662 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007663 // OpenMP, 2.7.1, Loop Construct, Restrictions
7664 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7665 // schedule(guided).
7666 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7667 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7668 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7669 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7670 diag::err_omp_schedule_nonmonotonic_static);
7671 return nullptr;
7672 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007673 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007674 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007675 if (ChunkSize) {
7676 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7677 !ChunkSize->isInstantiationDependent() &&
7678 !ChunkSize->containsUnexpandedParameterPack()) {
7679 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7680 ExprResult Val =
7681 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7682 if (Val.isInvalid())
7683 return nullptr;
7684
7685 ValExpr = Val.get();
7686
7687 // OpenMP [2.7.1, Restrictions]
7688 // chunk_size must be a loop invariant integer expression with a positive
7689 // value.
7690 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007691 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7692 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7693 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007694 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007695 return nullptr;
7696 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007697 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7698 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007699 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7700 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7701 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007702 }
7703 }
7704 }
7705
Alexey Bataev6402bca2015-12-28 07:25:51 +00007706 return new (Context)
7707 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007708 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007709}
7710
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007711OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7712 SourceLocation StartLoc,
7713 SourceLocation EndLoc) {
7714 OMPClause *Res = nullptr;
7715 switch (Kind) {
7716 case OMPC_ordered:
7717 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7718 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007719 case OMPC_nowait:
7720 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7721 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007722 case OMPC_untied:
7723 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7724 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007725 case OMPC_mergeable:
7726 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7727 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007728 case OMPC_read:
7729 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7730 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007731 case OMPC_write:
7732 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7733 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007734 case OMPC_update:
7735 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7736 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007737 case OMPC_capture:
7738 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7739 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007740 case OMPC_seq_cst:
7741 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7742 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007743 case OMPC_threads:
7744 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7745 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007746 case OMPC_simd:
7747 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7748 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007749 case OMPC_nogroup:
7750 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7751 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007752 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007753 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007754 case OMPC_num_threads:
7755 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007756 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007757 case OMPC_collapse:
7758 case OMPC_schedule:
7759 case OMPC_private:
7760 case OMPC_firstprivate:
7761 case OMPC_lastprivate:
7762 case OMPC_shared:
7763 case OMPC_reduction:
7764 case OMPC_linear:
7765 case OMPC_aligned:
7766 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007767 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007768 case OMPC_default:
7769 case OMPC_proc_bind:
7770 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007771 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007772 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007773 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007774 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007775 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007776 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007777 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007778 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007779 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007780 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007781 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007782 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007783 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007784 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007785 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007786 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007787 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007788 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007789 llvm_unreachable("Clause is not allowed.");
7790 }
7791 return Res;
7792}
7793
Alexey Bataev236070f2014-06-20 11:19:47 +00007794OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7795 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007796 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007797 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7798}
7799
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007800OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7801 SourceLocation EndLoc) {
7802 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7803}
7804
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007805OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7806 SourceLocation EndLoc) {
7807 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7808}
7809
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007810OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7811 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007812 return new (Context) OMPReadClause(StartLoc, EndLoc);
7813}
7814
Alexey Bataevdea47612014-07-23 07:46:59 +00007815OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7816 SourceLocation EndLoc) {
7817 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7818}
7819
Alexey Bataev67a4f222014-07-23 10:25:33 +00007820OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7821 SourceLocation EndLoc) {
7822 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7823}
7824
Alexey Bataev459dec02014-07-24 06:46:57 +00007825OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7826 SourceLocation EndLoc) {
7827 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7828}
7829
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007830OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7831 SourceLocation EndLoc) {
7832 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7833}
7834
Alexey Bataev346265e2015-09-25 10:37:12 +00007835OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7836 SourceLocation EndLoc) {
7837 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7838}
7839
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007840OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7841 SourceLocation EndLoc) {
7842 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7843}
7844
Alexey Bataevb825de12015-12-07 10:51:44 +00007845OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7846 SourceLocation EndLoc) {
7847 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7848}
7849
Alexey Bataevc5e02582014-06-16 07:08:35 +00007850OMPClause *Sema::ActOnOpenMPVarListClause(
7851 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7852 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7853 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007854 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007855 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7856 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7857 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007858 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007859 switch (Kind) {
7860 case OMPC_private:
7861 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7862 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007863 case OMPC_firstprivate:
7864 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7865 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007866 case OMPC_lastprivate:
7867 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7868 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007869 case OMPC_shared:
7870 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7871 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007872 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007873 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7874 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007875 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007876 case OMPC_linear:
7877 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007878 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007879 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007880 case OMPC_aligned:
7881 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7882 ColonLoc, EndLoc);
7883 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007884 case OMPC_copyin:
7885 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7886 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007887 case OMPC_copyprivate:
7888 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7889 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007890 case OMPC_flush:
7891 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7892 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007893 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007894 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007895 StartLoc, LParenLoc, EndLoc);
7896 break;
7897 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007898 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7899 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7900 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007901 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007902 case OMPC_to:
7903 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7904 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007905 case OMPC_from:
7906 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7907 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007908 case OMPC_use_device_ptr:
7909 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7910 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007911 case OMPC_is_device_ptr:
7912 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7913 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007914 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007915 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007916 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007917 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007918 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007919 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007920 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007921 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007922 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007923 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007924 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007925 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007926 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007927 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007928 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007929 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007930 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007931 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007932 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007933 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007934 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007935 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007936 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007937 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007938 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007939 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007940 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007941 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007942 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007943 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007944 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007945 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007946 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007947 llvm_unreachable("Clause is not allowed.");
7948 }
7949 return Res;
7950}
7951
Alexey Bataev90c228f2016-02-08 09:29:13 +00007952ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007953 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007954 ExprResult Res = BuildDeclRefExpr(
7955 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7956 if (!Res.isUsable())
7957 return ExprError();
7958 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7959 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7960 if (!Res.isUsable())
7961 return ExprError();
7962 }
7963 if (VK != VK_LValue && Res.get()->isGLValue()) {
7964 Res = DefaultLvalueConversion(Res.get());
7965 if (!Res.isUsable())
7966 return ExprError();
7967 }
7968 return Res;
7969}
7970
Alexey Bataev60da77e2016-02-29 05:54:20 +00007971static std::pair<ValueDecl *, bool>
7972getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7973 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007974 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7975 RefExpr->containsUnexpandedParameterPack())
7976 return std::make_pair(nullptr, true);
7977
Alexey Bataevd985eda2016-02-10 11:29:16 +00007978 // OpenMP [3.1, C/C++]
7979 // A list item is a variable name.
7980 // OpenMP [2.9.3.3, Restrictions, p.1]
7981 // A variable that is part of another variable (as an array or
7982 // structure element) cannot appear in a private clause.
7983 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007984 enum {
7985 NoArrayExpr = -1,
7986 ArraySubscript = 0,
7987 OMPArraySection = 1
7988 } IsArrayExpr = NoArrayExpr;
7989 if (AllowArraySection) {
7990 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7991 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7992 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7993 Base = TempASE->getBase()->IgnoreParenImpCasts();
7994 RefExpr = Base;
7995 IsArrayExpr = ArraySubscript;
7996 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7997 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7998 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7999 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8000 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8001 Base = TempASE->getBase()->IgnoreParenImpCasts();
8002 RefExpr = Base;
8003 IsArrayExpr = OMPArraySection;
8004 }
8005 }
8006 ELoc = RefExpr->getExprLoc();
8007 ERange = RefExpr->getSourceRange();
8008 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008009 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8010 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8011 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8012 (S.getCurrentThisType().isNull() || !ME ||
8013 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8014 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008015 if (IsArrayExpr != NoArrayExpr)
8016 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8017 << ERange;
8018 else {
8019 S.Diag(ELoc,
8020 AllowArraySection
8021 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8022 : diag::err_omp_expected_var_name_member_expr)
8023 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8024 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008025 return std::make_pair(nullptr, false);
8026 }
8027 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
8028}
8029
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008030OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8031 SourceLocation StartLoc,
8032 SourceLocation LParenLoc,
8033 SourceLocation EndLoc) {
8034 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008035 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008036 for (auto &RefExpr : VarList) {
8037 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008038 SourceLocation ELoc;
8039 SourceRange ERange;
8040 Expr *SimpleRefExpr = RefExpr;
8041 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008042 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008043 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008044 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008045 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008046 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008047 ValueDecl *D = Res.first;
8048 if (!D)
8049 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008050
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008051 QualType Type = D->getType();
8052 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008053
8054 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8055 // A variable that appears in a private clause must not have an incomplete
8056 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008057 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008058 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008059 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008060
Alexey Bataev758e55e2013-09-06 18:03:48 +00008061 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8062 // in a Construct]
8063 // Variables with the predetermined data-sharing attributes may not be
8064 // listed in data-sharing attributes clauses, except for the cases
8065 // listed below. For these exceptions only, listing a predetermined
8066 // variable in a data-sharing attribute clause is allowed and overrides
8067 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008068 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008069 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008070 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8071 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008072 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008073 continue;
8074 }
8075
Kelvin Libf594a52016-12-17 05:48:59 +00008076 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008077 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008078 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008079 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008080 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8081 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008082 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008083 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008084 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008085 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008086 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008087 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008088 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008089 continue;
8090 }
8091
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008092 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8093 // A list item cannot appear in both a map clause and a data-sharing
8094 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008095 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008096 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008097 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008098 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008099 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008100 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008101 CurrDir == OMPD_target_parallel_for_simd ||
8102 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008103 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008104 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008105 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008106 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8107 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8108 ConflictKind = WhereFoundClauseKind;
8109 return true;
8110 })) {
8111 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008112 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008113 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008114 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008115 ReportOriginalDSA(*this, DSAStack, D, DVar);
8116 continue;
8117 }
8118 }
8119
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008120 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8121 // A variable of class type (or array thereof) that appears in a private
8122 // clause requires an accessible, unambiguous default constructor for the
8123 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008124 // Generate helper private variable and initialize it with the default
8125 // value. The address of the original variable is replaced by the address of
8126 // the new private variable in CodeGen. This new variable is not added to
8127 // IdResolver, so the code in the OpenMP region uses original variable for
8128 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008129 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008130 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8131 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008132 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008133 if (VDPrivate->isInvalidDecl())
8134 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008135 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008136 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008137
Alexey Bataev90c228f2016-02-08 09:29:13 +00008138 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008139 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008140 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008141 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008142 Vars.push_back((VD || CurContext->isDependentContext())
8143 ? RefExpr->IgnoreParens()
8144 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008145 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008146 }
8147
Alexey Bataeved09d242014-05-28 05:53:51 +00008148 if (Vars.empty())
8149 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008150
Alexey Bataev03b340a2014-10-21 03:16:40 +00008151 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8152 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008153}
8154
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008155namespace {
8156class DiagsUninitializedSeveretyRAII {
8157private:
8158 DiagnosticsEngine &Diags;
8159 SourceLocation SavedLoc;
8160 bool IsIgnored;
8161
8162public:
8163 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8164 bool IsIgnored)
8165 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8166 if (!IsIgnored) {
8167 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8168 /*Map*/ diag::Severity::Ignored, Loc);
8169 }
8170 }
8171 ~DiagsUninitializedSeveretyRAII() {
8172 if (!IsIgnored)
8173 Diags.popMappings(SavedLoc);
8174 }
8175};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008176}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008177
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008178OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8179 SourceLocation StartLoc,
8180 SourceLocation LParenLoc,
8181 SourceLocation EndLoc) {
8182 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008183 SmallVector<Expr *, 8> PrivateCopies;
8184 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008185 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008186 bool IsImplicitClause =
8187 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8188 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8189
Alexey Bataeved09d242014-05-28 05:53:51 +00008190 for (auto &RefExpr : VarList) {
8191 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008192 SourceLocation ELoc;
8193 SourceRange ERange;
8194 Expr *SimpleRefExpr = RefExpr;
8195 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008196 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008197 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008198 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008199 PrivateCopies.push_back(nullptr);
8200 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008201 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008202 ValueDecl *D = Res.first;
8203 if (!D)
8204 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008205
Alexey Bataev60da77e2016-02-29 05:54:20 +00008206 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008207 QualType Type = D->getType();
8208 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008209
8210 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8211 // A variable that appears in a private clause must not have an incomplete
8212 // type or a reference type.
8213 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008214 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008215 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008216 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008217
8218 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8219 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008220 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008221 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008222 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008223
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008224 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008225 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008226 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008227 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008228 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008229 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008230 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8231 // A list item that specifies a given variable may not appear in more
8232 // than one clause on the same directive, except that a variable may be
8233 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008234 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00008235 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008236 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008237 << getOpenMPClauseName(DVar.CKind)
8238 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008239 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008240 continue;
8241 }
8242
8243 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8244 // in a Construct]
8245 // Variables with the predetermined data-sharing attributes may not be
8246 // listed in data-sharing attributes clauses, except for the cases
8247 // listed below. For these exceptions only, listing a predetermined
8248 // variable in a data-sharing attribute clause is allowed and overrides
8249 // the variable's predetermined data-sharing attributes.
8250 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8251 // in a Construct, C/C++, p.2]
8252 // Variables with const-qualified type having no mutable member may be
8253 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008254 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008255 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8256 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008257 << getOpenMPClauseName(DVar.CKind)
8258 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008259 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008260 continue;
8261 }
8262
Alexey Bataevf29276e2014-06-18 04:14:57 +00008263 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008264 // OpenMP [2.9.3.4, Restrictions, p.2]
8265 // A list item that is private within a parallel region must not appear
8266 // in a firstprivate clause on a worksharing construct if any of the
8267 // worksharing regions arising from the worksharing construct ever bind
8268 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008269 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008270 !isOpenMPParallelDirective(CurrDir) &&
8271 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008272 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008273 if (DVar.CKind != OMPC_shared &&
8274 (isOpenMPParallelDirective(DVar.DKind) ||
8275 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008276 Diag(ELoc, diag::err_omp_required_access)
8277 << getOpenMPClauseName(OMPC_firstprivate)
8278 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008279 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008280 continue;
8281 }
8282 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008283 // OpenMP [2.9.3.4, Restrictions, p.3]
8284 // A list item that appears in a reduction clause of a parallel construct
8285 // must not appear in a firstprivate clause on a worksharing or task
8286 // construct if any of the worksharing or task regions arising from the
8287 // worksharing or task construct ever bind to any of the parallel regions
8288 // arising from the parallel construct.
8289 // OpenMP [2.9.3.4, Restrictions, p.4]
8290 // A list item that appears in a reduction clause in worksharing
8291 // construct must not appear in a firstprivate clause in a task construct
8292 // encountered during execution of any of the worksharing regions arising
8293 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008294 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008295 DVar = DSAStack->hasInnermostDSA(
8296 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8297 [](OpenMPDirectiveKind K) -> bool {
8298 return isOpenMPParallelDirective(K) ||
8299 isOpenMPWorksharingDirective(K);
8300 },
8301 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008302 if (DVar.CKind == OMPC_reduction &&
8303 (isOpenMPParallelDirective(DVar.DKind) ||
8304 isOpenMPWorksharingDirective(DVar.DKind))) {
8305 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8306 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008307 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008308 continue;
8309 }
8310 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008311
8312 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8313 // A list item that is private within a teams region must not appear in a
8314 // firstprivate clause on a distribute construct if any of the distribute
8315 // regions arising from the distribute construct ever bind to any of the
8316 // teams regions arising from the teams construct.
8317 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8318 // A list item that appears in a reduction clause of a teams construct
8319 // must not appear in a firstprivate clause on a distribute construct if
8320 // any of the distribute regions arising from the distribute construct
8321 // ever bind to any of the teams regions arising from the teams construct.
8322 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8323 // A list item may appear in a firstprivate or lastprivate clause but not
8324 // both.
8325 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008326 DVar = DSAStack->hasInnermostDSA(
8327 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8328 [](OpenMPDirectiveKind K) -> bool {
8329 return isOpenMPTeamsDirective(K);
8330 },
8331 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008332 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8333 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008334 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008335 continue;
8336 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008337 DVar = DSAStack->hasInnermostDSA(
8338 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8339 [](OpenMPDirectiveKind K) -> bool {
8340 return isOpenMPTeamsDirective(K);
8341 },
8342 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008343 if (DVar.CKind == OMPC_reduction &&
8344 isOpenMPTeamsDirective(DVar.DKind)) {
8345 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008346 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008347 continue;
8348 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008349 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008350 if (DVar.CKind == OMPC_lastprivate) {
8351 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008352 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008353 continue;
8354 }
8355 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008356 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8357 // A list item cannot appear in both a map clause and a data-sharing
8358 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008359 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008360 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008361 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008362 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008363 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008364 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008365 CurrDir == OMPD_target_parallel_for_simd ||
8366 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008367 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008368 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008369 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008370 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8371 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8372 ConflictKind = WhereFoundClauseKind;
8373 return true;
8374 })) {
8375 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008376 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008377 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008378 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8379 ReportOriginalDSA(*this, DSAStack, D, DVar);
8380 continue;
8381 }
8382 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008383 }
8384
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008385 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008386 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008387 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008388 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8389 << getOpenMPClauseName(OMPC_firstprivate) << Type
8390 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8391 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008392 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008393 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008394 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008395 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008396 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008397 continue;
8398 }
8399
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008400 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008401 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8402 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008403 // Generate helper private variable and initialize it with the value of the
8404 // original variable. The address of the original variable is replaced by
8405 // the address of the new private variable in the CodeGen. This new variable
8406 // is not added to IdResolver, so the code in the OpenMP region uses
8407 // original variable for proper diagnostics and variable capturing.
8408 Expr *VDInitRefExpr = nullptr;
8409 // For arrays generate initializer for single element and replace it by the
8410 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008411 if (Type->isArrayType()) {
8412 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008413 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008414 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008415 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008416 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008417 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008418 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008419 InitializedEntity Entity =
8420 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008421 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8422
8423 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8424 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8425 if (Result.isInvalid())
8426 VDPrivate->setInvalidDecl();
8427 else
8428 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008429 // Remove temp variable declaration.
8430 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008431 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008432 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8433 ".firstprivate.temp");
8434 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8435 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008436 AddInitializerToDecl(VDPrivate,
8437 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008438 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008439 }
8440 if (VDPrivate->isInvalidDecl()) {
8441 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008442 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008443 diag::note_omp_task_predetermined_firstprivate_here);
8444 }
8445 continue;
8446 }
8447 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008448 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008449 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8450 RefExpr->getExprLoc());
8451 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008452 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008453 if (TopDVar.CKind == OMPC_lastprivate)
8454 Ref = TopDVar.PrivateCopy;
8455 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008456 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008457 if (!IsOpenMPCapturedDecl(D))
8458 ExprCaptures.push_back(Ref->getDecl());
8459 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008460 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008461 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008462 Vars.push_back((VD || CurContext->isDependentContext())
8463 ? RefExpr->IgnoreParens()
8464 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008465 PrivateCopies.push_back(VDPrivateRefExpr);
8466 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008467 }
8468
Alexey Bataeved09d242014-05-28 05:53:51 +00008469 if (Vars.empty())
8470 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008471
8472 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008473 Vars, PrivateCopies, Inits,
8474 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008475}
8476
Alexander Musman1bb328c2014-06-04 13:06:39 +00008477OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8478 SourceLocation StartLoc,
8479 SourceLocation LParenLoc,
8480 SourceLocation EndLoc) {
8481 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008482 SmallVector<Expr *, 8> SrcExprs;
8483 SmallVector<Expr *, 8> DstExprs;
8484 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008485 SmallVector<Decl *, 4> ExprCaptures;
8486 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008487 for (auto &RefExpr : VarList) {
8488 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008489 SourceLocation ELoc;
8490 SourceRange ERange;
8491 Expr *SimpleRefExpr = RefExpr;
8492 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008493 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008494 // It will be analyzed later.
8495 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008496 SrcExprs.push_back(nullptr);
8497 DstExprs.push_back(nullptr);
8498 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008499 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008500 ValueDecl *D = Res.first;
8501 if (!D)
8502 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008503
Alexey Bataev74caaf22016-02-20 04:09:36 +00008504 QualType Type = D->getType();
8505 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008506
8507 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8508 // A variable that appears in a lastprivate clause must not have an
8509 // incomplete type or a reference type.
8510 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008511 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008512 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008513 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008514
8515 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8516 // in a Construct]
8517 // Variables with the predetermined data-sharing attributes may not be
8518 // listed in data-sharing attributes clauses, except for the cases
8519 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008520 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008521 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8522 DVar.CKind != OMPC_firstprivate &&
8523 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8524 Diag(ELoc, diag::err_omp_wrong_dsa)
8525 << getOpenMPClauseName(DVar.CKind)
8526 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008527 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008528 continue;
8529 }
8530
Alexey Bataevf29276e2014-06-18 04:14:57 +00008531 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8532 // OpenMP [2.14.3.5, Restrictions, p.2]
8533 // A list item that is private within a parallel region, or that appears in
8534 // the reduction clause of a parallel construct, must not appear in a
8535 // lastprivate clause on a worksharing construct if any of the corresponding
8536 // worksharing regions ever binds to any of the corresponding parallel
8537 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008538 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008539 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008540 !isOpenMPParallelDirective(CurrDir) &&
8541 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008542 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008543 if (DVar.CKind != OMPC_shared) {
8544 Diag(ELoc, diag::err_omp_required_access)
8545 << getOpenMPClauseName(OMPC_lastprivate)
8546 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008547 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008548 continue;
8549 }
8550 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008551
8552 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8553 // A list item may appear in a firstprivate or lastprivate clause but not
8554 // both.
8555 if (CurrDir == OMPD_distribute) {
8556 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8557 if (DVar.CKind == OMPC_firstprivate) {
8558 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8559 ReportOriginalDSA(*this, DSAStack, D, DVar);
8560 continue;
8561 }
8562 }
8563
Alexander Musman1bb328c2014-06-04 13:06:39 +00008564 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008565 // A variable of class type (or array thereof) that appears in a
8566 // lastprivate clause requires an accessible, unambiguous default
8567 // constructor for the class type, unless the list item is also specified
8568 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008569 // A variable of class type (or array thereof) that appears in a
8570 // lastprivate clause requires an accessible, unambiguous copy assignment
8571 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008572 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008573 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008574 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008575 D->hasAttrs() ? &D->getAttrs() : nullptr);
8576 auto *PseudoSrcExpr =
8577 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008578 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008579 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008580 D->hasAttrs() ? &D->getAttrs() : nullptr);
8581 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008582 // For arrays generate assignment operation for single element and replace
8583 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008584 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008585 PseudoDstExpr, PseudoSrcExpr);
8586 if (AssignmentOp.isInvalid())
8587 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008588 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008589 /*DiscardedValue=*/true);
8590 if (AssignmentOp.isInvalid())
8591 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008592
Alexey Bataev74caaf22016-02-20 04:09:36 +00008593 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008594 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008595 if (TopDVar.CKind == OMPC_firstprivate)
8596 Ref = TopDVar.PrivateCopy;
8597 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008598 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008599 if (!IsOpenMPCapturedDecl(D))
8600 ExprCaptures.push_back(Ref->getDecl());
8601 }
8602 if (TopDVar.CKind == OMPC_firstprivate ||
8603 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008604 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008605 ExprResult RefRes = DefaultLvalueConversion(Ref);
8606 if (!RefRes.isUsable())
8607 continue;
8608 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008609 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8610 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008611 if (!PostUpdateRes.isUsable())
8612 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008613 ExprPostUpdates.push_back(
8614 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008615 }
8616 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008617 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008618 Vars.push_back((VD || CurContext->isDependentContext())
8619 ? RefExpr->IgnoreParens()
8620 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008621 SrcExprs.push_back(PseudoSrcExpr);
8622 DstExprs.push_back(PseudoDstExpr);
8623 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008624 }
8625
8626 if (Vars.empty())
8627 return nullptr;
8628
8629 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008630 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008631 buildPreInits(Context, ExprCaptures),
8632 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008633}
8634
Alexey Bataev758e55e2013-09-06 18:03:48 +00008635OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8636 SourceLocation StartLoc,
8637 SourceLocation LParenLoc,
8638 SourceLocation EndLoc) {
8639 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008640 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008641 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008642 SourceLocation ELoc;
8643 SourceRange ERange;
8644 Expr *SimpleRefExpr = RefExpr;
8645 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008646 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008647 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008648 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008649 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008650 ValueDecl *D = Res.first;
8651 if (!D)
8652 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008653
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008654 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008655 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8656 // in a Construct]
8657 // Variables with the predetermined data-sharing attributes may not be
8658 // listed in data-sharing attributes clauses, except for the cases
8659 // listed below. For these exceptions only, listing a predetermined
8660 // variable in a data-sharing attribute clause is allowed and overrides
8661 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008662 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008663 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8664 DVar.RefExpr) {
8665 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8666 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008667 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008668 continue;
8669 }
8670
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008671 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008672 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008673 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008674 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008675 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8676 ? RefExpr->IgnoreParens()
8677 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008678 }
8679
Alexey Bataeved09d242014-05-28 05:53:51 +00008680 if (Vars.empty())
8681 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008682
8683 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8684}
8685
Alexey Bataevc5e02582014-06-16 07:08:35 +00008686namespace {
8687class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8688 DSAStackTy *Stack;
8689
8690public:
8691 bool VisitDeclRefExpr(DeclRefExpr *E) {
8692 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008693 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008694 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8695 return false;
8696 if (DVar.CKind != OMPC_unknown)
8697 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008698 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8699 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8700 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008701 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008702 return true;
8703 return false;
8704 }
8705 return false;
8706 }
8707 bool VisitStmt(Stmt *S) {
8708 for (auto Child : S->children()) {
8709 if (Child && Visit(Child))
8710 return true;
8711 }
8712 return false;
8713 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008714 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008715};
Alexey Bataev23b69422014-06-18 07:08:49 +00008716} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008717
Alexey Bataev60da77e2016-02-29 05:54:20 +00008718namespace {
8719// Transform MemberExpression for specified FieldDecl of current class to
8720// DeclRefExpr to specified OMPCapturedExprDecl.
8721class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8722 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8723 ValueDecl *Field;
8724 DeclRefExpr *CapturedExpr;
8725
8726public:
8727 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8728 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8729
8730 ExprResult TransformMemberExpr(MemberExpr *E) {
8731 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8732 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008733 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008734 return CapturedExpr;
8735 }
8736 return BaseTransform::TransformMemberExpr(E);
8737 }
8738 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8739};
8740} // namespace
8741
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008742template <typename T>
8743static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8744 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8745 for (auto &Set : Lookups) {
8746 for (auto *D : Set) {
8747 if (auto Res = Gen(cast<ValueDecl>(D)))
8748 return Res;
8749 }
8750 }
8751 return T();
8752}
8753
8754static ExprResult
8755buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8756 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8757 const DeclarationNameInfo &ReductionId, QualType Ty,
8758 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8759 if (ReductionIdScopeSpec.isInvalid())
8760 return ExprError();
8761 SmallVector<UnresolvedSet<8>, 4> Lookups;
8762 if (S) {
8763 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8764 Lookup.suppressDiagnostics();
8765 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8766 auto *D = Lookup.getRepresentativeDecl();
8767 do {
8768 S = S->getParent();
8769 } while (S && !S->isDeclScope(D));
8770 if (S)
8771 S = S->getParent();
8772 Lookups.push_back(UnresolvedSet<8>());
8773 Lookups.back().append(Lookup.begin(), Lookup.end());
8774 Lookup.clear();
8775 }
8776 } else if (auto *ULE =
8777 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8778 Lookups.push_back(UnresolvedSet<8>());
8779 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008780 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008781 if (D == PrevD)
8782 Lookups.push_back(UnresolvedSet<8>());
8783 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8784 Lookups.back().addDecl(DRD);
8785 PrevD = D;
8786 }
8787 }
8788 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8789 Ty->containsUnexpandedParameterPack() ||
8790 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8791 return !D->isInvalidDecl() &&
8792 (D->getType()->isDependentType() ||
8793 D->getType()->isInstantiationDependentType() ||
8794 D->getType()->containsUnexpandedParameterPack());
8795 })) {
8796 UnresolvedSet<8> ResSet;
8797 for (auto &Set : Lookups) {
8798 ResSet.append(Set.begin(), Set.end());
8799 // The last item marks the end of all declarations at the specified scope.
8800 ResSet.addDecl(Set[Set.size() - 1]);
8801 }
8802 return UnresolvedLookupExpr::Create(
8803 SemaRef.Context, /*NamingClass=*/nullptr,
8804 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8805 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8806 }
8807 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8808 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8809 if (!D->isInvalidDecl() &&
8810 SemaRef.Context.hasSameType(D->getType(), Ty))
8811 return D;
8812 return nullptr;
8813 }))
8814 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8815 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8816 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8817 if (!D->isInvalidDecl() &&
8818 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8819 !Ty.isMoreQualifiedThan(D->getType()))
8820 return D;
8821 return nullptr;
8822 })) {
8823 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8824 /*DetectVirtual=*/false);
8825 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8826 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8827 VD->getType().getUnqualifiedType()))) {
8828 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8829 /*DiagID=*/0) !=
8830 Sema::AR_inaccessible) {
8831 SemaRef.BuildBasePathArray(Paths, BasePath);
8832 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8833 }
8834 }
8835 }
8836 }
8837 if (ReductionIdScopeSpec.isSet()) {
8838 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8839 return ExprError();
8840 }
8841 return ExprEmpty();
8842}
8843
Alexey Bataevc5e02582014-06-16 07:08:35 +00008844OMPClause *Sema::ActOnOpenMPReductionClause(
8845 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8846 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008847 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8848 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008849 auto DN = ReductionId.getName();
8850 auto OOK = DN.getCXXOverloadedOperator();
8851 BinaryOperatorKind BOK = BO_Comma;
8852
8853 // OpenMP [2.14.3.6, reduction clause]
8854 // C
8855 // reduction-identifier is either an identifier or one of the following
8856 // operators: +, -, *, &, |, ^, && and ||
8857 // C++
8858 // reduction-identifier is either an id-expression or one of the following
8859 // operators: +, -, *, &, |, ^, && and ||
8860 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8861 switch (OOK) {
8862 case OO_Plus:
8863 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008864 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008865 break;
8866 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008867 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008868 break;
8869 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008870 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008871 break;
8872 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008873 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008874 break;
8875 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008876 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008877 break;
8878 case OO_AmpAmp:
8879 BOK = BO_LAnd;
8880 break;
8881 case OO_PipePipe:
8882 BOK = BO_LOr;
8883 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008884 case OO_New:
8885 case OO_Delete:
8886 case OO_Array_New:
8887 case OO_Array_Delete:
8888 case OO_Slash:
8889 case OO_Percent:
8890 case OO_Tilde:
8891 case OO_Exclaim:
8892 case OO_Equal:
8893 case OO_Less:
8894 case OO_Greater:
8895 case OO_LessEqual:
8896 case OO_GreaterEqual:
8897 case OO_PlusEqual:
8898 case OO_MinusEqual:
8899 case OO_StarEqual:
8900 case OO_SlashEqual:
8901 case OO_PercentEqual:
8902 case OO_CaretEqual:
8903 case OO_AmpEqual:
8904 case OO_PipeEqual:
8905 case OO_LessLess:
8906 case OO_GreaterGreater:
8907 case OO_LessLessEqual:
8908 case OO_GreaterGreaterEqual:
8909 case OO_EqualEqual:
8910 case OO_ExclaimEqual:
8911 case OO_PlusPlus:
8912 case OO_MinusMinus:
8913 case OO_Comma:
8914 case OO_ArrowStar:
8915 case OO_Arrow:
8916 case OO_Call:
8917 case OO_Subscript:
8918 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008919 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008920 case NUM_OVERLOADED_OPERATORS:
8921 llvm_unreachable("Unexpected reduction identifier");
8922 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008923 if (auto II = DN.getAsIdentifierInfo()) {
8924 if (II->isStr("max"))
8925 BOK = BO_GT;
8926 else if (II->isStr("min"))
8927 BOK = BO_LT;
8928 }
8929 break;
8930 }
8931 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008932 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008933 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008934 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008935
8936 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008937 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008938 SmallVector<Expr *, 8> LHSs;
8939 SmallVector<Expr *, 8> RHSs;
8940 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008941 SmallVector<Decl *, 4> ExprCaptures;
8942 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008943 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8944 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008945 for (auto RefExpr : VarList) {
8946 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008947 // OpenMP [2.1, C/C++]
8948 // A list item is a variable or array section, subject to the restrictions
8949 // specified in Section 2.4 on page 42 and in each of the sections
8950 // describing clauses and directives for which a list appears.
8951 // OpenMP [2.14.3.3, Restrictions, p.1]
8952 // A variable that is part of another variable (as an array or
8953 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008954 if (!FirstIter && IR != ER)
8955 ++IR;
8956 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008957 SourceLocation ELoc;
8958 SourceRange ERange;
8959 Expr *SimpleRefExpr = RefExpr;
8960 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8961 /*AllowArraySection=*/true);
8962 if (Res.second) {
8963 // It will be analyzed later.
8964 Vars.push_back(RefExpr);
8965 Privates.push_back(nullptr);
8966 LHSs.push_back(nullptr);
8967 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008968 // Try to find 'declare reduction' corresponding construct before using
8969 // builtin/overloaded operators.
8970 QualType Type = Context.DependentTy;
8971 CXXCastPath BasePath;
8972 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8973 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8974 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8975 if (CurContext->isDependentContext() &&
8976 (DeclareReductionRef.isUnset() ||
8977 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8978 ReductionOps.push_back(DeclareReductionRef.get());
8979 else
8980 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008981 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008982 ValueDecl *D = Res.first;
8983 if (!D)
8984 continue;
8985
Alexey Bataeva1764212015-09-30 09:22:36 +00008986 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008987 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8988 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8989 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008990 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008991 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008992 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8993 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8994 Type = ATy->getElementType();
8995 else
8996 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008997 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008998 } else
8999 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9000 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009001
Alexey Bataevc5e02582014-06-16 07:08:35 +00009002 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9003 // A variable that appears in a private clause must not have an incomplete
9004 // type or a reference type.
9005 if (RequireCompleteType(ELoc, Type,
9006 diag::err_omp_reduction_incomplete_type))
9007 continue;
9008 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009009 // A list item that appears in a reduction clause must not be
9010 // const-qualified.
9011 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009012 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009013 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009014 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009015 bool IsDecl = !VD ||
9016 VD->isThisDeclarationADefinition(Context) ==
9017 VarDecl::DeclarationOnly;
9018 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00009019 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009020 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009021 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009022 continue;
9023 }
9024 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9025 // If a list-item is a reference type then it must bind to the same object
9026 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009027 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009028 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009029 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009030 DSARefChecker Check(DSAStack);
9031 if (Check.Visit(VDDef->getInit())) {
9032 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
9033 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
9034 continue;
9035 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009036 }
9037 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009038
Alexey Bataevc5e02582014-06-16 07:08:35 +00009039 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9040 // in a Construct]
9041 // Variables with the predetermined data-sharing attributes may not be
9042 // listed in data-sharing attributes clauses, except for the cases
9043 // listed below. For these exceptions only, listing a predetermined
9044 // variable in a data-sharing attribute clause is allowed and overrides
9045 // the variable's predetermined data-sharing attributes.
9046 // OpenMP [2.14.3.6, Restrictions, p.3]
9047 // Any number of reduction clauses can be specified on the directive,
9048 // but a list item can appear only once in the reduction clauses for that
9049 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009050 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009051 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009052 if (DVar.CKind == OMPC_reduction) {
9053 Diag(ELoc, diag::err_omp_once_referenced)
9054 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009055 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009056 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009057 } else if (DVar.CKind != OMPC_unknown) {
9058 Diag(ELoc, diag::err_omp_wrong_dsa)
9059 << getOpenMPClauseName(DVar.CKind)
9060 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009061 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009062 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009063 }
9064
9065 // OpenMP [2.14.3.6, Restrictions, p.1]
9066 // A list item that appears in a reduction clause of a worksharing
9067 // construct must be shared in the parallel regions to which any of the
9068 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009069 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9070 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009071 !isOpenMPParallelDirective(CurrDir) &&
9072 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009073 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009074 if (DVar.CKind != OMPC_shared) {
9075 Diag(ELoc, diag::err_omp_required_access)
9076 << getOpenMPClauseName(OMPC_reduction)
9077 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009078 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009079 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009080 }
9081 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009082
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009083 // Try to find 'declare reduction' corresponding construct before using
9084 // builtin/overloaded operators.
9085 CXXCastPath BasePath;
9086 ExprResult DeclareReductionRef = buildDeclareReductionRef(
9087 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
9088 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9089 if (DeclareReductionRef.isInvalid())
9090 continue;
9091 if (CurContext->isDependentContext() &&
9092 (DeclareReductionRef.isUnset() ||
9093 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
9094 Vars.push_back(RefExpr);
9095 Privates.push_back(nullptr);
9096 LHSs.push_back(nullptr);
9097 RHSs.push_back(nullptr);
9098 ReductionOps.push_back(DeclareReductionRef.get());
9099 continue;
9100 }
9101 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9102 // Not allowed reduction identifier is found.
9103 Diag(ReductionId.getLocStart(),
9104 diag::err_omp_unknown_reduction_identifier)
9105 << Type << ReductionIdRange;
9106 continue;
9107 }
9108
9109 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9110 // The type of a list item that appears in a reduction clause must be valid
9111 // for the reduction-identifier. For a max or min reduction in C, the type
9112 // of the list item must be an allowed arithmetic data type: char, int,
9113 // float, double, or _Bool, possibly modified with long, short, signed, or
9114 // unsigned. For a max or min reduction in C++, the type of the list item
9115 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9116 // double, or bool, possibly modified with long, short, signed, or unsigned.
9117 if (DeclareReductionRef.isUnset()) {
9118 if ((BOK == BO_GT || BOK == BO_LT) &&
9119 !(Type->isScalarType() ||
9120 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9121 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
9122 << getLangOpts().CPlusPlus;
9123 if (!ASE && !OASE) {
9124 bool IsDecl = !VD ||
9125 VD->isThisDeclarationADefinition(Context) ==
9126 VarDecl::DeclarationOnly;
9127 Diag(D->getLocation(),
9128 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9129 << D;
9130 }
9131 continue;
9132 }
9133 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
9134 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
9135 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
9136 if (!ASE && !OASE) {
9137 bool IsDecl = !VD ||
9138 VD->isThisDeclarationADefinition(Context) ==
9139 VarDecl::DeclarationOnly;
9140 Diag(D->getLocation(),
9141 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9142 << D;
9143 }
9144 continue;
9145 }
9146 }
9147
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009148 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009149 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009150 D->hasAttrs() ? &D->getAttrs() : nullptr);
9151 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9152 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009153 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009154 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009155 (!ASE &&
9156 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009157 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009158 // Create pseudo array type for private copy. The size for this array will
9159 // be generated during codegen.
9160 // For array subscripts or single variables Private Ty is the same as Type
9161 // (type of the variable or single array element).
9162 PrivateTy = Context.getVariableArrayType(
9163 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9164 Context.getSizeType(), VK_RValue),
9165 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009166 } else if (!ASE && !OASE &&
9167 Context.getAsArrayType(D->getType().getNonReferenceType()))
9168 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009169 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009170 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9171 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009172 // Add initializer for private variable.
9173 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009174 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9175 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9176 if (DeclareReductionRef.isUsable()) {
9177 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9178 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9179 if (DRD->getInitializer()) {
9180 Init = DRDRef;
9181 RHSVD->setInit(DRDRef);
9182 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009183 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009184 } else {
9185 switch (BOK) {
9186 case BO_Add:
9187 case BO_Xor:
9188 case BO_Or:
9189 case BO_LOr:
9190 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9191 if (Type->isScalarType() || Type->isAnyComplexType())
9192 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9193 break;
9194 case BO_Mul:
9195 case BO_LAnd:
9196 if (Type->isScalarType() || Type->isAnyComplexType()) {
9197 // '*' and '&&' reduction ops - initializer is '1'.
9198 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009199 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009200 break;
9201 case BO_And: {
9202 // '&' reduction op - initializer is '~0'.
9203 QualType OrigType = Type;
9204 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9205 Type = ComplexTy->getElementType();
9206 if (Type->isRealFloatingType()) {
9207 llvm::APFloat InitValue =
9208 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9209 /*isIEEE=*/true);
9210 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9211 Type, ELoc);
9212 } else if (Type->isScalarType()) {
9213 auto Size = Context.getTypeSize(Type);
9214 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9215 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9216 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9217 }
9218 if (Init && OrigType->isAnyComplexType()) {
9219 // Init = 0xFFFF + 0xFFFFi;
9220 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9221 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9222 }
9223 Type = OrigType;
9224 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009225 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009226 case BO_LT:
9227 case BO_GT: {
9228 // 'min' reduction op - initializer is 'Largest representable number in
9229 // the reduction list item type'.
9230 // 'max' reduction op - initializer is 'Least representable number in
9231 // the reduction list item type'.
9232 if (Type->isIntegerType() || Type->isPointerType()) {
9233 bool IsSigned = Type->hasSignedIntegerRepresentation();
9234 auto Size = Context.getTypeSize(Type);
9235 QualType IntTy =
9236 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9237 llvm::APInt InitValue =
9238 (BOK != BO_LT)
9239 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9240 : llvm::APInt::getMinValue(Size)
9241 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9242 : llvm::APInt::getMaxValue(Size);
9243 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9244 if (Type->isPointerType()) {
9245 // Cast to pointer type.
9246 auto CastExpr = BuildCStyleCastExpr(
9247 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9248 SourceLocation(), Init);
9249 if (CastExpr.isInvalid())
9250 continue;
9251 Init = CastExpr.get();
9252 }
9253 } else if (Type->isRealFloatingType()) {
9254 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9255 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9256 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9257 Type, ELoc);
9258 }
9259 break;
9260 }
9261 case BO_PtrMemD:
9262 case BO_PtrMemI:
9263 case BO_MulAssign:
9264 case BO_Div:
9265 case BO_Rem:
9266 case BO_Sub:
9267 case BO_Shl:
9268 case BO_Shr:
9269 case BO_LE:
9270 case BO_GE:
9271 case BO_EQ:
9272 case BO_NE:
9273 case BO_AndAssign:
9274 case BO_XorAssign:
9275 case BO_OrAssign:
9276 case BO_Assign:
9277 case BO_AddAssign:
9278 case BO_SubAssign:
9279 case BO_DivAssign:
9280 case BO_RemAssign:
9281 case BO_ShlAssign:
9282 case BO_ShrAssign:
9283 case BO_Comma:
9284 llvm_unreachable("Unexpected reduction operation");
9285 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009286 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009287 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009288 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009289 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009290 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009291 if (RHSVD->isInvalidDecl())
9292 continue;
9293 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009294 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9295 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009296 bool IsDecl =
9297 !VD ||
9298 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9299 Diag(D->getLocation(),
9300 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9301 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009302 continue;
9303 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009304 // Store initializer for single element in private copy. Will be used during
9305 // codegen.
9306 PrivateVD->setInit(RHSVD->getInit());
9307 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009308 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009309 ExprResult ReductionOp;
9310 if (DeclareReductionRef.isUsable()) {
9311 QualType RedTy = DeclareReductionRef.get()->getType();
9312 QualType PtrRedTy = Context.getPointerType(RedTy);
9313 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9314 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9315 if (!BasePath.empty()) {
9316 LHS = DefaultLvalueConversion(LHS.get());
9317 RHS = DefaultLvalueConversion(RHS.get());
9318 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9319 CK_UncheckedDerivedToBase, LHS.get(),
9320 &BasePath, LHS.get()->getValueKind());
9321 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9322 CK_UncheckedDerivedToBase, RHS.get(),
9323 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009324 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009325 FunctionProtoType::ExtProtoInfo EPI;
9326 QualType Params[] = {PtrRedTy, PtrRedTy};
9327 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9328 auto *OVE = new (Context) OpaqueValueExpr(
9329 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9330 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9331 Expr *Args[] = {LHS.get(), RHS.get()};
9332 ReductionOp = new (Context)
9333 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9334 } else {
9335 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9336 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9337 if (ReductionOp.isUsable()) {
9338 if (BOK != BO_LT && BOK != BO_GT) {
9339 ReductionOp =
9340 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9341 BO_Assign, LHSDRE, ReductionOp.get());
9342 } else {
9343 auto *ConditionalOp = new (Context) ConditionalOperator(
9344 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9345 RHSDRE, Type, VK_LValue, OK_Ordinary);
9346 ReductionOp =
9347 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9348 BO_Assign, LHSDRE, ConditionalOp);
9349 }
9350 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9351 }
9352 if (ReductionOp.isInvalid())
9353 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009354 }
9355
Alexey Bataev60da77e2016-02-29 05:54:20 +00009356 DeclRefExpr *Ref = nullptr;
9357 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009358 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009359 if (ASE || OASE) {
9360 TransformExprToCaptures RebuildToCapture(*this, D);
9361 VarsExpr =
9362 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9363 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009364 } else {
9365 VarsExpr = Ref =
9366 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009367 }
9368 if (!IsOpenMPCapturedDecl(D)) {
9369 ExprCaptures.push_back(Ref->getDecl());
9370 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9371 ExprResult RefRes = DefaultLvalueConversion(Ref);
9372 if (!RefRes.isUsable())
9373 continue;
9374 ExprResult PostUpdateRes =
9375 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9376 SimpleRefExpr, RefRes.get());
9377 if (!PostUpdateRes.isUsable())
9378 continue;
9379 ExprPostUpdates.push_back(
9380 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009381 }
9382 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009383 }
9384 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9385 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009386 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009387 LHSs.push_back(LHSDRE);
9388 RHSs.push_back(RHSDRE);
9389 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009390 }
9391
9392 if (Vars.empty())
9393 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009394
Alexey Bataevc5e02582014-06-16 07:08:35 +00009395 return OMPReductionClause::Create(
9396 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009397 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009398 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9399 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009400}
9401
Alexey Bataevecba70f2016-04-12 11:02:11 +00009402bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9403 SourceLocation LinLoc) {
9404 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9405 LinKind == OMPC_LINEAR_unknown) {
9406 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9407 return true;
9408 }
9409 return false;
9410}
9411
9412bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9413 OpenMPLinearClauseKind LinKind,
9414 QualType Type) {
9415 auto *VD = dyn_cast_or_null<VarDecl>(D);
9416 // A variable must not have an incomplete type or a reference type.
9417 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9418 return true;
9419 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9420 !Type->isReferenceType()) {
9421 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9422 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9423 return true;
9424 }
9425 Type = Type.getNonReferenceType();
9426
9427 // A list item must not be const-qualified.
9428 if (Type.isConstant(Context)) {
9429 Diag(ELoc, diag::err_omp_const_variable)
9430 << getOpenMPClauseName(OMPC_linear);
9431 if (D) {
9432 bool IsDecl =
9433 !VD ||
9434 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9435 Diag(D->getLocation(),
9436 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9437 << D;
9438 }
9439 return true;
9440 }
9441
9442 // A list item must be of integral or pointer type.
9443 Type = Type.getUnqualifiedType().getCanonicalType();
9444 const auto *Ty = Type.getTypePtrOrNull();
9445 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9446 !Ty->isPointerType())) {
9447 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9448 if (D) {
9449 bool IsDecl =
9450 !VD ||
9451 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9452 Diag(D->getLocation(),
9453 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9454 << D;
9455 }
9456 return true;
9457 }
9458 return false;
9459}
9460
Alexey Bataev182227b2015-08-20 10:54:39 +00009461OMPClause *Sema::ActOnOpenMPLinearClause(
9462 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9463 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9464 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009465 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009466 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009467 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009468 SmallVector<Decl *, 4> ExprCaptures;
9469 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009470 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009471 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009472 for (auto &RefExpr : VarList) {
9473 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009474 SourceLocation ELoc;
9475 SourceRange ERange;
9476 Expr *SimpleRefExpr = RefExpr;
9477 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9478 /*AllowArraySection=*/false);
9479 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009480 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009481 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009482 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009483 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009484 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009485 ValueDecl *D = Res.first;
9486 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009487 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009488
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009489 QualType Type = D->getType();
9490 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009491
9492 // OpenMP [2.14.3.7, linear clause]
9493 // A list-item cannot appear in more than one linear clause.
9494 // A list-item that appears in a linear clause cannot appear in any
9495 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009496 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009497 if (DVar.RefExpr) {
9498 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9499 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009500 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009501 continue;
9502 }
9503
Alexey Bataevecba70f2016-04-12 11:02:11 +00009504 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009505 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009506 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009507
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009508 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009509 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9510 D->hasAttrs() ? &D->getAttrs() : nullptr);
9511 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009512 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009513 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009514 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009515 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009516 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009517 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9518 if (!IsOpenMPCapturedDecl(D)) {
9519 ExprCaptures.push_back(Ref->getDecl());
9520 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9521 ExprResult RefRes = DefaultLvalueConversion(Ref);
9522 if (!RefRes.isUsable())
9523 continue;
9524 ExprResult PostUpdateRes =
9525 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9526 SimpleRefExpr, RefRes.get());
9527 if (!PostUpdateRes.isUsable())
9528 continue;
9529 ExprPostUpdates.push_back(
9530 IgnoredValueConversions(PostUpdateRes.get()).get());
9531 }
9532 }
9533 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009534 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009535 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009536 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009537 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009538 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009539 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009540 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9541
9542 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009543 Vars.push_back((VD || CurContext->isDependentContext())
9544 ? RefExpr->IgnoreParens()
9545 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009546 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009547 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009548 }
9549
9550 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009551 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009552
9553 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009554 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009555 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9556 !Step->isInstantiationDependent() &&
9557 !Step->containsUnexpandedParameterPack()) {
9558 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009559 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009560 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009561 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009562 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009563
Alexander Musman3276a272015-03-21 10:12:56 +00009564 // Build var to save the step value.
9565 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009566 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009567 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009568 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009569 ExprResult CalcStep =
9570 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009571 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009572
Alexander Musman8dba6642014-04-22 13:09:42 +00009573 // Warn about zero linear step (it would be probably better specified as
9574 // making corresponding variables 'const').
9575 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009576 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9577 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009578 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9579 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009580 if (!IsConstant && CalcStep.isUsable()) {
9581 // Calculate the step beforehand instead of doing this on each iteration.
9582 // (This is not used if the number of iterations may be kfold-ed).
9583 CalcStepExpr = CalcStep.get();
9584 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009585 }
9586
Alexey Bataev182227b2015-08-20 10:54:39 +00009587 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9588 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009589 StepExpr, CalcStepExpr,
9590 buildPreInits(Context, ExprCaptures),
9591 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009592}
9593
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009594static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9595 Expr *NumIterations, Sema &SemaRef,
9596 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009597 // Walk the vars and build update/final expressions for the CodeGen.
9598 SmallVector<Expr *, 8> Updates;
9599 SmallVector<Expr *, 8> Finals;
9600 Expr *Step = Clause.getStep();
9601 Expr *CalcStep = Clause.getCalcStep();
9602 // OpenMP [2.14.3.7, linear clause]
9603 // If linear-step is not specified it is assumed to be 1.
9604 if (Step == nullptr)
9605 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009606 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009607 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009608 }
Alexander Musman3276a272015-03-21 10:12:56 +00009609 bool HasErrors = false;
9610 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009611 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009612 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009613 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009614 SourceLocation ELoc;
9615 SourceRange ERange;
9616 Expr *SimpleRefExpr = RefExpr;
9617 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9618 /*AllowArraySection=*/false);
9619 ValueDecl *D = Res.first;
9620 if (Res.second || !D) {
9621 Updates.push_back(nullptr);
9622 Finals.push_back(nullptr);
9623 HasErrors = true;
9624 continue;
9625 }
9626 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9627 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9628 ->getMemberDecl();
9629 }
9630 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009631 Expr *InitExpr = *CurInit;
9632
9633 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009634 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009635 Expr *CapturedRef;
9636 if (LinKind == OMPC_LINEAR_uval)
9637 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9638 else
9639 CapturedRef =
9640 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9641 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9642 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009643
9644 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009645 ExprResult Update;
9646 if (!Info.first) {
9647 Update =
9648 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9649 InitExpr, IV, Step, /* Subtract */ false);
9650 } else
9651 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009652 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9653 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009654
9655 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009656 ExprResult Final;
9657 if (!Info.first) {
9658 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9659 InitExpr, NumIterations, Step,
9660 /* Subtract */ false);
9661 } else
9662 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009663 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9664 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009665
Alexander Musman3276a272015-03-21 10:12:56 +00009666 if (!Update.isUsable() || !Final.isUsable()) {
9667 Updates.push_back(nullptr);
9668 Finals.push_back(nullptr);
9669 HasErrors = true;
9670 } else {
9671 Updates.push_back(Update.get());
9672 Finals.push_back(Final.get());
9673 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009674 ++CurInit;
9675 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009676 }
9677 Clause.setUpdates(Updates);
9678 Clause.setFinals(Finals);
9679 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009680}
9681
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009682OMPClause *Sema::ActOnOpenMPAlignedClause(
9683 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9684 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9685
9686 SmallVector<Expr *, 8> Vars;
9687 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009688 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9689 SourceLocation ELoc;
9690 SourceRange ERange;
9691 Expr *SimpleRefExpr = RefExpr;
9692 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9693 /*AllowArraySection=*/false);
9694 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009695 // It will be analyzed later.
9696 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009697 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009698 ValueDecl *D = Res.first;
9699 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009700 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009701
Alexey Bataev1efd1662016-03-29 10:59:56 +00009702 QualType QType = D->getType();
9703 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009704
9705 // OpenMP [2.8.1, simd construct, Restrictions]
9706 // The type of list items appearing in the aligned clause must be
9707 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009708 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009709 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009710 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009711 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009712 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009713 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009714 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009715 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009716 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009717 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009718 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009719 continue;
9720 }
9721
9722 // OpenMP [2.8.1, simd construct, Restrictions]
9723 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009724 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009725 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009726 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9727 << getOpenMPClauseName(OMPC_aligned);
9728 continue;
9729 }
9730
Alexey Bataev1efd1662016-03-29 10:59:56 +00009731 DeclRefExpr *Ref = nullptr;
9732 if (!VD && IsOpenMPCapturedDecl(D))
9733 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9734 Vars.push_back(DefaultFunctionArrayConversion(
9735 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9736 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009737 }
9738
9739 // OpenMP [2.8.1, simd construct, Description]
9740 // The parameter of the aligned clause, alignment, must be a constant
9741 // positive integer expression.
9742 // If no optional parameter is specified, implementation-defined default
9743 // alignments for SIMD instructions on the target platforms are assumed.
9744 if (Alignment != nullptr) {
9745 ExprResult AlignResult =
9746 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9747 if (AlignResult.isInvalid())
9748 return nullptr;
9749 Alignment = AlignResult.get();
9750 }
9751 if (Vars.empty())
9752 return nullptr;
9753
9754 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9755 EndLoc, Vars, Alignment);
9756}
9757
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009758OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9759 SourceLocation StartLoc,
9760 SourceLocation LParenLoc,
9761 SourceLocation EndLoc) {
9762 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009763 SmallVector<Expr *, 8> SrcExprs;
9764 SmallVector<Expr *, 8> DstExprs;
9765 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009766 for (auto &RefExpr : VarList) {
9767 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9768 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009769 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009770 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009771 SrcExprs.push_back(nullptr);
9772 DstExprs.push_back(nullptr);
9773 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009774 continue;
9775 }
9776
Alexey Bataeved09d242014-05-28 05:53:51 +00009777 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009778 // OpenMP [2.1, C/C++]
9779 // A list item is a variable name.
9780 // OpenMP [2.14.4.1, Restrictions, p.1]
9781 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009782 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009783 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009784 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9785 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009786 continue;
9787 }
9788
9789 Decl *D = DE->getDecl();
9790 VarDecl *VD = cast<VarDecl>(D);
9791
9792 QualType Type = VD->getType();
9793 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9794 // It will be analyzed later.
9795 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009796 SrcExprs.push_back(nullptr);
9797 DstExprs.push_back(nullptr);
9798 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009799 continue;
9800 }
9801
9802 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9803 // A list item that appears in a copyin clause must be threadprivate.
9804 if (!DSAStack->isThreadPrivate(VD)) {
9805 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009806 << getOpenMPClauseName(OMPC_copyin)
9807 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009808 continue;
9809 }
9810
9811 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9812 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009813 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009814 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009815 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009816 auto *SrcVD =
9817 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9818 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009819 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009820 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9821 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009822 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9823 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009824 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009825 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009826 // For arrays generate assignment operation for single element and replace
9827 // it by the original array element in CodeGen.
9828 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9829 PseudoDstExpr, PseudoSrcExpr);
9830 if (AssignmentOp.isInvalid())
9831 continue;
9832 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9833 /*DiscardedValue=*/true);
9834 if (AssignmentOp.isInvalid())
9835 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009836
9837 DSAStack->addDSA(VD, DE, OMPC_copyin);
9838 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009839 SrcExprs.push_back(PseudoSrcExpr);
9840 DstExprs.push_back(PseudoDstExpr);
9841 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009842 }
9843
Alexey Bataeved09d242014-05-28 05:53:51 +00009844 if (Vars.empty())
9845 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009846
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009847 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9848 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009849}
9850
Alexey Bataevbae9a792014-06-27 10:37:06 +00009851OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9852 SourceLocation StartLoc,
9853 SourceLocation LParenLoc,
9854 SourceLocation EndLoc) {
9855 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009856 SmallVector<Expr *, 8> SrcExprs;
9857 SmallVector<Expr *, 8> DstExprs;
9858 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009859 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009860 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9861 SourceLocation ELoc;
9862 SourceRange ERange;
9863 Expr *SimpleRefExpr = RefExpr;
9864 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9865 /*AllowArraySection=*/false);
9866 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009867 // It will be analyzed later.
9868 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009869 SrcExprs.push_back(nullptr);
9870 DstExprs.push_back(nullptr);
9871 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009872 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009873 ValueDecl *D = Res.first;
9874 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009875 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009876
Alexey Bataeve122da12016-03-17 10:50:17 +00009877 QualType Type = D->getType();
9878 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009879
9880 // OpenMP [2.14.4.2, Restrictions, p.2]
9881 // A list item that appears in a copyprivate clause may not appear in a
9882 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009883 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9884 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009885 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9886 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009887 Diag(ELoc, diag::err_omp_wrong_dsa)
9888 << getOpenMPClauseName(DVar.CKind)
9889 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009890 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009891 continue;
9892 }
9893
9894 // OpenMP [2.11.4.2, Restrictions, p.1]
9895 // All list items that appear in a copyprivate clause must be either
9896 // threadprivate or private in the enclosing context.
9897 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009898 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009899 if (DVar.CKind == OMPC_shared) {
9900 Diag(ELoc, diag::err_omp_required_access)
9901 << getOpenMPClauseName(OMPC_copyprivate)
9902 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009903 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009904 continue;
9905 }
9906 }
9907 }
9908
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009909 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009910 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009911 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009912 << getOpenMPClauseName(OMPC_copyprivate) << Type
9913 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009914 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009915 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009916 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009917 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009918 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009919 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009920 continue;
9921 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009922
Alexey Bataevbae9a792014-06-27 10:37:06 +00009923 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9924 // A variable of class type (or array thereof) that appears in a
9925 // copyin clause requires an accessible, unambiguous copy assignment
9926 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009927 Type = Context.getBaseElementType(Type.getNonReferenceType())
9928 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009929 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009930 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9931 D->hasAttrs() ? &D->getAttrs() : nullptr);
9932 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009933 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009934 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9935 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009936 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009937 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009938 PseudoDstExpr, PseudoSrcExpr);
9939 if (AssignmentOp.isInvalid())
9940 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009941 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009942 /*DiscardedValue=*/true);
9943 if (AssignmentOp.isInvalid())
9944 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009945
9946 // No need to mark vars as copyprivate, they are already threadprivate or
9947 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009948 assert(VD || IsOpenMPCapturedDecl(D));
9949 Vars.push_back(
9950 VD ? RefExpr->IgnoreParens()
9951 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009952 SrcExprs.push_back(PseudoSrcExpr);
9953 DstExprs.push_back(PseudoDstExpr);
9954 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009955 }
9956
9957 if (Vars.empty())
9958 return nullptr;
9959
Alexey Bataeva63048e2015-03-23 06:18:07 +00009960 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9961 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009962}
9963
Alexey Bataev6125da92014-07-21 11:26:11 +00009964OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9965 SourceLocation StartLoc,
9966 SourceLocation LParenLoc,
9967 SourceLocation EndLoc) {
9968 if (VarList.empty())
9969 return nullptr;
9970
9971 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9972}
Alexey Bataevdea47612014-07-23 07:46:59 +00009973
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009974OMPClause *
9975Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9976 SourceLocation DepLoc, SourceLocation ColonLoc,
9977 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9978 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009979 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009980 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009981 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009982 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009983 return nullptr;
9984 }
9985 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009986 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9987 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009988 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009989 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009990 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9991 /*Last=*/OMPC_DEPEND_unknown, Except)
9992 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009993 return nullptr;
9994 }
9995 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009996 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009997 llvm::APSInt DepCounter(/*BitWidth=*/32);
9998 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9999 if (DepKind == OMPC_DEPEND_sink) {
10000 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10001 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10002 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010003 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010004 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010005 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10006 DSAStack->getParentOrderedRegionParam()) {
10007 for (auto &RefExpr : VarList) {
10008 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010009 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010010 // It will be analyzed later.
10011 Vars.push_back(RefExpr);
10012 continue;
10013 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010014
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010015 SourceLocation ELoc = RefExpr->getExprLoc();
10016 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10017 if (DepKind == OMPC_DEPEND_sink) {
10018 if (DepCounter >= TotalDepCount) {
10019 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10020 continue;
10021 }
10022 ++DepCounter;
10023 // OpenMP [2.13.9, Summary]
10024 // depend(dependence-type : vec), where dependence-type is:
10025 // 'sink' and where vec is the iteration vector, which has the form:
10026 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10027 // where n is the value specified by the ordered clause in the loop
10028 // directive, xi denotes the loop iteration variable of the i-th nested
10029 // loop associated with the loop directive, and di is a constant
10030 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010031 if (CurContext->isDependentContext()) {
10032 // It will be analyzed later.
10033 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010034 continue;
10035 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010036 SimpleExpr = SimpleExpr->IgnoreImplicit();
10037 OverloadedOperatorKind OOK = OO_None;
10038 SourceLocation OOLoc;
10039 Expr *LHS = SimpleExpr;
10040 Expr *RHS = nullptr;
10041 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10042 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10043 OOLoc = BO->getOperatorLoc();
10044 LHS = BO->getLHS()->IgnoreParenImpCasts();
10045 RHS = BO->getRHS()->IgnoreParenImpCasts();
10046 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10047 OOK = OCE->getOperator();
10048 OOLoc = OCE->getOperatorLoc();
10049 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10050 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10051 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10052 OOK = MCE->getMethodDecl()
10053 ->getNameInfo()
10054 .getName()
10055 .getCXXOverloadedOperator();
10056 OOLoc = MCE->getCallee()->getExprLoc();
10057 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10058 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10059 }
10060 SourceLocation ELoc;
10061 SourceRange ERange;
10062 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10063 /*AllowArraySection=*/false);
10064 if (Res.second) {
10065 // It will be analyzed later.
10066 Vars.push_back(RefExpr);
10067 }
10068 ValueDecl *D = Res.first;
10069 if (!D)
10070 continue;
10071
10072 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10073 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10074 continue;
10075 }
10076 if (RHS) {
10077 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10078 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10079 if (RHSRes.isInvalid())
10080 continue;
10081 }
10082 if (!CurContext->isDependentContext() &&
10083 DSAStack->getParentOrderedRegionParam() &&
10084 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10085 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10086 << DSAStack->getParentLoopControlVariable(
10087 DepCounter.getZExtValue());
10088 continue;
10089 }
10090 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010091 } else {
10092 // OpenMP [2.11.1.1, Restrictions, p.3]
10093 // A variable that is part of another variable (such as a field of a
10094 // structure) but is not an array element or an array section cannot
10095 // appear in a depend clause.
10096 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10097 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10098 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10099 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10100 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010101 (ASE &&
10102 !ASE->getBase()
10103 ->getType()
10104 .getNonReferenceType()
10105 ->isPointerType() &&
10106 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010107 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10108 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010109 continue;
10110 }
10111 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010112 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10113 }
10114
10115 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10116 TotalDepCount > VarList.size() &&
10117 DSAStack->getParentOrderedRegionParam()) {
10118 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10119 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10120 }
10121 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10122 Vars.empty())
10123 return nullptr;
10124 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010125 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10126 DepKind, DepLoc, ColonLoc, Vars);
10127 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10128 DSAStack->addDoacrossDependClause(C, OpsOffs);
10129 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010130}
Michael Wonge710d542015-08-07 16:16:36 +000010131
10132OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10133 SourceLocation LParenLoc,
10134 SourceLocation EndLoc) {
10135 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010136
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010137 // OpenMP [2.9.1, Restrictions]
10138 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010139 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10140 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010141 return nullptr;
10142
Michael Wonge710d542015-08-07 16:16:36 +000010143 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10144}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010145
10146static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10147 DSAStackTy *Stack, CXXRecordDecl *RD) {
10148 if (!RD || RD->isInvalidDecl())
10149 return true;
10150
10151 auto QTy = SemaRef.Context.getRecordType(RD);
10152 if (RD->isDynamicClass()) {
10153 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10154 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10155 return false;
10156 }
10157 auto *DC = RD;
10158 bool IsCorrect = true;
10159 for (auto *I : DC->decls()) {
10160 if (I) {
10161 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10162 if (MD->isStatic()) {
10163 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10164 SemaRef.Diag(MD->getLocation(),
10165 diag::note_omp_static_member_in_target);
10166 IsCorrect = false;
10167 }
10168 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10169 if (VD->isStaticDataMember()) {
10170 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10171 SemaRef.Diag(VD->getLocation(),
10172 diag::note_omp_static_member_in_target);
10173 IsCorrect = false;
10174 }
10175 }
10176 }
10177 }
10178
10179 for (auto &I : RD->bases()) {
10180 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10181 I.getType()->getAsCXXRecordDecl()))
10182 IsCorrect = false;
10183 }
10184 return IsCorrect;
10185}
10186
10187static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10188 DSAStackTy *Stack, QualType QTy) {
10189 NamedDecl *ND;
10190 if (QTy->isIncompleteType(&ND)) {
10191 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10192 return false;
10193 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010194 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010195 return false;
10196 }
10197 return true;
10198}
10199
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010200/// \brief Return true if it can be proven that the provided array expression
10201/// (array section or array subscript) does NOT specify the whole size of the
10202/// array whose base type is \a BaseQTy.
10203static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10204 const Expr *E,
10205 QualType BaseQTy) {
10206 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10207
10208 // If this is an array subscript, it refers to the whole size if the size of
10209 // the dimension is constant and equals 1. Also, an array section assumes the
10210 // format of an array subscript if no colon is used.
10211 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10212 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10213 return ATy->getSize().getSExtValue() != 1;
10214 // Size can't be evaluated statically.
10215 return false;
10216 }
10217
10218 assert(OASE && "Expecting array section if not an array subscript.");
10219 auto *LowerBound = OASE->getLowerBound();
10220 auto *Length = OASE->getLength();
10221
10222 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010223 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010224 if (LowerBound) {
10225 llvm::APSInt ConstLowerBound;
10226 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10227 return false; // Can't get the integer value as a constant.
10228 if (ConstLowerBound.getSExtValue())
10229 return true;
10230 }
10231
10232 // If we don't have a length we covering the whole dimension.
10233 if (!Length)
10234 return false;
10235
10236 // If the base is a pointer, we don't have a way to get the size of the
10237 // pointee.
10238 if (BaseQTy->isPointerType())
10239 return false;
10240
10241 // We can only check if the length is the same as the size of the dimension
10242 // if we have a constant array.
10243 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10244 if (!CATy)
10245 return false;
10246
10247 llvm::APSInt ConstLength;
10248 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10249 return false; // Can't get the integer value as a constant.
10250
10251 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10252}
10253
10254// Return true if it can be proven that the provided array expression (array
10255// section or array subscript) does NOT specify a single element of the array
10256// whose base type is \a BaseQTy.
10257static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010258 const Expr *E,
10259 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010260 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10261
10262 // An array subscript always refer to a single element. Also, an array section
10263 // assumes the format of an array subscript if no colon is used.
10264 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10265 return false;
10266
10267 assert(OASE && "Expecting array section if not an array subscript.");
10268 auto *Length = OASE->getLength();
10269
10270 // If we don't have a length we have to check if the array has unitary size
10271 // for this dimension. Also, we should always expect a length if the base type
10272 // is pointer.
10273 if (!Length) {
10274 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10275 return ATy->getSize().getSExtValue() != 1;
10276 // We cannot assume anything.
10277 return false;
10278 }
10279
10280 // Check if the length evaluates to 1.
10281 llvm::APSInt ConstLength;
10282 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10283 return false; // Can't get the integer value as a constant.
10284
10285 return ConstLength.getSExtValue() != 1;
10286}
10287
Samuel Antao661c0902016-05-26 17:39:58 +000010288// Return the expression of the base of the mappable expression or null if it
10289// cannot be determined and do all the necessary checks to see if the expression
10290// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010291// components of the expression.
10292static Expr *CheckMapClauseExpressionBase(
10293 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010294 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10295 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010296 SourceLocation ELoc = E->getExprLoc();
10297 SourceRange ERange = E->getSourceRange();
10298
10299 // The base of elements of list in a map clause have to be either:
10300 // - a reference to variable or field.
10301 // - a member expression.
10302 // - an array expression.
10303 //
10304 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10305 // reference to 'r'.
10306 //
10307 // If we have:
10308 //
10309 // struct SS {
10310 // Bla S;
10311 // foo() {
10312 // #pragma omp target map (S.Arr[:12]);
10313 // }
10314 // }
10315 //
10316 // We want to retrieve the member expression 'this->S';
10317
10318 Expr *RelevantExpr = nullptr;
10319
Samuel Antao5de996e2016-01-22 20:21:36 +000010320 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10321 // If a list item is an array section, it must specify contiguous storage.
10322 //
10323 // For this restriction it is sufficient that we make sure only references
10324 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010325 // exist except in the rightmost expression (unless they cover the whole
10326 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010327 //
10328 // r.ArrS[3:5].Arr[6:7]
10329 //
10330 // r.ArrS[3:5].x
10331 //
10332 // but these would be valid:
10333 // r.ArrS[3].Arr[6:7]
10334 //
10335 // r.ArrS[3].x
10336
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010337 bool AllowUnitySizeArraySection = true;
10338 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010339
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010340 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010341 E = E->IgnoreParenImpCasts();
10342
10343 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10344 if (!isa<VarDecl>(CurE->getDecl()))
10345 break;
10346
10347 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010348
10349 // If we got a reference to a declaration, we should not expect any array
10350 // section before that.
10351 AllowUnitySizeArraySection = false;
10352 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010353
10354 // Record the component.
10355 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10356 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010357 continue;
10358 }
10359
10360 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10361 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10362
10363 if (isa<CXXThisExpr>(BaseE))
10364 // We found a base expression: this->Val.
10365 RelevantExpr = CurE;
10366 else
10367 E = BaseE;
10368
10369 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10370 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10371 << CurE->getSourceRange();
10372 break;
10373 }
10374
10375 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10376
10377 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10378 // A bit-field cannot appear in a map clause.
10379 //
10380 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010381 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10382 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010383 break;
10384 }
10385
10386 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10387 // If the type of a list item is a reference to a type T then the type
10388 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010389 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010390
10391 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10392 // A list item cannot be a variable that is a member of a structure with
10393 // a union type.
10394 //
10395 if (auto *RT = CurType->getAs<RecordType>())
10396 if (RT->isUnionType()) {
10397 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10398 << CurE->getSourceRange();
10399 break;
10400 }
10401
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010402 // If we got a member expression, we should not expect any array section
10403 // before that:
10404 //
10405 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10406 // If a list item is an element of a structure, only the rightmost symbol
10407 // of the variable reference can be an array section.
10408 //
10409 AllowUnitySizeArraySection = false;
10410 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010411
10412 // Record the component.
10413 CurComponents.push_back(
10414 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010415 continue;
10416 }
10417
10418 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10419 E = CurE->getBase()->IgnoreParenImpCasts();
10420
10421 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10422 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10423 << 0 << CurE->getSourceRange();
10424 break;
10425 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010426
10427 // If we got an array subscript that express the whole dimension we
10428 // can have any array expressions before. If it only expressing part of
10429 // the dimension, we can only have unitary-size array expressions.
10430 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10431 E->getType()))
10432 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010433
10434 // Record the component - we don't have any declaration associated.
10435 CurComponents.push_back(
10436 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010437 continue;
10438 }
10439
10440 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010441 E = CurE->getBase()->IgnoreParenImpCasts();
10442
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010443 auto CurType =
10444 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10445
Samuel Antao5de996e2016-01-22 20:21:36 +000010446 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10447 // If the type of a list item is a reference to a type T then the type
10448 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010449 if (CurType->isReferenceType())
10450 CurType = CurType->getPointeeType();
10451
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010452 bool IsPointer = CurType->isAnyPointerType();
10453
10454 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010455 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10456 << 0 << CurE->getSourceRange();
10457 break;
10458 }
10459
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010460 bool NotWhole =
10461 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10462 bool NotUnity =
10463 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10464
Samuel Antaodab51bb2016-07-18 23:22:11 +000010465 if (AllowWholeSizeArraySection) {
10466 // Any array section is currently allowed. Allowing a whole size array
10467 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010468 //
10469 // If this array section refers to the whole dimension we can still
10470 // accept other array sections before this one, except if the base is a
10471 // pointer. Otherwise, only unitary sections are accepted.
10472 if (NotWhole || IsPointer)
10473 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010474 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010475 // A unity or whole array section is not allowed and that is not
10476 // compatible with the properties of the current array section.
10477 SemaRef.Diag(
10478 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10479 << CurE->getSourceRange();
10480 break;
10481 }
Samuel Antao90927002016-04-26 14:54:23 +000010482
10483 // Record the component - we don't have any declaration associated.
10484 CurComponents.push_back(
10485 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010486 continue;
10487 }
10488
10489 // If nothing else worked, this is not a valid map clause expression.
10490 SemaRef.Diag(ELoc,
10491 diag::err_omp_expected_named_var_member_or_array_expression)
10492 << ERange;
10493 break;
10494 }
10495
10496 return RelevantExpr;
10497}
10498
10499// Return true if expression E associated with value VD has conflicts with other
10500// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010501static bool CheckMapConflicts(
10502 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10503 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010504 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10505 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010506 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010507 SourceLocation ELoc = E->getExprLoc();
10508 SourceRange ERange = E->getSourceRange();
10509
10510 // In order to easily check the conflicts we need to match each component of
10511 // the expression under test with the components of the expressions that are
10512 // already in the stack.
10513
Samuel Antao5de996e2016-01-22 20:21:36 +000010514 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010515 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010516 "Map clause expression with unexpected base!");
10517
10518 // Variables to help detecting enclosing problems in data environment nests.
10519 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010520 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010521
Samuel Antao90927002016-04-26 14:54:23 +000010522 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10523 VD, CurrentRegionOnly,
10524 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010525 StackComponents,
10526 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010527
Samuel Antao5de996e2016-01-22 20:21:36 +000010528 assert(!StackComponents.empty() &&
10529 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010530 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010531 "Map clause expression with unexpected base!");
10532
Samuel Antao90927002016-04-26 14:54:23 +000010533 // The whole expression in the stack.
10534 auto *RE = StackComponents.front().getAssociatedExpression();
10535
Samuel Antao5de996e2016-01-22 20:21:36 +000010536 // Expressions must start from the same base. Here we detect at which
10537 // point both expressions diverge from each other and see if we can
10538 // detect if the memory referred to both expressions is contiguous and
10539 // do not overlap.
10540 auto CI = CurComponents.rbegin();
10541 auto CE = CurComponents.rend();
10542 auto SI = StackComponents.rbegin();
10543 auto SE = StackComponents.rend();
10544 for (; CI != CE && SI != SE; ++CI, ++SI) {
10545
10546 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10547 // At most one list item can be an array item derived from a given
10548 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010549 if (CurrentRegionOnly &&
10550 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10551 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10552 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10553 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10554 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010555 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010556 << CI->getAssociatedExpression()->getSourceRange();
10557 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10558 diag::note_used_here)
10559 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010560 return true;
10561 }
10562
10563 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010564 if (CI->getAssociatedExpression()->getStmtClass() !=
10565 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010566 break;
10567
10568 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010569 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010570 break;
10571 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010572 // Check if the extra components of the expressions in the enclosing
10573 // data environment are redundant for the current base declaration.
10574 // If they are, the maps completely overlap, which is legal.
10575 for (; SI != SE; ++SI) {
10576 QualType Type;
10577 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010578 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010579 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010580 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10581 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010582 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10583 Type =
10584 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10585 }
10586 if (Type.isNull() || Type->isAnyPointerType() ||
10587 CheckArrayExpressionDoesNotReferToWholeSize(
10588 SemaRef, SI->getAssociatedExpression(), Type))
10589 break;
10590 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010591
10592 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10593 // List items of map clauses in the same construct must not share
10594 // original storage.
10595 //
10596 // If the expressions are exactly the same or one is a subset of the
10597 // other, it means they are sharing storage.
10598 if (CI == CE && SI == SE) {
10599 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010600 if (CKind == OMPC_map)
10601 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10602 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010603 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010604 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10605 << ERange;
10606 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010607 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10608 << RE->getSourceRange();
10609 return true;
10610 } else {
10611 // If we find the same expression in the enclosing data environment,
10612 // that is legal.
10613 IsEnclosedByDataEnvironmentExpr = true;
10614 return false;
10615 }
10616 }
10617
Samuel Antao90927002016-04-26 14:54:23 +000010618 QualType DerivedType =
10619 std::prev(CI)->getAssociatedDeclaration()->getType();
10620 SourceLocation DerivedLoc =
10621 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010622
10623 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10624 // If the type of a list item is a reference to a type T then the type
10625 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010626 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010627
10628 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10629 // A variable for which the type is pointer and an array section
10630 // derived from that variable must not appear as list items of map
10631 // clauses of the same construct.
10632 //
10633 // Also, cover one of the cases in:
10634 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10635 // If any part of the original storage of a list item has corresponding
10636 // storage in the device data environment, all of the original storage
10637 // must have corresponding storage in the device data environment.
10638 //
10639 if (DerivedType->isAnyPointerType()) {
10640 if (CI == CE || SI == SE) {
10641 SemaRef.Diag(
10642 DerivedLoc,
10643 diag::err_omp_pointer_mapped_along_with_derived_section)
10644 << DerivedLoc;
10645 } else {
10646 assert(CI != CE && SI != SE);
10647 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10648 << DerivedLoc;
10649 }
10650 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10651 << RE->getSourceRange();
10652 return true;
10653 }
10654
10655 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10656 // List items of map clauses in the same construct must not share
10657 // original storage.
10658 //
10659 // An expression is a subset of the other.
10660 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010661 if (CKind == OMPC_map)
10662 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10663 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010664 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010665 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10666 << ERange;
10667 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010668 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10669 << RE->getSourceRange();
10670 return true;
10671 }
10672
10673 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010674 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010675 if (!CurrentRegionOnly && SI != SE)
10676 EnclosingExpr = RE;
10677
10678 // The current expression is a subset of the expression in the data
10679 // environment.
10680 IsEnclosedByDataEnvironmentExpr |=
10681 (!CurrentRegionOnly && CI != CE && SI == SE);
10682
10683 return false;
10684 });
10685
10686 if (CurrentRegionOnly)
10687 return FoundError;
10688
10689 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10690 // If any part of the original storage of a list item has corresponding
10691 // storage in the device data environment, all of the original storage must
10692 // have corresponding storage in the device data environment.
10693 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10694 // If a list item is an element of a structure, and a different element of
10695 // the structure has a corresponding list item in the device data environment
10696 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010697 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010698 // data environment prior to the task encountering the construct.
10699 //
10700 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10701 SemaRef.Diag(ELoc,
10702 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10703 << ERange;
10704 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10705 << EnclosingExpr->getSourceRange();
10706 return true;
10707 }
10708
10709 return FoundError;
10710}
10711
Samuel Antao661c0902016-05-26 17:39:58 +000010712namespace {
10713// Utility struct that gathers all the related lists associated with a mappable
10714// expression.
10715struct MappableVarListInfo final {
10716 // The list of expressions.
10717 ArrayRef<Expr *> VarList;
10718 // The list of processed expressions.
10719 SmallVector<Expr *, 16> ProcessedVarList;
10720 // The mappble components for each expression.
10721 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10722 // The base declaration of the variable.
10723 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10724
10725 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10726 // We have a list of components and base declarations for each entry in the
10727 // variable list.
10728 VarComponents.reserve(VarList.size());
10729 VarBaseDeclarations.reserve(VarList.size());
10730 }
10731};
10732}
10733
10734// Check the validity of the provided variable list for the provided clause kind
10735// \a CKind. In the check process the valid expressions, and mappable expression
10736// components and variables are extracted and used to fill \a Vars,
10737// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10738// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10739static void
10740checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10741 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10742 SourceLocation StartLoc,
10743 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10744 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010745 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10746 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010747 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010748
Samuel Antao90927002016-04-26 14:54:23 +000010749 // Keep track of the mappable components and base declarations in this clause.
10750 // Each entry in the list is going to have a list of components associated. We
10751 // record each set of the components so that we can build the clause later on.
10752 // In the end we should have the same amount of declarations and component
10753 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010754
Samuel Antao661c0902016-05-26 17:39:58 +000010755 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010756 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010757 SourceLocation ELoc = RE->getExprLoc();
10758
Kelvin Li0bff7af2015-11-23 05:32:03 +000010759 auto *VE = RE->IgnoreParenLValueCasts();
10760
10761 if (VE->isValueDependent() || VE->isTypeDependent() ||
10762 VE->isInstantiationDependent() ||
10763 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010764 // We can only analyze this information once the missing information is
10765 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010766 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010767 continue;
10768 }
10769
10770 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010771
Samuel Antao5de996e2016-01-22 20:21:36 +000010772 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010773 SemaRef.Diag(ELoc,
10774 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010775 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010776 continue;
10777 }
10778
Samuel Antao90927002016-04-26 14:54:23 +000010779 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10780 ValueDecl *CurDeclaration = nullptr;
10781
10782 // Obtain the array or member expression bases if required. Also, fill the
10783 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010784 auto *BE =
10785 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010786 if (!BE)
10787 continue;
10788
Samuel Antao90927002016-04-26 14:54:23 +000010789 assert(!CurComponents.empty() &&
10790 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010791
Samuel Antao90927002016-04-26 14:54:23 +000010792 // For the following checks, we rely on the base declaration which is
10793 // expected to be associated with the last component. The declaration is
10794 // expected to be a variable or a field (if 'this' is being mapped).
10795 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10796 assert(CurDeclaration && "Null decl on map clause.");
10797 assert(
10798 CurDeclaration->isCanonicalDecl() &&
10799 "Expecting components to have associated only canonical declarations.");
10800
10801 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10802 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010803
10804 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010805 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010806
10807 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010808 // threadprivate variables cannot appear in a map clause.
10809 // OpenMP 4.5 [2.10.5, target update Construct]
10810 // threadprivate variables cannot appear in a from clause.
10811 if (VD && DSAS->isThreadPrivate(VD)) {
10812 auto DVar = DSAS->getTopDSA(VD, false);
10813 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10814 << getOpenMPClauseName(CKind);
10815 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010816 continue;
10817 }
10818
Samuel Antao5de996e2016-01-22 20:21:36 +000010819 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10820 // A list item cannot appear in both a map clause and a data-sharing
10821 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010822
Samuel Antao5de996e2016-01-22 20:21:36 +000010823 // Check conflicts with other map clause expressions. We check the conflicts
10824 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010825 // environment, because the restrictions are different. We only have to
10826 // check conflicts across regions for the map clauses.
10827 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10828 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010829 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010830 if (CKind == OMPC_map &&
10831 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10832 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010833 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010834
Samuel Antao661c0902016-05-26 17:39:58 +000010835 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010836 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10837 // If the type of a list item is a reference to a type T then the type will
10838 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010839 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010840
Samuel Antao661c0902016-05-26 17:39:58 +000010841 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10842 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010843 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010844 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010845 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10846 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010847 continue;
10848
Samuel Antao661c0902016-05-26 17:39:58 +000010849 if (CKind == OMPC_map) {
10850 // target enter data
10851 // OpenMP [2.10.2, Restrictions, p. 99]
10852 // A map-type must be specified in all map clauses and must be either
10853 // to or alloc.
10854 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10855 if (DKind == OMPD_target_enter_data &&
10856 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10857 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10858 << (IsMapTypeImplicit ? 1 : 0)
10859 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10860 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010861 continue;
10862 }
Samuel Antao661c0902016-05-26 17:39:58 +000010863
10864 // target exit_data
10865 // OpenMP [2.10.3, Restrictions, p. 102]
10866 // A map-type must be specified in all map clauses and must be either
10867 // from, release, or delete.
10868 if (DKind == OMPD_target_exit_data &&
10869 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10870 MapType == OMPC_MAP_delete)) {
10871 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10872 << (IsMapTypeImplicit ? 1 : 0)
10873 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10874 << getOpenMPDirectiveName(DKind);
10875 continue;
10876 }
10877
10878 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10879 // A list item cannot appear in both a map clause and a data-sharing
10880 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010881 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010882 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010883 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010884 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10885 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010886 auto DVar = DSAS->getTopDSA(VD, false);
10887 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010888 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010889 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010890 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010891 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10892 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10893 continue;
10894 }
10895 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010896 }
10897
Samuel Antao90927002016-04-26 14:54:23 +000010898 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010899 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010900
10901 // Store the components in the stack so that they can be used to check
10902 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010903 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10904 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010905
10906 // Save the components and declaration to create the clause. For purposes of
10907 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010908 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010909 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10910 MVLI.VarComponents.back().append(CurComponents.begin(),
10911 CurComponents.end());
10912 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10913 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010914 }
Samuel Antao661c0902016-05-26 17:39:58 +000010915}
10916
10917OMPClause *
10918Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10919 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10920 SourceLocation MapLoc, SourceLocation ColonLoc,
10921 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10922 SourceLocation LParenLoc, SourceLocation EndLoc) {
10923 MappableVarListInfo MVLI(VarList);
10924 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10925 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010926
Samuel Antao5de996e2016-01-22 20:21:36 +000010927 // We need to produce a map clause even if we don't have variables so that
10928 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010929 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10930 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10931 MVLI.VarComponents, MapTypeModifier, MapType,
10932 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010933}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010934
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010935QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10936 TypeResult ParsedType) {
10937 assert(ParsedType.isUsable());
10938
10939 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10940 if (ReductionType.isNull())
10941 return QualType();
10942
10943 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10944 // A type name in a declare reduction directive cannot be a function type, an
10945 // array type, a reference type, or a type qualified with const, volatile or
10946 // restrict.
10947 if (ReductionType.hasQualifiers()) {
10948 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10949 return QualType();
10950 }
10951
10952 if (ReductionType->isFunctionType()) {
10953 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10954 return QualType();
10955 }
10956 if (ReductionType->isReferenceType()) {
10957 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10958 return QualType();
10959 }
10960 if (ReductionType->isArrayType()) {
10961 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10962 return QualType();
10963 }
10964 return ReductionType;
10965}
10966
10967Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10968 Scope *S, DeclContext *DC, DeclarationName Name,
10969 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10970 AccessSpecifier AS, Decl *PrevDeclInScope) {
10971 SmallVector<Decl *, 8> Decls;
10972 Decls.reserve(ReductionTypes.size());
10973
10974 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10975 ForRedeclaration);
10976 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10977 // A reduction-identifier may not be re-declared in the current scope for the
10978 // same type or for a type that is compatible according to the base language
10979 // rules.
10980 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10981 OMPDeclareReductionDecl *PrevDRD = nullptr;
10982 bool InCompoundScope = true;
10983 if (S != nullptr) {
10984 // Find previous declaration with the same name not referenced in other
10985 // declarations.
10986 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10987 InCompoundScope =
10988 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10989 LookupName(Lookup, S);
10990 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10991 /*AllowInlineNamespace=*/false);
10992 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10993 auto Filter = Lookup.makeFilter();
10994 while (Filter.hasNext()) {
10995 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10996 if (InCompoundScope) {
10997 auto I = UsedAsPrevious.find(PrevDecl);
10998 if (I == UsedAsPrevious.end())
10999 UsedAsPrevious[PrevDecl] = false;
11000 if (auto *D = PrevDecl->getPrevDeclInScope())
11001 UsedAsPrevious[D] = true;
11002 }
11003 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11004 PrevDecl->getLocation();
11005 }
11006 Filter.done();
11007 if (InCompoundScope) {
11008 for (auto &PrevData : UsedAsPrevious) {
11009 if (!PrevData.second) {
11010 PrevDRD = PrevData.first;
11011 break;
11012 }
11013 }
11014 }
11015 } else if (PrevDeclInScope != nullptr) {
11016 auto *PrevDRDInScope = PrevDRD =
11017 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11018 do {
11019 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11020 PrevDRDInScope->getLocation();
11021 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11022 } while (PrevDRDInScope != nullptr);
11023 }
11024 for (auto &TyData : ReductionTypes) {
11025 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11026 bool Invalid = false;
11027 if (I != PreviousRedeclTypes.end()) {
11028 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11029 << TyData.first;
11030 Diag(I->second, diag::note_previous_definition);
11031 Invalid = true;
11032 }
11033 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11034 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11035 Name, TyData.first, PrevDRD);
11036 DC->addDecl(DRD);
11037 DRD->setAccess(AS);
11038 Decls.push_back(DRD);
11039 if (Invalid)
11040 DRD->setInvalidDecl();
11041 else
11042 PrevDRD = DRD;
11043 }
11044
11045 return DeclGroupPtrTy::make(
11046 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11047}
11048
11049void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11050 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11051
11052 // Enter new function scope.
11053 PushFunctionScope();
11054 getCurFunction()->setHasBranchProtectedScope();
11055 getCurFunction()->setHasOMPDeclareReductionCombiner();
11056
11057 if (S != nullptr)
11058 PushDeclContext(S, DRD);
11059 else
11060 CurContext = DRD;
11061
Faisal Valid143a0c2017-04-01 21:30:49 +000011062 PushExpressionEvaluationContext(
11063 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011064
11065 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011066 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11067 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11068 // uses semantics of argument handles by value, but it should be passed by
11069 // reference. C lang does not support references, so pass all parameters as
11070 // pointers.
11071 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011072 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011073 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011074 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11075 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11076 // uses semantics of argument handles by value, but it should be passed by
11077 // reference. C lang does not support references, so pass all parameters as
11078 // pointers.
11079 // Create 'T omp_out;' variable.
11080 auto *OmpOutParm =
11081 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11082 if (S != nullptr) {
11083 PushOnScopeChains(OmpInParm, S);
11084 PushOnScopeChains(OmpOutParm, S);
11085 } else {
11086 DRD->addDecl(OmpInParm);
11087 DRD->addDecl(OmpOutParm);
11088 }
11089}
11090
11091void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11092 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11093 DiscardCleanupsInEvaluationContext();
11094 PopExpressionEvaluationContext();
11095
11096 PopDeclContext();
11097 PopFunctionScopeInfo();
11098
11099 if (Combiner != nullptr)
11100 DRD->setCombiner(Combiner);
11101 else
11102 DRD->setInvalidDecl();
11103}
11104
11105void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11106 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11107
11108 // Enter new function scope.
11109 PushFunctionScope();
11110 getCurFunction()->setHasBranchProtectedScope();
11111
11112 if (S != nullptr)
11113 PushDeclContext(S, DRD);
11114 else
11115 CurContext = DRD;
11116
Faisal Valid143a0c2017-04-01 21:30:49 +000011117 PushExpressionEvaluationContext(
11118 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011119
11120 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011121 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11122 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11123 // uses semantics of argument handles by value, but it should be passed by
11124 // reference. C lang does not support references, so pass all parameters as
11125 // pointers.
11126 // Create 'T omp_priv;' variable.
11127 auto *OmpPrivParm =
11128 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011129 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11130 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11131 // uses semantics of argument handles by value, but it should be passed by
11132 // reference. C lang does not support references, so pass all parameters as
11133 // pointers.
11134 // Create 'T omp_orig;' variable.
11135 auto *OmpOrigParm =
11136 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011137 if (S != nullptr) {
11138 PushOnScopeChains(OmpPrivParm, S);
11139 PushOnScopeChains(OmpOrigParm, S);
11140 } else {
11141 DRD->addDecl(OmpPrivParm);
11142 DRD->addDecl(OmpOrigParm);
11143 }
11144}
11145
11146void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11147 Expr *Initializer) {
11148 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11149 DiscardCleanupsInEvaluationContext();
11150 PopExpressionEvaluationContext();
11151
11152 PopDeclContext();
11153 PopFunctionScopeInfo();
11154
11155 if (Initializer != nullptr)
11156 DRD->setInitializer(Initializer);
11157 else
11158 DRD->setInvalidDecl();
11159}
11160
11161Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11162 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11163 for (auto *D : DeclReductions.get()) {
11164 if (IsValid) {
11165 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11166 if (S != nullptr)
11167 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11168 } else
11169 D->setInvalidDecl();
11170 }
11171 return DeclReductions;
11172}
11173
David Majnemer9d168222016-08-05 17:44:54 +000011174OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011175 SourceLocation StartLoc,
11176 SourceLocation LParenLoc,
11177 SourceLocation EndLoc) {
11178 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011179 Stmt *HelperValStmt = nullptr;
11180 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011181
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011182 // OpenMP [teams Constrcut, Restrictions]
11183 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011184 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11185 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011186 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011187
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011188 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11189 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11190 if (CaptureRegion != OMPD_unknown) {
11191 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11192 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11193 HelperValStmt = buildPreInits(Context, Captures);
11194 }
11195
11196 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11197 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011198}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011199
11200OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11201 SourceLocation StartLoc,
11202 SourceLocation LParenLoc,
11203 SourceLocation EndLoc) {
11204 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011205 Stmt *HelperValStmt = nullptr;
11206 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011207
11208 // OpenMP [teams Constrcut, Restrictions]
11209 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011210 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11211 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011212 return nullptr;
11213
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011214 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11215 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11216 if (CaptureRegion != OMPD_unknown) {
11217 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11218 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11219 HelperValStmt = buildPreInits(Context, Captures);
11220 }
11221
11222 return new (Context) OMPThreadLimitClause(
11223 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011224}
Alexey Bataeva0569352015-12-01 10:17:31 +000011225
11226OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11227 SourceLocation StartLoc,
11228 SourceLocation LParenLoc,
11229 SourceLocation EndLoc) {
11230 Expr *ValExpr = Priority;
11231
11232 // OpenMP [2.9.1, task Constrcut]
11233 // The priority-value is a non-negative numerical scalar expression.
11234 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11235 /*StrictlyPositive=*/false))
11236 return nullptr;
11237
11238 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11239}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011240
11241OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11242 SourceLocation StartLoc,
11243 SourceLocation LParenLoc,
11244 SourceLocation EndLoc) {
11245 Expr *ValExpr = Grainsize;
11246
11247 // OpenMP [2.9.2, taskloop Constrcut]
11248 // The parameter of the grainsize clause must be a positive integer
11249 // expression.
11250 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11251 /*StrictlyPositive=*/true))
11252 return nullptr;
11253
11254 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11255}
Alexey Bataev382967a2015-12-08 12:06:20 +000011256
11257OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11258 SourceLocation StartLoc,
11259 SourceLocation LParenLoc,
11260 SourceLocation EndLoc) {
11261 Expr *ValExpr = NumTasks;
11262
11263 // OpenMP [2.9.2, taskloop Constrcut]
11264 // The parameter of the num_tasks clause must be a positive integer
11265 // expression.
11266 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11267 /*StrictlyPositive=*/true))
11268 return nullptr;
11269
11270 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11271}
11272
Alexey Bataev28c75412015-12-15 08:19:24 +000011273OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11274 SourceLocation LParenLoc,
11275 SourceLocation EndLoc) {
11276 // OpenMP [2.13.2, critical construct, Description]
11277 // ... where hint-expression is an integer constant expression that evaluates
11278 // to a valid lock hint.
11279 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11280 if (HintExpr.isInvalid())
11281 return nullptr;
11282 return new (Context)
11283 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11284}
11285
Carlo Bertollib4adf552016-01-15 18:50:31 +000011286OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11287 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11288 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11289 SourceLocation EndLoc) {
11290 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11291 std::string Values;
11292 Values += "'";
11293 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11294 Values += "'";
11295 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11296 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11297 return nullptr;
11298 }
11299 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011300 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011301 if (ChunkSize) {
11302 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11303 !ChunkSize->isInstantiationDependent() &&
11304 !ChunkSize->containsUnexpandedParameterPack()) {
11305 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11306 ExprResult Val =
11307 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11308 if (Val.isInvalid())
11309 return nullptr;
11310
11311 ValExpr = Val.get();
11312
11313 // OpenMP [2.7.1, Restrictions]
11314 // chunk_size must be a loop invariant integer expression with a positive
11315 // value.
11316 llvm::APSInt Result;
11317 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11318 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11319 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11320 << "dist_schedule" << ChunkSize->getSourceRange();
11321 return nullptr;
11322 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011323 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11324 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011325 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11326 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11327 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011328 }
11329 }
11330 }
11331
11332 return new (Context)
11333 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011334 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011335}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011336
11337OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11338 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11339 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11340 SourceLocation KindLoc, SourceLocation EndLoc) {
11341 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011342 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011343 std::string Value;
11344 SourceLocation Loc;
11345 Value += "'";
11346 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11347 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011348 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011349 Loc = MLoc;
11350 } else {
11351 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011352 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011353 Loc = KindLoc;
11354 }
11355 Value += "'";
11356 Diag(Loc, diag::err_omp_unexpected_clause_value)
11357 << Value << getOpenMPClauseName(OMPC_defaultmap);
11358 return nullptr;
11359 }
11360
11361 return new (Context)
11362 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11363}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011364
11365bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11366 DeclContext *CurLexicalContext = getCurLexicalContext();
11367 if (!CurLexicalContext->isFileContext() &&
11368 !CurLexicalContext->isExternCContext() &&
11369 !CurLexicalContext->isExternCXXContext()) {
11370 Diag(Loc, diag::err_omp_region_not_file_context);
11371 return false;
11372 }
11373 if (IsInOpenMPDeclareTargetContext) {
11374 Diag(Loc, diag::err_omp_enclosed_declare_target);
11375 return false;
11376 }
11377
11378 IsInOpenMPDeclareTargetContext = true;
11379 return true;
11380}
11381
11382void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11383 assert(IsInOpenMPDeclareTargetContext &&
11384 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11385
11386 IsInOpenMPDeclareTargetContext = false;
11387}
11388
David Majnemer9d168222016-08-05 17:44:54 +000011389void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11390 CXXScopeSpec &ScopeSpec,
11391 const DeclarationNameInfo &Id,
11392 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11393 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011394 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11395 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11396
11397 if (Lookup.isAmbiguous())
11398 return;
11399 Lookup.suppressDiagnostics();
11400
11401 if (!Lookup.isSingleResult()) {
11402 if (TypoCorrection Corrected =
11403 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11404 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11405 CTK_ErrorRecovery)) {
11406 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11407 << Id.getName());
11408 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11409 return;
11410 }
11411
11412 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11413 return;
11414 }
11415
11416 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11417 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11418 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11419 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11420
11421 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11422 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11423 ND->addAttr(A);
11424 if (ASTMutationListener *ML = Context.getASTMutationListener())
11425 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11426 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11427 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11428 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11429 << Id.getName();
11430 }
11431 } else
11432 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11433}
11434
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011435static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11436 Sema &SemaRef, Decl *D) {
11437 if (!D)
11438 return;
11439 Decl *LD = nullptr;
11440 if (isa<TagDecl>(D)) {
11441 LD = cast<TagDecl>(D)->getDefinition();
11442 } else if (isa<VarDecl>(D)) {
11443 LD = cast<VarDecl>(D)->getDefinition();
11444
11445 // If this is an implicit variable that is legal and we do not need to do
11446 // anything.
11447 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011448 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11449 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11450 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011451 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011452 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011453 return;
11454 }
11455
11456 } else if (isa<FunctionDecl>(D)) {
11457 const FunctionDecl *FD = nullptr;
11458 if (cast<FunctionDecl>(D)->hasBody(FD))
11459 LD = const_cast<FunctionDecl *>(FD);
11460
11461 // If the definition is associated with the current declaration in the
11462 // target region (it can be e.g. a lambda) that is legal and we do not need
11463 // to do anything else.
11464 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011465 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11466 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11467 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011468 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011469 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011470 return;
11471 }
11472 }
11473 if (!LD)
11474 LD = D;
11475 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11476 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11477 // Outlined declaration is not declared target.
11478 if (LD->isOutOfLine()) {
11479 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11480 SemaRef.Diag(SL, diag::note_used_here) << SR;
11481 } else {
11482 DeclContext *DC = LD->getDeclContext();
11483 while (DC) {
11484 if (isa<FunctionDecl>(DC) &&
11485 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11486 break;
11487 DC = DC->getParent();
11488 }
11489 if (DC)
11490 return;
11491
11492 // Is not declared in target context.
11493 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11494 SemaRef.Diag(SL, diag::note_used_here) << SR;
11495 }
11496 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011497 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11498 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11499 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011500 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011501 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011502 }
11503}
11504
11505static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11506 Sema &SemaRef, DSAStackTy *Stack,
11507 ValueDecl *VD) {
11508 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11509 return true;
11510 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11511 return false;
11512 return true;
11513}
11514
11515void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11516 if (!D || D->isInvalidDecl())
11517 return;
11518 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11519 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11520 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11521 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11522 if (DSAStack->isThreadPrivate(VD)) {
11523 Diag(SL, diag::err_omp_threadprivate_in_target);
11524 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11525 return;
11526 }
11527 }
11528 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11529 // Problem if any with var declared with incomplete type will be reported
11530 // as normal, so no need to check it here.
11531 if ((E || !VD->getType()->isIncompleteType()) &&
11532 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11533 // Mark decl as declared target to prevent further diagnostic.
11534 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011535 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11536 Context, OMPDeclareTargetDeclAttr::MT_To);
11537 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011538 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011539 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011540 }
11541 return;
11542 }
11543 }
11544 if (!E) {
11545 // Checking declaration inside declare target region.
11546 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11547 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011548 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11549 Context, OMPDeclareTargetDeclAttr::MT_To);
11550 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011551 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011552 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011553 }
11554 return;
11555 }
11556 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11557}
Samuel Antao661c0902016-05-26 17:39:58 +000011558
11559OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11560 SourceLocation StartLoc,
11561 SourceLocation LParenLoc,
11562 SourceLocation EndLoc) {
11563 MappableVarListInfo MVLI(VarList);
11564 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11565 if (MVLI.ProcessedVarList.empty())
11566 return nullptr;
11567
11568 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11569 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11570 MVLI.VarComponents);
11571}
Samuel Antaoec172c62016-05-26 17:49:04 +000011572
11573OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11574 SourceLocation StartLoc,
11575 SourceLocation LParenLoc,
11576 SourceLocation EndLoc) {
11577 MappableVarListInfo MVLI(VarList);
11578 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11579 if (MVLI.ProcessedVarList.empty())
11580 return nullptr;
11581
11582 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11583 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11584 MVLI.VarComponents);
11585}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011586
11587OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11588 SourceLocation StartLoc,
11589 SourceLocation LParenLoc,
11590 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011591 MappableVarListInfo MVLI(VarList);
11592 SmallVector<Expr *, 8> PrivateCopies;
11593 SmallVector<Expr *, 8> Inits;
11594
Carlo Bertolli2404b172016-07-13 15:37:16 +000011595 for (auto &RefExpr : VarList) {
11596 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11597 SourceLocation ELoc;
11598 SourceRange ERange;
11599 Expr *SimpleRefExpr = RefExpr;
11600 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11601 if (Res.second) {
11602 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011603 MVLI.ProcessedVarList.push_back(RefExpr);
11604 PrivateCopies.push_back(nullptr);
11605 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011606 }
11607 ValueDecl *D = Res.first;
11608 if (!D)
11609 continue;
11610
11611 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011612 Type = Type.getNonReferenceType().getUnqualifiedType();
11613
11614 auto *VD = dyn_cast<VarDecl>(D);
11615
11616 // Item should be a pointer or reference to pointer.
11617 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011618 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11619 << 0 << RefExpr->getSourceRange();
11620 continue;
11621 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011622
11623 // Build the private variable and the expression that refers to it.
11624 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11625 D->hasAttrs() ? &D->getAttrs() : nullptr);
11626 if (VDPrivate->isInvalidDecl())
11627 continue;
11628
11629 CurContext->addDecl(VDPrivate);
11630 auto VDPrivateRefExpr = buildDeclRefExpr(
11631 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11632
11633 // Add temporary variable to initialize the private copy of the pointer.
11634 auto *VDInit =
11635 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11636 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11637 RefExpr->getExprLoc());
11638 AddInitializerToDecl(VDPrivate,
11639 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011640 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011641
11642 // If required, build a capture to implement the privatization initialized
11643 // with the current list item value.
11644 DeclRefExpr *Ref = nullptr;
11645 if (!VD)
11646 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11647 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11648 PrivateCopies.push_back(VDPrivateRefExpr);
11649 Inits.push_back(VDInitRefExpr);
11650
11651 // We need to add a data sharing attribute for this variable to make sure it
11652 // is correctly captured. A variable that shows up in a use_device_ptr has
11653 // similar properties of a first private variable.
11654 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11655
11656 // Create a mappable component for the list item. List items in this clause
11657 // only need a component.
11658 MVLI.VarBaseDeclarations.push_back(D);
11659 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11660 MVLI.VarComponents.back().push_back(
11661 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011662 }
11663
Samuel Antaocc10b852016-07-28 14:23:26 +000011664 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011665 return nullptr;
11666
Samuel Antaocc10b852016-07-28 14:23:26 +000011667 return OMPUseDevicePtrClause::Create(
11668 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11669 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011670}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011671
11672OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11673 SourceLocation StartLoc,
11674 SourceLocation LParenLoc,
11675 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011676 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011677 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011678 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011679 SourceLocation ELoc;
11680 SourceRange ERange;
11681 Expr *SimpleRefExpr = RefExpr;
11682 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11683 if (Res.second) {
11684 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011685 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011686 }
11687 ValueDecl *D = Res.first;
11688 if (!D)
11689 continue;
11690
11691 QualType Type = D->getType();
11692 // item should be a pointer or array or reference to pointer or array
11693 if (!Type.getNonReferenceType()->isPointerType() &&
11694 !Type.getNonReferenceType()->isArrayType()) {
11695 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11696 << 0 << RefExpr->getSourceRange();
11697 continue;
11698 }
Samuel Antao6890b092016-07-28 14:25:09 +000011699
11700 // Check if the declaration in the clause does not show up in any data
11701 // sharing attribute.
11702 auto DVar = DSAStack->getTopDSA(D, false);
11703 if (isOpenMPPrivate(DVar.CKind)) {
11704 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11705 << getOpenMPClauseName(DVar.CKind)
11706 << getOpenMPClauseName(OMPC_is_device_ptr)
11707 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11708 ReportOriginalDSA(*this, DSAStack, D, DVar);
11709 continue;
11710 }
11711
11712 Expr *ConflictExpr;
11713 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011714 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011715 [&ConflictExpr](
11716 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11717 OpenMPClauseKind) -> bool {
11718 ConflictExpr = R.front().getAssociatedExpression();
11719 return true;
11720 })) {
11721 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11722 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11723 << ConflictExpr->getSourceRange();
11724 continue;
11725 }
11726
11727 // Store the components in the stack so that they can be used to check
11728 // against other clauses later on.
11729 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11730 DSAStack->addMappableExpressionComponents(
11731 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11732
11733 // Record the expression we've just processed.
11734 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11735
11736 // Create a mappable component for the list item. List items in this clause
11737 // only need a component. We use a null declaration to signal fields in
11738 // 'this'.
11739 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11740 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11741 "Unexpected device pointer expression!");
11742 MVLI.VarBaseDeclarations.push_back(
11743 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11744 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11745 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011746 }
11747
Samuel Antao6890b092016-07-28 14:25:09 +000011748 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011749 return nullptr;
11750
Samuel Antao6890b092016-07-28 14:25:09 +000011751 return OMPIsDevicePtrClause::Create(
11752 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11753 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011754}