blob: 1bf44127f236177fdc1b9346de872b2c564e099a [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 Bataev4d4624c2017-07-20 16:47:47 +000058 DSAVarData() = default;
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) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000115 SharingMapTy() = default;
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
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000415 /// Do the check specified in \a Check to all component lists at a given level
416 /// and return true if any issue is found.
417 bool checkMappableExprComponentListsForDeclAtLevel(
418 ValueDecl *VD, unsigned Level,
419 const llvm::function_ref<
420 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
421 OpenMPClauseKind)> &Check) {
422 if (isStackEmpty())
423 return false;
424
425 auto StartI = Stack.back().first.begin();
426 auto EndI = Stack.back().first.end();
427 if (std::distance(StartI, EndI) <= (int)Level)
428 return false;
429 std::advance(StartI, Level);
430
431 auto MI = StartI->MappedExprComponents.find(VD);
432 if (MI != StartI->MappedExprComponents.end())
433 for (auto &L : MI->second.Components)
434 if (Check(L, MI->second.Kind))
435 return true;
436 return false;
437 }
438
Samuel Antao4c8035b2016-12-12 18:00:20 +0000439 /// Create a new mappable expression component list associated with a given
440 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000441 void addMappableExpressionComponents(
442 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000443 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
444 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000445 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000446 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000447 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000448 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000449 MEC.Components.resize(MEC.Components.size() + 1);
450 MEC.Components.back().append(Components.begin(), Components.end());
451 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000452 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000453
454 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000455 assert(!isStackEmpty());
456 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000457 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000458 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000459 assert(!isStackEmpty() && Stack.back().first.size() > 1);
460 auto &StackElem = *std::next(Stack.back().first.rbegin());
461 assert(isOpenMPWorksharingDirective(StackElem.Directive));
462 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000463 }
464 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
465 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000466 assert(!isStackEmpty());
467 auto &StackElem = Stack.back().first.back();
468 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
469 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000470 return llvm::make_range(Ref.begin(), Ref.end());
471 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000472 return llvm::make_range(StackElem.DoacrossDepends.end(),
473 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000474 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000475};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000476bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000477 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
478 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000479}
Alexey Bataeved09d242014-05-28 05:53:51 +0000480} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000481
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000482static Expr *getExprAsWritten(Expr *E) {
483 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
484 E = ExprTemp->getSubExpr();
485
486 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
487 E = MTE->GetTemporaryExpr();
488
489 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
490 E = Binder->getSubExpr();
491
492 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
493 E = ICE->getSubExprAsWritten();
494 return E->IgnoreParens();
495}
496
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000497static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000498 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
499 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
500 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000501 auto *VD = dyn_cast<VarDecl>(D);
502 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000503 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000504 VD = VD->getCanonicalDecl();
505 D = VD;
506 } else {
507 assert(FD);
508 FD = FD->getCanonicalDecl();
509 D = FD;
510 }
511 return D;
512}
513
David Majnemer9d168222016-08-05 17:44:54 +0000514DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000515 ValueDecl *D) {
516 D = getCanonicalDecl(D);
517 auto *VD = dyn_cast<VarDecl>(D);
518 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000520 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000521 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
522 // in a region but not in construct]
523 // File-scope or namespace-scope variables referenced in called routines
524 // in the region are shared unless they appear in a threadprivate
525 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000526 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000527 DVar.CKind = OMPC_shared;
528
529 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
530 // in a region but not in construct]
531 // Variables with static storage duration that are declared in called
532 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000533 if (VD && VD->hasGlobalStorage())
534 DVar.CKind = OMPC_shared;
535
536 // Non-static data members are shared by default.
537 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000538 DVar.CKind = OMPC_shared;
539
Alexey Bataev758e55e2013-09-06 18:03:48 +0000540 return DVar;
541 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000542
Alexey Bataevec3da872014-01-31 05:15:34 +0000543 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
544 // in a Construct, C/C++, predetermined, p.1]
545 // Variables with automatic storage duration that are declared in a scope
546 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000547 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
548 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000549 DVar.CKind = OMPC_private;
550 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000551 }
552
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000553 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000554 // Explicitly specified attributes and local variables with predetermined
555 // attributes.
556 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000557 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000558 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000559 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000560 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000561 return DVar;
562 }
563
564 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
565 // in a Construct, C/C++, implicitly determined, p.1]
566 // In a parallel or task construct, the data-sharing attributes of these
567 // variables are determined by the default clause, if present.
568 switch (Iter->DefaultAttr) {
569 case DSA_shared:
570 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000571 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000572 return DVar;
573 case DSA_none:
574 return DVar;
575 case DSA_unspecified:
576 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
577 // in a Construct, implicitly determined, p.2]
578 // In a parallel construct, if no default clause is present, these
579 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000580 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000581 if (isOpenMPParallelDirective(DVar.DKind) ||
582 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000583 DVar.CKind = OMPC_shared;
584 return DVar;
585 }
586
587 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
588 // in a Construct, implicitly determined, p.4]
589 // In a task construct, if no default clause is present, a variable that in
590 // the enclosing context is determined to be shared by all implicit tasks
591 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000592 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000593 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000594 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000595 do {
596 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000597 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000598 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000599 // In a task construct, if no default clause is present, a variable
600 // whose data-sharing attribute is not determined by the rules above is
601 // firstprivate.
602 DVarTemp = getDSA(I, D);
603 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000604 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000605 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000606 return DVar;
607 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000608 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000609 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000610 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000611 return DVar;
612 }
613 }
614 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
615 // in a Construct, implicitly determined, p.3]
616 // For constructs other than task, if no default clause is present, these
617 // variables inherit their data-sharing attributes from the enclosing
618 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000619 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620}
621
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000622Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000623 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000624 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000625 auto &StackElem = Stack.back().first.back();
626 auto It = StackElem.AlignedMap.find(D);
627 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000628 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000629 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000630 return nullptr;
631 } else {
632 assert(It->second && "Unexpected nullptr expr in the aligned map");
633 return It->second;
634 }
635 return nullptr;
636}
637
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000638void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000639 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000640 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000641 auto &StackElem = Stack.back().first.back();
642 StackElem.LCVMap.insert(
643 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000644}
645
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000646DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000647 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000648 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000649 auto &StackElem = Stack.back().first.back();
650 auto It = StackElem.LCVMap.find(D);
651 if (It != StackElem.LCVMap.end())
652 return It->second;
653 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000654}
655
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000656DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000657 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
658 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000659 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000660 auto &StackElem = *std::next(Stack.back().first.rbegin());
661 auto It = StackElem.LCVMap.find(D);
662 if (It != StackElem.LCVMap.end())
663 return It->second;
664 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000665}
666
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000667ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000668 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
669 "Data-sharing attributes stack is empty");
670 auto &StackElem = *std::next(Stack.back().first.rbegin());
671 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000672 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000673 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000674 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000675 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000676 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000677}
678
Alexey Bataev90c228f2016-02-08 09:29:13 +0000679void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
680 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000681 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000682 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000683 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000684 Data.Attributes = A;
685 Data.RefExpr.setPointer(E);
686 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000687 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000688 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
689 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000690 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
691 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
692 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
693 (isLoopControlVariable(D).first && A == OMPC_private));
694 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
695 Data.RefExpr.setInt(/*IntVal=*/true);
696 return;
697 }
698 const bool IsLastprivate =
699 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
700 Data.Attributes = A;
701 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
702 Data.PrivateCopy = PrivateCopy;
703 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000704 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000705 Data.Attributes = A;
706 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
707 Data.PrivateCopy = nullptr;
708 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000709 }
710}
711
Alexey Bataeved09d242014-05-28 05:53:51 +0000712bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000713 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000714 if (!isStackEmpty() && Stack.back().first.size() > 1) {
715 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000716 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000717 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000718 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000719 if (I == E)
720 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000721 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000722 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000723 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000724 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000725 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000726 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000727 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000728}
729
Alexey Bataev39f915b82015-05-08 10:41:21 +0000730/// \brief Build a variable declaration for OpenMP loop iteration variable.
731static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000732 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000733 DeclContext *DC = SemaRef.CurContext;
734 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
735 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
736 VarDecl *Decl =
737 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000738 if (Attrs) {
739 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
740 I != E; ++I)
741 Decl->addAttr(*I);
742 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000743 Decl->setImplicit();
744 return Decl;
745}
746
747static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
748 SourceLocation Loc,
749 bool RefersToCapture = false) {
750 D->setReferenced();
751 D->markUsed(S.Context);
752 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
753 SourceLocation(), D, RefersToCapture, Loc, Ty,
754 VK_LValue);
755}
756
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
758 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000759 DSAVarData DVar;
760
761 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
762 // in a Construct, C/C++, predetermined, p.1]
763 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000764 auto *VD = dyn_cast<VarDecl>(D);
765 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
766 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000767 SemaRef.getLangOpts().OpenMPUseTLS &&
768 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000769 (VD && VD->getStorageClass() == SC_Register &&
770 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
771 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000772 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000773 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000774 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000775 auto TI = Threadprivates.find(D);
776 if (TI != Threadprivates.end()) {
777 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000778 DVar.CKind = OMPC_threadprivate;
779 return DVar;
780 }
781
Alexey Bataev4b465392017-04-26 15:06:24 +0000782 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000783 // Not in OpenMP execution region and top scope was already checked.
784 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000785
Alexey Bataev758e55e2013-09-06 18:03:48 +0000786 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000787 // in a Construct, C/C++, predetermined, p.4]
788 // Static data members are shared.
789 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
790 // in a Construct, C/C++, predetermined, p.7]
791 // Variables with static storage duration that are declared in a scope
792 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000793 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000794 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000795 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000796 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000797 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000798
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000799 DVar.CKind = OMPC_shared;
800 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000801 }
802
803 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000804 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
805 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000806 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
807 // in a Construct, C/C++, predetermined, p.6]
808 // Variables with const qualified type having no mutable member are
809 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000810 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000811 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000812 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
813 if (auto *CTD = CTSD->getSpecializedTemplate())
814 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000815 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000816 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
817 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000818 // Variables with const-qualified type having no mutable member may be
819 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000820 DSAVarData DVarTemp = hasDSA(
821 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
822 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000823 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
824 return DVar;
825
Alexey Bataev758e55e2013-09-06 18:03:48 +0000826 DVar.CKind = OMPC_shared;
827 return DVar;
828 }
829
Alexey Bataev758e55e2013-09-06 18:03:48 +0000830 // Explicitly specified attributes and local variables with predetermined
831 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000832 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000833 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000834 if (FromParent && I != EndI)
835 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000836 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000837 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000838 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000839 DVar.CKind = I->SharingMap[D].Attributes;
840 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000841 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000842 }
843
844 return DVar;
845}
846
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000847DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
848 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000849 if (isStackEmpty()) {
850 StackTy::reverse_iterator I;
851 return getDSA(I, D);
852 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000853 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000854 auto StartI = Stack.back().first.rbegin();
855 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000856 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000857 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000858 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000859}
860
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000861DSAStackTy::DSAVarData
862DSAStackTy::hasDSA(ValueDecl *D,
863 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
864 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
865 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000866 if (isStackEmpty())
867 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000868 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000869 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000870 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000871 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +0000872 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000873 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000874 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000875 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000876 auto NewI = I;
877 DSAVarData DVar = getDSA(NewI, D);
878 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000879 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +0000880 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000881 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000882}
883
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000884DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
885 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
886 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
887 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000888 if (isStackEmpty())
889 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000890 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000891 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000892 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000893 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000894 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +0000895 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +0000896 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000897 auto NewI = StartI;
898 DSAVarData DVar = getDSA(NewI, D);
899 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000900}
901
Alexey Bataevaac108a2015-06-23 04:51:00 +0000902bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000903 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000904 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000905 if (CPred(ClauseKindMode))
906 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000907 if (isStackEmpty())
908 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000909 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000910 auto StartI = Stack.back().first.begin();
911 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000912 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000913 return false;
914 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000915 return (StartI->SharingMap.count(D) > 0) &&
916 StartI->SharingMap[D].RefExpr.getPointer() &&
917 CPred(StartI->SharingMap[D].Attributes) &&
918 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000919}
920
Samuel Antao4be30e92015-10-02 17:14:03 +0000921bool DSAStackTy::hasExplicitDirective(
922 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
923 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000924 if (isStackEmpty())
925 return false;
926 auto StartI = Stack.back().first.begin();
927 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000928 if (std::distance(StartI, EndI) <= (int)Level)
929 return false;
930 std::advance(StartI, Level);
931 return DPred(StartI->Directive);
932}
933
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000934bool DSAStackTy::hasDirective(
935 const llvm::function_ref<bool(OpenMPDirectiveKind,
936 const DeclarationNameInfo &, SourceLocation)>
937 &DPred,
938 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000939 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000940 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +0000941 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +0000942 auto StartI = std::next(Stack.back().first.rbegin());
943 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000944 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000945 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000946 for (auto I = StartI, EE = EndI; I != EE; ++I) {
947 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
948 return true;
949 }
950 return false;
951}
952
Alexey Bataev758e55e2013-09-06 18:03:48 +0000953void Sema::InitDataSharingAttributesStack() {
954 VarDataSharingAttributesStack = new DSAStackTy(*this);
955}
956
957#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
958
Alexey Bataev4b465392017-04-26 15:06:24 +0000959void Sema::pushOpenMPFunctionRegion() {
960 DSAStack->pushFunction();
961}
962
963void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
964 DSAStack->popFunction(OldFSI);
965}
966
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000967bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000968 assert(LangOpts.OpenMP && "OpenMP is not allowed");
969
970 auto &Ctx = getASTContext();
971 bool IsByRef = true;
972
973 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000974 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000975
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000976 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000977 // This table summarizes how a given variable should be passed to the device
978 // given its type and the clauses where it appears. This table is based on
979 // the description in OpenMP 4.5 [2.10.4, target Construct] and
980 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
981 //
982 // =========================================================================
983 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
984 // | |(tofrom:scalar)| | pvt | | | |
985 // =========================================================================
986 // | scl | | | | - | | bycopy|
987 // | scl | | - | x | - | - | bycopy|
988 // | scl | | x | - | - | - | null |
989 // | scl | x | | | - | | byref |
990 // | scl | x | - | x | - | - | bycopy|
991 // | scl | x | x | - | - | - | null |
992 // | scl | | - | - | - | x | byref |
993 // | scl | x | - | - | - | x | byref |
994 //
995 // | agg | n.a. | | | - | | byref |
996 // | agg | n.a. | - | x | - | - | byref |
997 // | agg | n.a. | x | - | - | - | null |
998 // | agg | n.a. | - | - | - | x | byref |
999 // | agg | n.a. | - | - | - | x[] | byref |
1000 //
1001 // | ptr | n.a. | | | - | | bycopy|
1002 // | ptr | n.a. | - | x | - | - | bycopy|
1003 // | ptr | n.a. | x | - | - | - | null |
1004 // | ptr | n.a. | - | - | - | x | byref |
1005 // | ptr | n.a. | - | - | - | x[] | bycopy|
1006 // | ptr | n.a. | - | - | x | | bycopy|
1007 // | ptr | n.a. | - | - | x | x | bycopy|
1008 // | ptr | n.a. | - | - | x | x[] | bycopy|
1009 // =========================================================================
1010 // Legend:
1011 // scl - scalar
1012 // ptr - pointer
1013 // agg - aggregate
1014 // x - applies
1015 // - - invalid in this combination
1016 // [] - mapped with an array section
1017 // byref - should be mapped by reference
1018 // byval - should be mapped by value
1019 // null - initialize a local variable to null on the device
1020 //
1021 // Observations:
1022 // - All scalar declarations that show up in a map clause have to be passed
1023 // by reference, because they may have been mapped in the enclosing data
1024 // environment.
1025 // - If the scalar value does not fit the size of uintptr, it has to be
1026 // passed by reference, regardless the result in the table above.
1027 // - For pointers mapped by value that have either an implicit map or an
1028 // array section, the runtime library may pass the NULL value to the
1029 // device instead of the value passed to it by the compiler.
1030
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001031 if (Ty->isReferenceType())
1032 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001033
1034 // Locate map clauses and see if the variable being captured is referred to
1035 // in any of those clauses. Here we only care about variables, not fields,
1036 // because fields are part of aggregates.
1037 bool IsVariableUsedInMapClause = false;
1038 bool IsVariableAssociatedWithSection = false;
1039
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001040 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1041 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001042 MapExprComponents,
1043 OpenMPClauseKind WhereFoundClauseKind) {
1044 // Only the map clause information influences how a variable is
1045 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001046 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001047 if (WhereFoundClauseKind != OMPC_map)
1048 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001049
1050 auto EI = MapExprComponents.rbegin();
1051 auto EE = MapExprComponents.rend();
1052
1053 assert(EI != EE && "Invalid map expression!");
1054
1055 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1056 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1057
1058 ++EI;
1059 if (EI == EE)
1060 return false;
1061
1062 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1063 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1064 isa<MemberExpr>(EI->getAssociatedExpression())) {
1065 IsVariableAssociatedWithSection = true;
1066 // There is nothing more we need to know about this variable.
1067 return true;
1068 }
1069
1070 // Keep looking for more map info.
1071 return false;
1072 });
1073
1074 if (IsVariableUsedInMapClause) {
1075 // If variable is identified in a map clause it is always captured by
1076 // reference except if it is a pointer that is dereferenced somehow.
1077 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1078 } else {
1079 // By default, all the data that has a scalar type is mapped by copy.
1080 IsByRef = !Ty->isScalarType();
1081 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001082 }
1083
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001084 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1085 IsByRef = !DSAStack->hasExplicitDSA(
1086 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1087 Level, /*NotLastprivate=*/true);
1088 }
1089
Samuel Antao86ace552016-04-27 22:40:57 +00001090 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001091 // and alignment, because the runtime library only deals with uintptr types.
1092 // If it does not fit the uintptr size, we need to pass the data by reference
1093 // instead.
1094 if (!IsByRef &&
1095 (Ctx.getTypeSizeInChars(Ty) >
1096 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001097 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001098 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001099 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001100
1101 return IsByRef;
1102}
1103
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001104unsigned Sema::getOpenMPNestingLevel() const {
1105 assert(getLangOpts().OpenMP);
1106 return DSAStack->getNestingLevel();
1107}
1108
Alexey Bataev90c228f2016-02-08 09:29:13 +00001109VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001110 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001111 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001112
1113 // If we are attempting to capture a global variable in a directive with
1114 // 'target' we return true so that this global is also mapped to the device.
1115 //
1116 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1117 // then it should not be captured. Therefore, an extra check has to be
1118 // inserted here once support for 'declare target' is added.
1119 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001120 auto *VD = dyn_cast<VarDecl>(D);
1121 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001122 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001123 !DSAStack->isClauseParsingMode())
1124 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001125 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001126 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1127 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001128 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001129 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001130 false))
1131 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001132 }
1133
Alexey Bataev48977c32015-08-04 08:10:48 +00001134 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1135 (!DSAStack->isClauseParsingMode() ||
1136 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001137 auto &&Info = DSAStack->isLoopControlVariable(D);
1138 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001139 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001140 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001141 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001142 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001143 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001144 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001145 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001146 DVarPrivate = DSAStack->hasDSA(
1147 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1148 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001149 if (DVarPrivate.CKind != OMPC_unknown)
1150 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001151 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001152 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001153}
1154
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001155bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001156 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1157 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001158 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001159}
1160
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001161bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001162 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1163 // Return true if the current level is no longer enclosed in a target region.
1164
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001165 auto *VD = dyn_cast<VarDecl>(D);
1166 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001167 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1168 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001169}
1170
Alexey Bataeved09d242014-05-28 05:53:51 +00001171void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001172
1173void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1174 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001175 Scope *CurScope, SourceLocation Loc) {
1176 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001177 PushExpressionEvaluationContext(
1178 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001179}
1180
Alexey Bataevaac108a2015-06-23 04:51:00 +00001181void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1182 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001183}
1184
Alexey Bataevaac108a2015-06-23 04:51:00 +00001185void Sema::EndOpenMPClause() {
1186 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001187}
1188
Alexey Bataev758e55e2013-09-06 18:03:48 +00001189void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001190 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1191 // A variable of class type (or array thereof) that appears in a lastprivate
1192 // clause requires an accessible, unambiguous default constructor for the
1193 // class type, unless the list item is also specified in a firstprivate
1194 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001195 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001196 for (auto *C : D->clauses()) {
1197 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1198 SmallVector<Expr *, 8> PrivateCopies;
1199 for (auto *DE : Clause->varlists()) {
1200 if (DE->isValueDependent() || DE->isTypeDependent()) {
1201 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001202 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001203 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001204 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001205 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1206 QualType Type = VD->getType().getNonReferenceType();
1207 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001208 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001209 // Generate helper private variable and initialize it with the
1210 // default value. The address of the original variable is replaced
1211 // by the address of the new private variable in CodeGen. This new
1212 // variable is not added to IdResolver, so the code in the OpenMP
1213 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001214 auto *VDPrivate = buildVarDecl(
1215 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001216 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001217 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001218 if (VDPrivate->isInvalidDecl())
1219 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001220 PrivateCopies.push_back(buildDeclRefExpr(
1221 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001222 } else {
1223 // The variable is also a firstprivate, so initialization sequence
1224 // for private copy is generated already.
1225 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001226 }
1227 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001228 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001229 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001230 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001231 }
1232 }
1233 }
1234
Alexey Bataev758e55e2013-09-06 18:03:48 +00001235 DSAStack->pop();
1236 DiscardCleanupsInEvaluationContext();
1237 PopExpressionEvaluationContext();
1238}
1239
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001240static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1241 Expr *NumIterations, Sema &SemaRef,
1242 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001243
Alexey Bataeva769e072013-03-22 06:34:35 +00001244namespace {
1245
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001246class VarDeclFilterCCC : public CorrectionCandidateCallback {
1247private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001248 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001249
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001250public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001251 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001252 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001253 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001254 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001255 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001256 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1257 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001258 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001259 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001260 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001261};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001262
1263class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1264private:
1265 Sema &SemaRef;
1266
1267public:
1268 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1269 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1270 NamedDecl *ND = Candidate.getCorrectionDecl();
1271 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1272 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1273 SemaRef.getCurScope());
1274 }
1275 return false;
1276 }
1277};
1278
Alexey Bataeved09d242014-05-28 05:53:51 +00001279} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280
1281ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1282 CXXScopeSpec &ScopeSpec,
1283 const DeclarationNameInfo &Id) {
1284 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1285 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1286
1287 if (Lookup.isAmbiguous())
1288 return ExprError();
1289
1290 VarDecl *VD;
1291 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001292 if (TypoCorrection Corrected = CorrectTypo(
1293 Id, LookupOrdinaryName, CurScope, nullptr,
1294 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001295 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001296 PDiag(Lookup.empty()
1297 ? diag::err_undeclared_var_use_suggest
1298 : diag::err_omp_expected_var_arg_suggest)
1299 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001300 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001301 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001302 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1303 : diag::err_omp_expected_var_arg)
1304 << Id.getName();
1305 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001306 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001307 } else {
1308 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001309 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001310 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1311 return ExprError();
1312 }
1313 }
1314 Lookup.suppressDiagnostics();
1315
1316 // OpenMP [2.9.2, Syntax, C/C++]
1317 // Variables must be file-scope, namespace-scope, or static block-scope.
1318 if (!VD->hasGlobalStorage()) {
1319 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001320 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1321 bool IsDecl =
1322 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1325 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 return ExprError();
1327 }
1328
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001329 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1330 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001331 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1332 // A threadprivate directive for file-scope variables must appear outside
1333 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001334 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1335 !getCurLexicalContext()->isTranslationUnit()) {
1336 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001337 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1338 bool IsDecl =
1339 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1340 Diag(VD->getLocation(),
1341 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1342 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001343 return ExprError();
1344 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001345 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1346 // A threadprivate directive for static class member variables must appear
1347 // in the class definition, in the same scope in which the member
1348 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001349 if (CanonicalVD->isStaticDataMember() &&
1350 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1351 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001352 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1353 bool IsDecl =
1354 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1355 Diag(VD->getLocation(),
1356 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1357 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001358 return ExprError();
1359 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001360 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1361 // A threadprivate directive for namespace-scope variables must appear
1362 // outside any definition or declaration other than the namespace
1363 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001364 if (CanonicalVD->getDeclContext()->isNamespace() &&
1365 (!getCurLexicalContext()->isFileContext() ||
1366 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1367 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001368 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1369 bool IsDecl =
1370 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1371 Diag(VD->getLocation(),
1372 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1373 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001374 return ExprError();
1375 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001376 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1377 // A threadprivate directive for static block-scope variables must appear
1378 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001379 if (CanonicalVD->isStaticLocal() && CurScope &&
1380 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001381 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001382 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1383 bool IsDecl =
1384 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1385 Diag(VD->getLocation(),
1386 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1387 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001388 return ExprError();
1389 }
1390
1391 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1392 // A threadprivate directive must lexically precede all references to any
1393 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001394 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001395 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001396 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001397 return ExprError();
1398 }
1399
1400 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001401 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1402 SourceLocation(), VD,
1403 /*RefersToEnclosingVariableOrCapture=*/false,
1404 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001405}
1406
Alexey Bataeved09d242014-05-28 05:53:51 +00001407Sema::DeclGroupPtrTy
1408Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1409 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001410 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001411 CurContext->addDecl(D);
1412 return DeclGroupPtrTy::make(DeclGroupRef(D));
1413 }
David Blaikie0403cb12016-01-15 23:43:25 +00001414 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001415}
1416
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001417namespace {
1418class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1419 Sema &SemaRef;
1420
1421public:
1422 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001423 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001424 if (VD->hasLocalStorage()) {
1425 SemaRef.Diag(E->getLocStart(),
1426 diag::err_omp_local_var_in_threadprivate_init)
1427 << E->getSourceRange();
1428 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1429 << VD << VD->getSourceRange();
1430 return true;
1431 }
1432 }
1433 return false;
1434 }
1435 bool VisitStmt(const Stmt *S) {
1436 for (auto Child : S->children()) {
1437 if (Child && Visit(Child))
1438 return true;
1439 }
1440 return false;
1441 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001442 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001443};
1444} // namespace
1445
Alexey Bataeved09d242014-05-28 05:53:51 +00001446OMPThreadPrivateDecl *
1447Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001448 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001449 for (auto &RefExpr : VarList) {
1450 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001451 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1452 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001453
Alexey Bataev376b4a42016-02-09 09:41:09 +00001454 // Mark variable as used.
1455 VD->setReferenced();
1456 VD->markUsed(Context);
1457
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001458 QualType QType = VD->getType();
1459 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1460 // It will be analyzed later.
1461 Vars.push_back(DE);
1462 continue;
1463 }
1464
Alexey Bataeva769e072013-03-22 06:34:35 +00001465 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1466 // A threadprivate variable must not have an incomplete type.
1467 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001468 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001469 continue;
1470 }
1471
1472 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1473 // A threadprivate variable must not have a reference type.
1474 if (VD->getType()->isReferenceType()) {
1475 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001476 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1477 bool IsDecl =
1478 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1479 Diag(VD->getLocation(),
1480 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1481 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001482 continue;
1483 }
1484
Samuel Antaof8b50122015-07-13 22:54:53 +00001485 // Check if this is a TLS variable. If TLS is not being supported, produce
1486 // the corresponding diagnostic.
1487 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1488 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1489 getLangOpts().OpenMPUseTLS &&
1490 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001491 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1492 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001493 Diag(ILoc, diag::err_omp_var_thread_local)
1494 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001495 bool IsDecl =
1496 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1497 Diag(VD->getLocation(),
1498 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1499 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001500 continue;
1501 }
1502
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001503 // Check if initial value of threadprivate variable reference variable with
1504 // local storage (it is not supported by runtime).
1505 if (auto Init = VD->getAnyInitializer()) {
1506 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001507 if (Checker.Visit(Init))
1508 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001509 }
1510
Alexey Bataeved09d242014-05-28 05:53:51 +00001511 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001512 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001513 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1514 Context, SourceRange(Loc, Loc)));
1515 if (auto *ML = Context.getASTMutationListener())
1516 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001517 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001518 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001519 if (!Vars.empty()) {
1520 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1521 Vars);
1522 D->setAccess(AS_public);
1523 }
1524 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001525}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001526
Alexey Bataev7ff55242014-06-19 09:13:45 +00001527static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001528 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001529 bool IsLoopIterVar = false) {
1530 if (DVar.RefExpr) {
1531 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1532 << getOpenMPClauseName(DVar.CKind);
1533 return;
1534 }
1535 enum {
1536 PDSA_StaticMemberShared,
1537 PDSA_StaticLocalVarShared,
1538 PDSA_LoopIterVarPrivate,
1539 PDSA_LoopIterVarLinear,
1540 PDSA_LoopIterVarLastprivate,
1541 PDSA_ConstVarShared,
1542 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001543 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001544 PDSA_LocalVarPrivate,
1545 PDSA_Implicit
1546 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001547 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001548 auto ReportLoc = D->getLocation();
1549 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001550 if (IsLoopIterVar) {
1551 if (DVar.CKind == OMPC_private)
1552 Reason = PDSA_LoopIterVarPrivate;
1553 else if (DVar.CKind == OMPC_lastprivate)
1554 Reason = PDSA_LoopIterVarLastprivate;
1555 else
1556 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001557 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1558 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001559 Reason = PDSA_TaskVarFirstprivate;
1560 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001562 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001563 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001564 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001565 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001566 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001567 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001568 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001569 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001570 ReportHint = true;
1571 Reason = PDSA_LocalVarPrivate;
1572 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001573 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001575 << Reason << ReportHint
1576 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1577 } else if (DVar.ImplicitDSALoc.isValid()) {
1578 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1579 << getOpenMPClauseName(DVar.CKind);
1580 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001581}
1582
Alexey Bataev758e55e2013-09-06 18:03:48 +00001583namespace {
1584class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1585 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001587 bool ErrorFound;
1588 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001589 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001590 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001591
Alexey Bataev758e55e2013-09-06 18:03:48 +00001592public:
1593 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001594 if (E->isTypeDependent() || E->isValueDependent() ||
1595 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1596 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001597 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001598 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001599 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1600 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001601
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001602 auto DVar = Stack->getTopDSA(VD, false);
1603 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001604 if (DVar.RefExpr)
1605 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001606
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001607 auto ELoc = E->getExprLoc();
1608 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001609 // The default(none) clause requires that each variable that is referenced
1610 // in the construct, and does not have a predetermined data-sharing
1611 // attribute, must have its data-sharing attribute explicitly determined
1612 // by being listed in a data-sharing attribute clause.
1613 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001614 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001615 VarsWithInheritedDSA.count(VD) == 0) {
1616 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001617 return;
1618 }
1619
1620 // OpenMP [2.9.3.6, Restrictions, p.2]
1621 // A list item that appears in a reduction clause of the innermost
1622 // enclosing worksharing or parallel construct may not be accessed in an
1623 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001624 DVar = Stack->hasInnermostDSA(
1625 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1626 [](OpenMPDirectiveKind K) -> bool {
1627 return isOpenMPParallelDirective(K) ||
1628 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1629 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001630 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001631 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001632 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001633 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1634 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001635 return;
1636 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001637
1638 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001639 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001640 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1641 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001642 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001643 }
1644 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001645 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001646 if (E->isTypeDependent() || E->isValueDependent() ||
1647 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1648 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001649 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1650 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1651 auto DVar = Stack->getTopDSA(FD, false);
1652 // Check if the variable has explicit DSA set and stop analysis if it
1653 // so.
1654 if (DVar.RefExpr)
1655 return;
1656
1657 auto ELoc = E->getExprLoc();
1658 auto DKind = Stack->getCurrentDirective();
1659 // OpenMP [2.9.3.6, Restrictions, p.2]
1660 // A list item that appears in a reduction clause of the innermost
1661 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001662 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001663 DVar = Stack->hasInnermostDSA(
1664 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1665 [](OpenMPDirectiveKind K) -> bool {
1666 return isOpenMPParallelDirective(K) ||
1667 isOpenMPWorksharingDirective(K) ||
1668 isOpenMPTeamsDirective(K);
1669 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001670 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001671 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001672 ErrorFound = true;
1673 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1674 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1675 return;
1676 }
1677
1678 // Define implicit data-sharing attributes for task.
1679 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001680 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1681 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001682 ImplicitFirstprivate.push_back(E);
1683 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001684 } else
1685 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001686 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001687 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001688 for (auto *C : S->clauses()) {
1689 // Skip analysis of arguments of implicitly defined firstprivate clause
1690 // for task directives.
1691 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1692 for (auto *CC : C->children()) {
1693 if (CC)
1694 Visit(CC);
1695 }
1696 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001697 }
1698 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001699 for (auto *C : S->children()) {
1700 if (C && !isa<OMPExecutableDirective>(C))
1701 Visit(C);
1702 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001703 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001704
1705 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001706 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001707 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001708 return VarsWithInheritedDSA;
1709 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001710
Alexey Bataev7ff55242014-06-19 09:13:45 +00001711 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1712 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001713};
Alexey Bataeved09d242014-05-28 05:53:51 +00001714} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001715
Alexey Bataevbae9a792014-06-27 10:37:06 +00001716void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001717 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001718 case OMPD_parallel:
1719 case OMPD_parallel_for:
1720 case OMPD_parallel_for_simd:
1721 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001722 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001723 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001724 QualType KmpInt32PtrTy =
1725 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001726 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001727 std::make_pair(".global_tid.", KmpInt32PtrTy),
1728 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1729 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001730 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001731 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1732 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001733 break;
1734 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001735 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001736 case OMPD_target_parallel: {
1737 Sema::CapturedParamNameType ParamsTarget[] = {
1738 std::make_pair(StringRef(), QualType()) // __context with shared vars
1739 };
1740 // Start a captured region for 'target' with no implicit parameters.
1741 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1742 ParamsTarget);
1743 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1744 QualType KmpInt32PtrTy =
1745 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001746 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001747 std::make_pair(".global_tid.", KmpInt32PtrTy),
1748 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1749 std::make_pair(StringRef(), QualType()) // __context with shared vars
1750 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001751 // Start a captured region for 'teams' or 'parallel'. Both regions have
1752 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001753 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001754 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001755 break;
1756 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001757 case OMPD_simd:
1758 case OMPD_for:
1759 case OMPD_for_simd:
1760 case OMPD_sections:
1761 case OMPD_section:
1762 case OMPD_single:
1763 case OMPD_master:
1764 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001765 case OMPD_taskgroup:
1766 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001767 case OMPD_ordered:
1768 case OMPD_atomic:
1769 case OMPD_target_data:
1770 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001771 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001772 case OMPD_target_parallel_for_simd:
1773 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001774 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001775 std::make_pair(StringRef(), QualType()) // __context with shared vars
1776 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001777 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1778 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001779 break;
1780 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001781 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001782 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001783 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1784 FunctionProtoType::ExtProtoInfo EPI;
1785 EPI.Variadic = true;
1786 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001787 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001788 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001789 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1790 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1791 std::make_pair(".copy_fn.",
1792 Context.getPointerType(CopyFnType).withConst()),
1793 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001794 std::make_pair(StringRef(), QualType()) // __context with shared vars
1795 };
1796 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1797 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001798 // Mark this captured region as inlined, because we don't use outlined
1799 // function directly.
1800 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1801 AlwaysInlineAttr::CreateImplicit(
1802 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001803 break;
1804 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001805 case OMPD_taskloop:
1806 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001807 QualType KmpInt32Ty =
1808 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1809 QualType KmpUInt64Ty =
1810 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1811 QualType KmpInt64Ty =
1812 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1813 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1814 FunctionProtoType::ExtProtoInfo EPI;
1815 EPI.Variadic = true;
1816 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001817 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001818 std::make_pair(".global_tid.", KmpInt32Ty),
1819 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1820 std::make_pair(".privates.",
1821 Context.VoidPtrTy.withConst().withRestrict()),
1822 std::make_pair(
1823 ".copy_fn.",
1824 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1825 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1826 std::make_pair(".lb.", KmpUInt64Ty),
1827 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1828 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001829 std::make_pair(".reductions.",
1830 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001831 std::make_pair(StringRef(), QualType()) // __context with shared vars
1832 };
1833 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1834 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001835 // Mark this captured region as inlined, because we don't use outlined
1836 // function directly.
1837 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1838 AlwaysInlineAttr::CreateImplicit(
1839 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001840 break;
1841 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001842 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001843 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001844 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001845 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001846 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001847 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001848 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001849 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001850 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001851 case OMPD_target_teams_distribute_parallel_for_simd:
1852 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001853 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1854 QualType KmpInt32PtrTy =
1855 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1856 Sema::CapturedParamNameType Params[] = {
1857 std::make_pair(".global_tid.", KmpInt32PtrTy),
1858 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1859 std::make_pair(".previous.lb.", Context.getSizeType()),
1860 std::make_pair(".previous.ub.", Context.getSizeType()),
1861 std::make_pair(StringRef(), QualType()) // __context with shared vars
1862 };
1863 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1864 Params);
1865 break;
1866 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001867 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001868 case OMPD_taskyield:
1869 case OMPD_barrier:
1870 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001871 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001872 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001873 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001874 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001875 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001876 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001877 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001878 case OMPD_declare_target:
1879 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001880 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001881 llvm_unreachable("OpenMP Directive is not allowed");
1882 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001883 llvm_unreachable("Unknown OpenMP directive");
1884 }
1885}
1886
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001887int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1888 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1889 getOpenMPCaptureRegions(CaptureRegions, DKind);
1890 return CaptureRegions.size();
1891}
1892
Alexey Bataev3392d762016-02-16 11:18:12 +00001893static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001894 Expr *CaptureExpr, bool WithInit,
1895 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001896 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001897 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001898 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001899 QualType Ty = Init->getType();
1900 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1901 if (S.getLangOpts().CPlusPlus)
1902 Ty = C.getLValueReferenceType(Ty);
1903 else {
1904 Ty = C.getPointerType(Ty);
1905 ExprResult Res =
1906 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1907 if (!Res.isUsable())
1908 return nullptr;
1909 Init = Res.get();
1910 }
Alexey Bataev61205072016-03-02 04:57:40 +00001911 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001912 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001913 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1914 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001915 if (!WithInit)
1916 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001917 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001918 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001919 return CED;
1920}
1921
Alexey Bataev61205072016-03-02 04:57:40 +00001922static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1923 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001924 OMPCapturedExprDecl *CD;
1925 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1926 CD = cast<OMPCapturedExprDecl>(VD);
1927 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001928 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1929 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001930 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001931 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001932}
1933
Alexey Bataev5a3af132016-03-29 08:58:54 +00001934static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1935 if (!Ref) {
1936 auto *CD =
1937 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1938 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1939 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1940 CaptureExpr->getExprLoc());
1941 }
1942 ExprResult Res = Ref;
1943 if (!S.getLangOpts().CPlusPlus &&
1944 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1945 Ref->getType()->isPointerType())
1946 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1947 if (!Res.isUsable())
1948 return ExprError();
1949 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001950}
1951
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001952namespace {
1953// OpenMP directives parsed in this section are represented as a
1954// CapturedStatement with an associated statement. If a syntax error
1955// is detected during the parsing of the associated statement, the
1956// compiler must abort processing and close the CapturedStatement.
1957//
1958// Combined directives such as 'target parallel' have more than one
1959// nested CapturedStatements. This RAII ensures that we unwind out
1960// of all the nested CapturedStatements when an error is found.
1961class CaptureRegionUnwinderRAII {
1962private:
1963 Sema &S;
1964 bool &ErrorFound;
1965 OpenMPDirectiveKind DKind;
1966
1967public:
1968 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1969 OpenMPDirectiveKind DKind)
1970 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1971 ~CaptureRegionUnwinderRAII() {
1972 if (ErrorFound) {
1973 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1974 while (--ThisCaptureLevel >= 0)
1975 S.ActOnCapturedRegionError();
1976 }
1977 }
1978};
1979} // namespace
1980
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001981StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1982 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001983 bool ErrorFound = false;
1984 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1985 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001986 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001987 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001988 return StmtError();
1989 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001990
1991 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001992 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001993 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001994 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001995 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001996 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001997 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001998 Clause->getClauseKind() == OMPC_copyprivate ||
1999 (getLangOpts().OpenMPUseTLS &&
2000 getASTContext().getTargetInfo().isTLSSupported() &&
2001 Clause->getClauseKind() == OMPC_copyin)) {
2002 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002003 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002004 for (auto *VarRef : Clause->children()) {
2005 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002006 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002007 }
2008 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002009 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002010 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002011 if (auto *C = OMPClauseWithPreInit::get(Clause))
2012 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002013 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2014 if (auto *E = C->getPostUpdateExpr())
2015 MarkDeclarationsReferencedInExpr(E);
2016 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002017 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002018 if (Clause->getClauseKind() == OMPC_schedule)
2019 SC = cast<OMPScheduleClause>(Clause);
2020 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002021 OC = cast<OMPOrderedClause>(Clause);
2022 else if (Clause->getClauseKind() == OMPC_linear)
2023 LCs.push_back(cast<OMPLinearClause>(Clause));
2024 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002025 // OpenMP, 2.7.1 Loop Construct, Restrictions
2026 // The nonmonotonic modifier cannot be specified if an ordered clause is
2027 // specified.
2028 if (SC &&
2029 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2030 SC->getSecondScheduleModifier() ==
2031 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2032 OC) {
2033 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2034 ? SC->getFirstScheduleModifierLoc()
2035 : SC->getSecondScheduleModifierLoc(),
2036 diag::err_omp_schedule_nonmonotonic_ordered)
2037 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2038 ErrorFound = true;
2039 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002040 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2041 for (auto *C : LCs) {
2042 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2043 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2044 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002045 ErrorFound = true;
2046 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002047 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2048 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2049 OC->getNumForLoops()) {
2050 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2051 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2052 ErrorFound = true;
2053 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002054 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002055 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002056 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002057 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002058 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2059 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2060 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2061 // Mark all variables in private list clauses as used in inner region.
2062 // Required for proper codegen of combined directives.
2063 // TODO: add processing for other clauses.
2064 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2065 for (auto *C : PICs) {
2066 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2067 // Find the particular capture region for the clause if the
2068 // directive is a combined one with multiple capture regions.
2069 // If the directive is not a combined one, the capture region
2070 // associated with the clause is OMPD_unknown and is generated
2071 // only once.
2072 if (CaptureRegion == ThisCaptureRegion ||
2073 CaptureRegion == OMPD_unknown) {
2074 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2075 for (auto *D : DS->decls())
2076 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2077 }
2078 }
2079 }
2080 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002081 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002082 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002083 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002084}
2085
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002086static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2087 OpenMPDirectiveKind CancelRegion,
2088 SourceLocation StartLoc) {
2089 // CancelRegion is only needed for cancel and cancellation_point.
2090 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2091 return false;
2092
2093 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2094 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2095 return false;
2096
2097 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2098 << getOpenMPDirectiveName(CancelRegion);
2099 return true;
2100}
2101
2102static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002103 OpenMPDirectiveKind CurrentRegion,
2104 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002105 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002106 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002107 if (Stack->getCurScope()) {
2108 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002109 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002110 bool NestingProhibited = false;
2111 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002112 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002113 enum {
2114 NoRecommend,
2115 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002116 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002117 ShouldBeInTargetRegion,
2118 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002119 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002120 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002121 // OpenMP [2.16, Nesting of Regions]
2122 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002123 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002124 // An ordered construct with the simd clause is the only OpenMP
2125 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002126 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002127 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2128 // message.
2129 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2130 ? diag::err_omp_prohibited_region_simd
2131 : diag::warn_omp_nesting_simd);
2132 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002133 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002134 if (ParentRegion == OMPD_atomic) {
2135 // OpenMP [2.16, Nesting of Regions]
2136 // OpenMP constructs may not be nested inside an atomic region.
2137 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2138 return true;
2139 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002140 if (CurrentRegion == OMPD_section) {
2141 // OpenMP [2.7.2, sections Construct, Restrictions]
2142 // Orphaned section directives are prohibited. That is, the section
2143 // directives must appear within the sections construct and must not be
2144 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002145 if (ParentRegion != OMPD_sections &&
2146 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002147 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2148 << (ParentRegion != OMPD_unknown)
2149 << getOpenMPDirectiveName(ParentRegion);
2150 return true;
2151 }
2152 return false;
2153 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002154 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002155 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002156 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002157 if (ParentRegion == OMPD_unknown &&
2158 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002159 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002160 if (CurrentRegion == OMPD_cancellation_point ||
2161 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002162 // OpenMP [2.16, Nesting of Regions]
2163 // A cancellation point construct for which construct-type-clause is
2164 // taskgroup must be nested inside a task construct. A cancellation
2165 // point construct for which construct-type-clause is not taskgroup must
2166 // be closely nested inside an OpenMP construct that matches the type
2167 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002168 // A cancel construct for which construct-type-clause is taskgroup must be
2169 // nested inside a task construct. A cancel construct for which
2170 // construct-type-clause is not taskgroup must be closely nested inside an
2171 // OpenMP construct that matches the type specified in
2172 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002173 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002174 !((CancelRegion == OMPD_parallel &&
2175 (ParentRegion == OMPD_parallel ||
2176 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002177 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002178 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2179 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002180 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2181 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002182 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2183 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002184 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002185 // OpenMP [2.16, Nesting of Regions]
2186 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002187 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002188 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002189 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002190 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2191 // OpenMP [2.16, Nesting of Regions]
2192 // A critical region may not be nested (closely or otherwise) inside a
2193 // critical region with the same name. Note that this restriction is not
2194 // sufficient to prevent deadlock.
2195 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002196 bool DeadLock = Stack->hasDirective(
2197 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2198 const DeclarationNameInfo &DNI,
2199 SourceLocation Loc) -> bool {
2200 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2201 PreviousCriticalLoc = Loc;
2202 return true;
2203 } else
2204 return false;
2205 },
2206 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002207 if (DeadLock) {
2208 SemaRef.Diag(StartLoc,
2209 diag::err_omp_prohibited_region_critical_same_name)
2210 << CurrentName.getName();
2211 if (PreviousCriticalLoc.isValid())
2212 SemaRef.Diag(PreviousCriticalLoc,
2213 diag::note_omp_previous_critical_region);
2214 return true;
2215 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002216 } else if (CurrentRegion == OMPD_barrier) {
2217 // OpenMP [2.16, Nesting of Regions]
2218 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002219 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002220 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2221 isOpenMPTaskingDirective(ParentRegion) ||
2222 ParentRegion == OMPD_master ||
2223 ParentRegion == OMPD_critical ||
2224 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002225 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002226 !isOpenMPParallelDirective(CurrentRegion) &&
2227 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002228 // OpenMP [2.16, Nesting of Regions]
2229 // A worksharing region may not be closely nested inside a worksharing,
2230 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002231 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2232 isOpenMPTaskingDirective(ParentRegion) ||
2233 ParentRegion == OMPD_master ||
2234 ParentRegion == OMPD_critical ||
2235 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002236 Recommend = ShouldBeInParallelRegion;
2237 } else if (CurrentRegion == OMPD_ordered) {
2238 // OpenMP [2.16, Nesting of Regions]
2239 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002240 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002241 // An ordered region must be closely nested inside a loop region (or
2242 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002243 // OpenMP [2.8.1,simd Construct, Restrictions]
2244 // An ordered construct with the simd clause is the only OpenMP construct
2245 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002246 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002247 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002248 !(isOpenMPSimdDirective(ParentRegion) ||
2249 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002250 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002251 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002252 // OpenMP [2.16, Nesting of Regions]
2253 // If specified, a teams construct must be contained within a target
2254 // construct.
2255 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002256 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002257 Recommend = ShouldBeInTargetRegion;
2258 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2259 }
Kelvin Libf594a52016-12-17 05:48:59 +00002260 if (!NestingProhibited &&
2261 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2262 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2263 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002264 // OpenMP [2.16, Nesting of Regions]
2265 // distribute, parallel, parallel sections, parallel workshare, and the
2266 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2267 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002268 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2269 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002270 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002271 }
David Majnemer9d168222016-08-05 17:44:54 +00002272 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002273 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002274 // OpenMP 4.5 [2.17 Nesting of Regions]
2275 // The region associated with the distribute construct must be strictly
2276 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002277 NestingProhibited =
2278 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002279 Recommend = ShouldBeInTeamsRegion;
2280 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002281 if (!NestingProhibited &&
2282 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2283 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2284 // OpenMP 4.5 [2.17 Nesting of Regions]
2285 // If a target, target update, target data, target enter data, or
2286 // target exit data construct is encountered during execution of a
2287 // target region, the behavior is unspecified.
2288 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002289 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2290 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002291 if (isOpenMPTargetExecutionDirective(K)) {
2292 OffendingRegion = K;
2293 return true;
2294 } else
2295 return false;
2296 },
2297 false /* don't skip top directive */);
2298 CloseNesting = false;
2299 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002300 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002301 if (OrphanSeen) {
2302 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2303 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2304 } else {
2305 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2306 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2307 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2308 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002309 return true;
2310 }
2311 }
2312 return false;
2313}
2314
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002315static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2316 ArrayRef<OMPClause *> Clauses,
2317 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2318 bool ErrorFound = false;
2319 unsigned NamedModifiersNumber = 0;
2320 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2321 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002322 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002323 for (const auto *C : Clauses) {
2324 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2325 // At most one if clause without a directive-name-modifier can appear on
2326 // the directive.
2327 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2328 if (FoundNameModifiers[CurNM]) {
2329 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2330 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2331 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2332 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002333 } else if (CurNM != OMPD_unknown) {
2334 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002335 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002336 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002337 FoundNameModifiers[CurNM] = IC;
2338 if (CurNM == OMPD_unknown)
2339 continue;
2340 // Check if the specified name modifier is allowed for the current
2341 // directive.
2342 // At most one if clause with the particular directive-name-modifier can
2343 // appear on the directive.
2344 bool MatchFound = false;
2345 for (auto NM : AllowedNameModifiers) {
2346 if (CurNM == NM) {
2347 MatchFound = true;
2348 break;
2349 }
2350 }
2351 if (!MatchFound) {
2352 S.Diag(IC->getNameModifierLoc(),
2353 diag::err_omp_wrong_if_directive_name_modifier)
2354 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2355 ErrorFound = true;
2356 }
2357 }
2358 }
2359 // If any if clause on the directive includes a directive-name-modifier then
2360 // all if clauses on the directive must include a directive-name-modifier.
2361 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2362 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2363 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2364 diag::err_omp_no_more_if_clause);
2365 } else {
2366 std::string Values;
2367 std::string Sep(", ");
2368 unsigned AllowedCnt = 0;
2369 unsigned TotalAllowedNum =
2370 AllowedNameModifiers.size() - NamedModifiersNumber;
2371 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2372 ++Cnt) {
2373 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2374 if (!FoundNameModifiers[NM]) {
2375 Values += "'";
2376 Values += getOpenMPDirectiveName(NM);
2377 Values += "'";
2378 if (AllowedCnt + 2 == TotalAllowedNum)
2379 Values += " or ";
2380 else if (AllowedCnt + 1 != TotalAllowedNum)
2381 Values += Sep;
2382 ++AllowedCnt;
2383 }
2384 }
2385 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2386 diag::err_omp_unnamed_if_clause)
2387 << (TotalAllowedNum > 1) << Values;
2388 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002389 for (auto Loc : NameModifierLoc) {
2390 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2391 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002392 ErrorFound = true;
2393 }
2394 return ErrorFound;
2395}
2396
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002397StmtResult Sema::ActOnOpenMPExecutableDirective(
2398 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2399 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2400 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002401 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002402 // First check CancelRegion which is then used in checkNestingOfRegions.
2403 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2404 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002405 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002406 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002407
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002408 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002409 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002410 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002411 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002412 if (AStmt) {
2413 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2414
2415 // Check default data sharing attributes for referenced variables.
2416 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002417 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2418 Stmt *S = AStmt;
2419 while (--ThisCaptureLevel >= 0)
2420 S = cast<CapturedStmt>(S)->getCapturedStmt();
2421 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002422 if (DSAChecker.isErrorFound())
2423 return StmtError();
2424 // Generate list of implicitly defined firstprivate variables.
2425 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002426
2427 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2428 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2429 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2430 SourceLocation(), SourceLocation())) {
2431 ClausesWithImplicit.push_back(Implicit);
2432 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2433 DSAChecker.getImplicitFirstprivate().size();
2434 } else
2435 ErrorFound = true;
2436 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002437 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002438
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002439 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002440 switch (Kind) {
2441 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002442 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2443 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002444 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002445 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002446 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002447 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2448 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002449 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002450 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002451 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2452 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002453 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002454 case OMPD_for_simd:
2455 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2456 EndLoc, VarsWithInheritedDSA);
2457 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002458 case OMPD_sections:
2459 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2460 EndLoc);
2461 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002462 case OMPD_section:
2463 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002464 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002465 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2466 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002467 case OMPD_single:
2468 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2469 EndLoc);
2470 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002471 case OMPD_master:
2472 assert(ClausesWithImplicit.empty() &&
2473 "No clauses are allowed for 'omp master' directive");
2474 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2475 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002476 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002477 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2478 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002479 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002480 case OMPD_parallel_for:
2481 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2482 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002483 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002484 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002485 case OMPD_parallel_for_simd:
2486 Res = ActOnOpenMPParallelForSimdDirective(
2487 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002488 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002489 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002490 case OMPD_parallel_sections:
2491 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2492 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002493 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002494 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002495 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002496 Res =
2497 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002498 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002499 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002500 case OMPD_taskyield:
2501 assert(ClausesWithImplicit.empty() &&
2502 "No clauses are allowed for 'omp taskyield' directive");
2503 assert(AStmt == nullptr &&
2504 "No associated statement allowed for 'omp taskyield' directive");
2505 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2506 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002507 case OMPD_barrier:
2508 assert(ClausesWithImplicit.empty() &&
2509 "No clauses are allowed for 'omp barrier' directive");
2510 assert(AStmt == nullptr &&
2511 "No associated statement allowed for 'omp barrier' directive");
2512 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2513 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002514 case OMPD_taskwait:
2515 assert(ClausesWithImplicit.empty() &&
2516 "No clauses are allowed for 'omp taskwait' directive");
2517 assert(AStmt == nullptr &&
2518 "No associated statement allowed for 'omp taskwait' directive");
2519 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2520 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002521 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002522 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2523 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002524 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002525 case OMPD_flush:
2526 assert(AStmt == nullptr &&
2527 "No associated statement allowed for 'omp flush' directive");
2528 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2529 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002530 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002531 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2532 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002533 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002534 case OMPD_atomic:
2535 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2536 EndLoc);
2537 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002538 case OMPD_teams:
2539 Res =
2540 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2541 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002542 case OMPD_target:
2543 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2544 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002545 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002546 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002547 case OMPD_target_parallel:
2548 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2549 StartLoc, EndLoc);
2550 AllowedNameModifiers.push_back(OMPD_target);
2551 AllowedNameModifiers.push_back(OMPD_parallel);
2552 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002553 case OMPD_target_parallel_for:
2554 Res = ActOnOpenMPTargetParallelForDirective(
2555 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2556 AllowedNameModifiers.push_back(OMPD_target);
2557 AllowedNameModifiers.push_back(OMPD_parallel);
2558 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002559 case OMPD_cancellation_point:
2560 assert(ClausesWithImplicit.empty() &&
2561 "No clauses are allowed for 'omp cancellation point' directive");
2562 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2563 "cancellation point' directive");
2564 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2565 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002566 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002567 assert(AStmt == nullptr &&
2568 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002569 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2570 CancelRegion);
2571 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002572 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002573 case OMPD_target_data:
2574 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2575 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002576 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002577 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002578 case OMPD_target_enter_data:
2579 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2580 EndLoc);
2581 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2582 break;
Samuel Antao72590762016-01-19 20:04:50 +00002583 case OMPD_target_exit_data:
2584 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2585 EndLoc);
2586 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2587 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002588 case OMPD_taskloop:
2589 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2590 EndLoc, VarsWithInheritedDSA);
2591 AllowedNameModifiers.push_back(OMPD_taskloop);
2592 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002593 case OMPD_taskloop_simd:
2594 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2595 EndLoc, VarsWithInheritedDSA);
2596 AllowedNameModifiers.push_back(OMPD_taskloop);
2597 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002598 case OMPD_distribute:
2599 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2600 EndLoc, VarsWithInheritedDSA);
2601 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002602 case OMPD_target_update:
2603 assert(!AStmt && "Statement is not allowed for target update");
2604 Res =
2605 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2606 AllowedNameModifiers.push_back(OMPD_target_update);
2607 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002608 case OMPD_distribute_parallel_for:
2609 Res = ActOnOpenMPDistributeParallelForDirective(
2610 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2611 AllowedNameModifiers.push_back(OMPD_parallel);
2612 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002613 case OMPD_distribute_parallel_for_simd:
2614 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2615 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2616 AllowedNameModifiers.push_back(OMPD_parallel);
2617 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002618 case OMPD_distribute_simd:
2619 Res = ActOnOpenMPDistributeSimdDirective(
2620 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2621 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002622 case OMPD_target_parallel_for_simd:
2623 Res = ActOnOpenMPTargetParallelForSimdDirective(
2624 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2625 AllowedNameModifiers.push_back(OMPD_target);
2626 AllowedNameModifiers.push_back(OMPD_parallel);
2627 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002628 case OMPD_target_simd:
2629 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2630 EndLoc, VarsWithInheritedDSA);
2631 AllowedNameModifiers.push_back(OMPD_target);
2632 break;
Kelvin Li02532872016-08-05 14:37:37 +00002633 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002634 Res = ActOnOpenMPTeamsDistributeDirective(
2635 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002636 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002637 case OMPD_teams_distribute_simd:
2638 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2639 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2640 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002641 case OMPD_teams_distribute_parallel_for_simd:
2642 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2643 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2644 AllowedNameModifiers.push_back(OMPD_parallel);
2645 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002646 case OMPD_teams_distribute_parallel_for:
2647 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2648 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2649 AllowedNameModifiers.push_back(OMPD_parallel);
2650 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002651 case OMPD_target_teams:
2652 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2653 EndLoc);
2654 AllowedNameModifiers.push_back(OMPD_target);
2655 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002656 case OMPD_target_teams_distribute:
2657 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2658 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2659 AllowedNameModifiers.push_back(OMPD_target);
2660 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002661 case OMPD_target_teams_distribute_parallel_for:
2662 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2663 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2664 AllowedNameModifiers.push_back(OMPD_target);
2665 AllowedNameModifiers.push_back(OMPD_parallel);
2666 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002667 case OMPD_target_teams_distribute_parallel_for_simd:
2668 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2669 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2670 AllowedNameModifiers.push_back(OMPD_target);
2671 AllowedNameModifiers.push_back(OMPD_parallel);
2672 break;
Kelvin Lida681182017-01-10 18:08:18 +00002673 case OMPD_target_teams_distribute_simd:
2674 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2675 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2676 AllowedNameModifiers.push_back(OMPD_target);
2677 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002678 case OMPD_declare_target:
2679 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002680 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002681 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002682 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002683 llvm_unreachable("OpenMP Directive is not allowed");
2684 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002685 llvm_unreachable("Unknown OpenMP directive");
2686 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002687
Alexey Bataev4acb8592014-07-07 13:01:15 +00002688 for (auto P : VarsWithInheritedDSA) {
2689 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2690 << P.first << P.second->getSourceRange();
2691 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002692 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2693
2694 if (!AllowedNameModifiers.empty())
2695 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2696 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002697
Alexey Bataeved09d242014-05-28 05:53:51 +00002698 if (ErrorFound)
2699 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002700 return Res;
2701}
2702
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002703Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2704 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002705 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002706 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2707 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002708 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002709 assert(Linears.size() == LinModifiers.size());
2710 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002711 if (!DG || DG.get().isNull())
2712 return DeclGroupPtrTy();
2713
2714 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002715 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002716 return DG;
2717 }
2718 auto *ADecl = DG.get().getSingleDecl();
2719 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2720 ADecl = FTD->getTemplatedDecl();
2721
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002722 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2723 if (!FD) {
2724 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002725 return DeclGroupPtrTy();
2726 }
2727
Alexey Bataev2af33e32016-04-07 12:45:37 +00002728 // OpenMP [2.8.2, declare simd construct, Description]
2729 // The parameter of the simdlen clause must be a constant positive integer
2730 // expression.
2731 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002732 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002733 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002734 // OpenMP [2.8.2, declare simd construct, Description]
2735 // The special this pointer can be used as if was one of the arguments to the
2736 // function in any of the linear, aligned, or uniform clauses.
2737 // The uniform clause declares one or more arguments to have an invariant
2738 // value for all concurrent invocations of the function in the execution of a
2739 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002740 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2741 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002742 for (auto *E : Uniforms) {
2743 E = E->IgnoreParenImpCasts();
2744 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2745 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2746 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2747 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002748 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2749 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002750 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002751 }
2752 if (isa<CXXThisExpr>(E)) {
2753 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002754 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002755 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002756 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2757 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002758 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002759 // OpenMP [2.8.2, declare simd construct, Description]
2760 // The aligned clause declares that the object to which each list item points
2761 // is aligned to the number of bytes expressed in the optional parameter of
2762 // the aligned clause.
2763 // The special this pointer can be used as if was one of the arguments to the
2764 // function in any of the linear, aligned, or uniform clauses.
2765 // The type of list items appearing in the aligned clause must be array,
2766 // pointer, reference to array, or reference to pointer.
2767 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2768 Expr *AlignedThis = nullptr;
2769 for (auto *E : Aligneds) {
2770 E = E->IgnoreParenImpCasts();
2771 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2772 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2773 auto *CanonPVD = PVD->getCanonicalDecl();
2774 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2775 FD->getParamDecl(PVD->getFunctionScopeIndex())
2776 ->getCanonicalDecl() == CanonPVD) {
2777 // OpenMP [2.8.1, simd construct, Restrictions]
2778 // A list-item cannot appear in more than one aligned clause.
2779 if (AlignedArgs.count(CanonPVD) > 0) {
2780 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2781 << 1 << E->getSourceRange();
2782 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2783 diag::note_omp_explicit_dsa)
2784 << getOpenMPClauseName(OMPC_aligned);
2785 continue;
2786 }
2787 AlignedArgs[CanonPVD] = E;
2788 QualType QTy = PVD->getType()
2789 .getNonReferenceType()
2790 .getUnqualifiedType()
2791 .getCanonicalType();
2792 const Type *Ty = QTy.getTypePtrOrNull();
2793 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2794 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2795 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2796 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2797 }
2798 continue;
2799 }
2800 }
2801 if (isa<CXXThisExpr>(E)) {
2802 if (AlignedThis) {
2803 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2804 << 2 << E->getSourceRange();
2805 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2806 << getOpenMPClauseName(OMPC_aligned);
2807 }
2808 AlignedThis = E;
2809 continue;
2810 }
2811 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2812 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2813 }
2814 // The optional parameter of the aligned clause, alignment, must be a constant
2815 // positive integer expression. If no optional parameter is specified,
2816 // implementation-defined default alignments for SIMD instructions on the
2817 // target platforms are assumed.
2818 SmallVector<Expr *, 4> NewAligns;
2819 for (auto *E : Alignments) {
2820 ExprResult Align;
2821 if (E)
2822 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2823 NewAligns.push_back(Align.get());
2824 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002825 // OpenMP [2.8.2, declare simd construct, Description]
2826 // The linear clause declares one or more list items to be private to a SIMD
2827 // lane and to have a linear relationship with respect to the iteration space
2828 // of a loop.
2829 // The special this pointer can be used as if was one of the arguments to the
2830 // function in any of the linear, aligned, or uniform clauses.
2831 // When a linear-step expression is specified in a linear clause it must be
2832 // either a constant integer expression or an integer-typed parameter that is
2833 // specified in a uniform clause on the directive.
2834 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2835 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2836 auto MI = LinModifiers.begin();
2837 for (auto *E : Linears) {
2838 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2839 ++MI;
2840 E = E->IgnoreParenImpCasts();
2841 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2842 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2843 auto *CanonPVD = PVD->getCanonicalDecl();
2844 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2845 FD->getParamDecl(PVD->getFunctionScopeIndex())
2846 ->getCanonicalDecl() == CanonPVD) {
2847 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2848 // A list-item cannot appear in more than one linear clause.
2849 if (LinearArgs.count(CanonPVD) > 0) {
2850 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2851 << getOpenMPClauseName(OMPC_linear)
2852 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2853 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2854 diag::note_omp_explicit_dsa)
2855 << getOpenMPClauseName(OMPC_linear);
2856 continue;
2857 }
2858 // Each argument can appear in at most one uniform or linear clause.
2859 if (UniformedArgs.count(CanonPVD) > 0) {
2860 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2861 << getOpenMPClauseName(OMPC_linear)
2862 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2863 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2864 diag::note_omp_explicit_dsa)
2865 << getOpenMPClauseName(OMPC_uniform);
2866 continue;
2867 }
2868 LinearArgs[CanonPVD] = E;
2869 if (E->isValueDependent() || E->isTypeDependent() ||
2870 E->isInstantiationDependent() ||
2871 E->containsUnexpandedParameterPack())
2872 continue;
2873 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2874 PVD->getOriginalType());
2875 continue;
2876 }
2877 }
2878 if (isa<CXXThisExpr>(E)) {
2879 if (UniformedLinearThis) {
2880 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2881 << getOpenMPClauseName(OMPC_linear)
2882 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2883 << E->getSourceRange();
2884 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2885 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2886 : OMPC_linear);
2887 continue;
2888 }
2889 UniformedLinearThis = E;
2890 if (E->isValueDependent() || E->isTypeDependent() ||
2891 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2892 continue;
2893 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2894 E->getType());
2895 continue;
2896 }
2897 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2898 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2899 }
2900 Expr *Step = nullptr;
2901 Expr *NewStep = nullptr;
2902 SmallVector<Expr *, 4> NewSteps;
2903 for (auto *E : Steps) {
2904 // Skip the same step expression, it was checked already.
2905 if (Step == E || !E) {
2906 NewSteps.push_back(E ? NewStep : nullptr);
2907 continue;
2908 }
2909 Step = E;
2910 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2911 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2912 auto *CanonPVD = PVD->getCanonicalDecl();
2913 if (UniformedArgs.count(CanonPVD) == 0) {
2914 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2915 << Step->getSourceRange();
2916 } else if (E->isValueDependent() || E->isTypeDependent() ||
2917 E->isInstantiationDependent() ||
2918 E->containsUnexpandedParameterPack() ||
2919 CanonPVD->getType()->hasIntegerRepresentation())
2920 NewSteps.push_back(Step);
2921 else {
2922 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2923 << Step->getSourceRange();
2924 }
2925 continue;
2926 }
2927 NewStep = Step;
2928 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2929 !Step->isInstantiationDependent() &&
2930 !Step->containsUnexpandedParameterPack()) {
2931 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2932 .get();
2933 if (NewStep)
2934 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2935 }
2936 NewSteps.push_back(NewStep);
2937 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002938 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2939 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002940 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002941 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2942 const_cast<Expr **>(Linears.data()), Linears.size(),
2943 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2944 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002945 ADecl->addAttr(NewAttr);
2946 return ConvertDeclToDeclGroup(ADecl);
2947}
2948
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002949StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2950 Stmt *AStmt,
2951 SourceLocation StartLoc,
2952 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002953 if (!AStmt)
2954 return StmtError();
2955
Alexey Bataev9959db52014-05-06 10:08:46 +00002956 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2957 // 1.2.2 OpenMP Language Terminology
2958 // Structured block - An executable statement with a single entry at the
2959 // top and a single exit at the bottom.
2960 // The point of exit cannot be a branch out of the structured block.
2961 // longjmp() and throw() must not violate the entry/exit criteria.
2962 CS->getCapturedDecl()->setNothrow();
2963
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002964 getCurFunction()->setHasBranchProtectedScope();
2965
Alexey Bataev25e5b442015-09-15 12:52:43 +00002966 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2967 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002968}
2969
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002970namespace {
2971/// \brief Helper class for checking canonical form of the OpenMP loops and
2972/// extracting iteration space of each loop in the loop nest, that will be used
2973/// for IR generation.
2974class OpenMPIterationSpaceChecker {
2975 /// \brief Reference to Sema.
2976 Sema &SemaRef;
2977 /// \brief A location for diagnostics (when there is no some better location).
2978 SourceLocation DefaultLoc;
2979 /// \brief A location for diagnostics (when increment is not compatible).
2980 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002981 /// \brief A source location for referring to loop init later.
2982 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002983 /// \brief A source location for referring to condition later.
2984 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002985 /// \brief A source location for referring to increment later.
2986 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002987 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002988 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002989 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002990 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002991 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002992 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002993 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002994 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002995 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002996 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002997 /// \brief This flag is true when condition is one of:
2998 /// Var < UB
2999 /// Var <= UB
3000 /// UB > Var
3001 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003002 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003003 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003004 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003005 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003006 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003007
3008public:
3009 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003010 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003011 /// \brief Check init-expr for canonical loop form and save loop counter
3012 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003013 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003014 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3015 /// for less/greater and for strict/non-strict comparison.
3016 bool CheckCond(Expr *S);
3017 /// \brief Check incr-expr for canonical loop form and return true if it
3018 /// does not conform, otherwise save loop step (#Step).
3019 bool CheckInc(Expr *S);
3020 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003021 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003022 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003023 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003024 /// \brief Source range of the loop init.
3025 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3026 /// \brief Source range of the loop condition.
3027 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3028 /// \brief Source range of the loop increment.
3029 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3030 /// \brief True if the step should be subtracted.
3031 bool ShouldSubtractStep() const { return SubtractStep; }
3032 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003033 Expr *
3034 BuildNumIterations(Scope *S, const bool LimitedType,
3035 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003036 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003037 Expr *BuildPreCond(Scope *S, Expr *Cond,
3038 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003039 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003040 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3041 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003042 /// \brief Build reference expression to the private counter be used for
3043 /// codegen.
3044 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003045 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003046 Expr *BuildCounterInit() const;
3047 /// \brief Build step of the counter be used for codegen.
3048 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003049 /// \brief Return true if any expression is dependent.
3050 bool Dependent() const;
3051
3052private:
3053 /// \brief Check the right-hand side of an assignment in the increment
3054 /// expression.
3055 bool CheckIncRHS(Expr *RHS);
3056 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003057 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003058 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003059 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003060 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003061 /// \brief Helper to set loop increment.
3062 bool SetStep(Expr *NewStep, bool Subtract);
3063};
3064
3065bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003066 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003067 assert(!LB && !UB && !Step);
3068 return false;
3069 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003070 return LCDecl->getType()->isDependentType() ||
3071 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3072 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003073}
3074
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003075bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3076 Expr *NewLCRefExpr,
3077 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003078 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003079 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003080 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003081 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003082 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003083 LCDecl = getCanonicalDecl(NewLCDecl);
3084 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003085 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3086 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003087 if ((Ctor->isCopyOrMoveConstructor() ||
3088 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3089 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003090 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 LB = NewLB;
3092 return false;
3093}
3094
3095bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003096 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003097 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003098 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3099 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003100 if (!NewUB)
3101 return true;
3102 UB = NewUB;
3103 TestIsLessOp = LessOp;
3104 TestIsStrictOp = StrictOp;
3105 ConditionSrcRange = SR;
3106 ConditionLoc = SL;
3107 return false;
3108}
3109
3110bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3111 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003112 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003113 if (!NewStep)
3114 return true;
3115 if (!NewStep->isValueDependent()) {
3116 // Check that the step is integer expression.
3117 SourceLocation StepLoc = NewStep->getLocStart();
3118 ExprResult Val =
3119 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3120 if (Val.isInvalid())
3121 return true;
3122 NewStep = Val.get();
3123
3124 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3125 // If test-expr is of form var relational-op b and relational-op is < or
3126 // <= then incr-expr must cause var to increase on each iteration of the
3127 // loop. If test-expr is of form var relational-op b and relational-op is
3128 // > or >= then incr-expr must cause var to decrease on each iteration of
3129 // the loop.
3130 // If test-expr is of form b relational-op var and relational-op is < or
3131 // <= then incr-expr must cause var to decrease on each iteration of the
3132 // loop. If test-expr is of form b relational-op var and relational-op is
3133 // > or >= then incr-expr must cause var to increase on each iteration of
3134 // the loop.
3135 llvm::APSInt Result;
3136 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3137 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3138 bool IsConstNeg =
3139 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003140 bool IsConstPos =
3141 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003142 bool IsConstZero = IsConstant && !Result.getBoolValue();
3143 if (UB && (IsConstZero ||
3144 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003145 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003146 SemaRef.Diag(NewStep->getExprLoc(),
3147 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003148 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003149 SemaRef.Diag(ConditionLoc,
3150 diag::note_omp_loop_cond_requres_compatible_incr)
3151 << TestIsLessOp << ConditionSrcRange;
3152 return true;
3153 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003154 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003155 NewStep =
3156 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3157 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003158 Subtract = !Subtract;
3159 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003160 }
3161
3162 Step = NewStep;
3163 SubtractStep = Subtract;
3164 return false;
3165}
3166
Alexey Bataev9c821032015-04-30 04:23:23 +00003167bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 // Check init-expr for canonical loop form and save loop counter
3169 // variable - #Var and its initialization value - #LB.
3170 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3171 // var = lb
3172 // integer-type var = lb
3173 // random-access-iterator-type var = lb
3174 // pointer-type var = lb
3175 //
3176 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003177 if (EmitDiags) {
3178 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3179 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003180 return true;
3181 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003182 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3183 if (!ExprTemp->cleanupsHaveSideEffects())
3184 S = ExprTemp->getSubExpr();
3185
Alexander Musmana5f070a2014-10-01 06:03:56 +00003186 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003187 if (Expr *E = dyn_cast<Expr>(S))
3188 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003189 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003190 if (BO->getOpcode() == BO_Assign) {
3191 auto *LHS = BO->getLHS()->IgnoreParens();
3192 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3193 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, BO->getRHS());
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 }
David Majnemer9d168222016-08-05 17:44:54 +00003204 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003205 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003206 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003207 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003208 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003209 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003210 SemaRef.Diag(S->getLocStart(),
3211 diag::ext_omp_loop_not_canonical_init)
3212 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003213 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003214 }
3215 }
3216 }
David Majnemer9d168222016-08-05 17:44:54 +00003217 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003218 if (CE->getOperator() == OO_Equal) {
3219 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003220 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003221 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3222 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3223 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3224 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3225 }
3226 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3227 if (ME->isArrow() &&
3228 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3229 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3230 }
3231 }
3232 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003233
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003234 if (Dependent() || SemaRef.CurContext->isDependentContext())
3235 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003236 if (EmitDiags) {
3237 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3238 << S->getSourceRange();
3239 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003240 return true;
3241}
3242
Alexey Bataev23b69422014-06-18 07:08:49 +00003243/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003244/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003245static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003246 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003247 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003248 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003249 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3250 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003251 if ((Ctor->isCopyOrMoveConstructor() ||
3252 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3253 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003254 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003255 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003256 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003257 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003258 }
3259 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3260 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3261 return getCanonicalDecl(ME->getMemberDecl());
3262 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003263}
3264
3265bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3266 // Check test-expr for canonical form, save upper-bound UB, flags for
3267 // less/greater and for strict/non-strict comparison.
3268 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3269 // var relational-op b
3270 // b relational-op var
3271 //
3272 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003273 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003274 return true;
3275 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003276 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003277 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003278 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003279 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003280 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003281 return SetUB(BO->getRHS(),
3282 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3283 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3284 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003285 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003286 return SetUB(BO->getLHS(),
3287 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3288 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3289 BO->getSourceRange(), BO->getOperatorLoc());
3290 }
David Majnemer9d168222016-08-05 17:44:54 +00003291 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003292 if (CE->getNumArgs() == 2) {
3293 auto Op = CE->getOperator();
3294 switch (Op) {
3295 case OO_Greater:
3296 case OO_GreaterEqual:
3297 case OO_Less:
3298 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003299 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003300 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3301 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3302 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003303 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003304 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3305 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3306 CE->getOperatorLoc());
3307 break;
3308 default:
3309 break;
3310 }
3311 }
3312 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003313 if (Dependent() || SemaRef.CurContext->isDependentContext())
3314 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003315 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003316 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003317 return true;
3318}
3319
3320bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3321 // RHS of canonical loop form increment can be:
3322 // var + incr
3323 // incr + var
3324 // var - incr
3325 //
3326 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003327 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003328 if (BO->isAdditiveOp()) {
3329 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003330 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003331 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003332 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003333 return SetStep(BO->getLHS(), false);
3334 }
David Majnemer9d168222016-08-05 17:44:54 +00003335 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003336 bool IsAdd = CE->getOperator() == OO_Plus;
3337 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003338 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003339 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003340 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003341 return SetStep(CE->getArg(0), false);
3342 }
3343 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003344 if (Dependent() || SemaRef.CurContext->isDependentContext())
3345 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003346 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003347 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003348 return true;
3349}
3350
3351bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3352 // Check incr-expr for canonical loop form and return true if it
3353 // does not conform.
3354 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3355 // ++var
3356 // var++
3357 // --var
3358 // var--
3359 // var += incr
3360 // var -= incr
3361 // var = var + incr
3362 // var = incr + var
3363 // var = var - incr
3364 //
3365 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003366 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003367 return true;
3368 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003369 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3370 if (!ExprTemp->cleanupsHaveSideEffects())
3371 S = ExprTemp->getSubExpr();
3372
Alexander Musmana5f070a2014-10-01 06:03:56 +00003373 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003374 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003375 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003376 if (UO->isIncrementDecrementOp() &&
3377 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003378 return SetStep(SemaRef
3379 .ActOnIntegerConstant(UO->getLocStart(),
3380 (UO->isDecrementOp() ? -1 : 1))
3381 .get(),
3382 false);
3383 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003384 switch (BO->getOpcode()) {
3385 case BO_AddAssign:
3386 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003387 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003388 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3389 break;
3390 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003391 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003392 return CheckIncRHS(BO->getRHS());
3393 break;
3394 default:
3395 break;
3396 }
David Majnemer9d168222016-08-05 17:44:54 +00003397 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003398 switch (CE->getOperator()) {
3399 case OO_PlusPlus:
3400 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003401 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003402 return SetStep(SemaRef
3403 .ActOnIntegerConstant(
3404 CE->getLocStart(),
3405 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3406 .get(),
3407 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003408 break;
3409 case OO_PlusEqual:
3410 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003411 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003412 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3413 break;
3414 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003415 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003416 return CheckIncRHS(CE->getArg(1));
3417 break;
3418 default:
3419 break;
3420 }
3421 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003422 if (Dependent() || SemaRef.CurContext->isDependentContext())
3423 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003424 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003425 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003426 return true;
3427}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003428
Alexey Bataev5a3af132016-03-29 08:58:54 +00003429static ExprResult
3430tryBuildCapture(Sema &SemaRef, Expr *Capture,
3431 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003432 if (SemaRef.CurContext->isDependentContext())
3433 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003434 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3435 return SemaRef.PerformImplicitConversion(
3436 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3437 /*AllowExplicit=*/true);
3438 auto I = Captures.find(Capture);
3439 if (I != Captures.end())
3440 return buildCapture(SemaRef, Capture, I->second);
3441 DeclRefExpr *Ref = nullptr;
3442 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3443 Captures[Capture] = Ref;
3444 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003445}
3446
Alexander Musmana5f070a2014-10-01 06:03:56 +00003447/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003448Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3449 Scope *S, const bool LimitedType,
3450 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003451 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003452 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003453 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003454 SemaRef.getLangOpts().CPlusPlus) {
3455 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003456 auto *UBExpr = TestIsLessOp ? UB : LB;
3457 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003458 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3459 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003460 if (!Upper || !Lower)
3461 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003462
3463 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3464
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003465 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003466 // BuildBinOp already emitted error, this one is to point user to upper
3467 // and lower bound, and to tell what is passed to 'operator-'.
3468 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3469 << Upper->getSourceRange() << Lower->getSourceRange();
3470 return nullptr;
3471 }
3472 }
3473
3474 if (!Diff.isUsable())
3475 return nullptr;
3476
3477 // Upper - Lower [- 1]
3478 if (TestIsStrictOp)
3479 Diff = SemaRef.BuildBinOp(
3480 S, DefaultLoc, BO_Sub, Diff.get(),
3481 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3482 if (!Diff.isUsable())
3483 return nullptr;
3484
3485 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003486 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3487 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003488 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003489 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003490 if (!Diff.isUsable())
3491 return nullptr;
3492
3493 // Parentheses (for dumping/debugging purposes only).
3494 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3495 if (!Diff.isUsable())
3496 return nullptr;
3497
3498 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003499 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003500 if (!Diff.isUsable())
3501 return nullptr;
3502
Alexander Musman174b3ca2014-10-06 11:16:29 +00003503 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003504 QualType Type = Diff.get()->getType();
3505 auto &C = SemaRef.Context;
3506 bool UseVarType = VarType->hasIntegerRepresentation() &&
3507 C.getTypeSize(Type) > C.getTypeSize(VarType);
3508 if (!Type->isIntegerType() || UseVarType) {
3509 unsigned NewSize =
3510 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3511 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3512 : Type->hasSignedIntegerRepresentation();
3513 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003514 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3515 Diff = SemaRef.PerformImplicitConversion(
3516 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3517 if (!Diff.isUsable())
3518 return nullptr;
3519 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003520 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003521 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003522 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3523 if (NewSize != C.getTypeSize(Type)) {
3524 if (NewSize < C.getTypeSize(Type)) {
3525 assert(NewSize == 64 && "incorrect loop var size");
3526 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3527 << InitSrcRange << ConditionSrcRange;
3528 }
3529 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003530 NewSize, Type->hasSignedIntegerRepresentation() ||
3531 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003532 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3533 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3534 Sema::AA_Converting, true);
3535 if (!Diff.isUsable())
3536 return nullptr;
3537 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003538 }
3539 }
3540
Alexander Musmana5f070a2014-10-01 06:03:56 +00003541 return Diff.get();
3542}
3543
Alexey Bataev5a3af132016-03-29 08:58:54 +00003544Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3545 Scope *S, Expr *Cond,
3546 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003547 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3548 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3549 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003550
Alexey Bataev5a3af132016-03-29 08:58:54 +00003551 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3552 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3553 if (!NewLB.isUsable() || !NewUB.isUsable())
3554 return nullptr;
3555
Alexey Bataev62dbb972015-04-22 11:59:37 +00003556 auto CondExpr = SemaRef.BuildBinOp(
3557 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3558 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003559 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003560 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003561 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3562 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003563 CondExpr = SemaRef.PerformImplicitConversion(
3564 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3565 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003566 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003567 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3568 // Otherwise use original loop conditon and evaluate it in runtime.
3569 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3570}
3571
Alexander Musmana5f070a2014-10-01 06:03:56 +00003572/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003573DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003574 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003575 auto *VD = dyn_cast<VarDecl>(LCDecl);
3576 if (!VD) {
3577 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3578 auto *Ref = buildDeclRefExpr(
3579 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003580 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3581 // If the loop control decl is explicitly marked as private, do not mark it
3582 // as captured again.
3583 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3584 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003585 return Ref;
3586 }
3587 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003588 DefaultLoc);
3589}
3590
3591Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003592 if (LCDecl && !LCDecl->isInvalidDecl()) {
3593 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003594 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003595 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3596 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003597 if (PrivateVar->isInvalidDecl())
3598 return nullptr;
3599 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3600 }
3601 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003602}
3603
Samuel Antao4c8035b2016-12-12 18:00:20 +00003604/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003605Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3606
3607/// \brief Build step of the counter be used for codegen.
3608Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3609
3610/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003611struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003612 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003613 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003614 /// \brief This expression calculates the number of iterations in the loop.
3615 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003616 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003617 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003618 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003619 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003620 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003621 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003622 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003623 /// \brief This is step for the #CounterVar used to generate its update:
3624 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003625 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003626 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003627 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003628 /// \brief Source range of the loop init.
3629 SourceRange InitSrcRange;
3630 /// \brief Source range of the loop condition.
3631 SourceRange CondSrcRange;
3632 /// \brief Source range of the loop increment.
3633 SourceRange IncSrcRange;
3634};
3635
Alexey Bataev23b69422014-06-18 07:08:49 +00003636} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003637
Alexey Bataev9c821032015-04-30 04:23:23 +00003638void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3639 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3640 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003641 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3642 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003643 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3644 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003645 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3646 if (auto *D = ISC.GetLoopDecl()) {
3647 auto *VD = dyn_cast<VarDecl>(D);
3648 if (!VD) {
3649 if (auto *Private = IsOpenMPCapturedDecl(D))
3650 VD = Private;
3651 else {
3652 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3653 /*WithInit=*/false);
3654 VD = cast<VarDecl>(Ref->getDecl());
3655 }
3656 }
3657 DSAStack->addLoopControlVariable(D, VD);
3658 }
3659 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003660 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003661 }
3662}
3663
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003664/// \brief Called on a for stmt to check and extract its iteration space
3665/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003666static bool CheckOpenMPIterationSpace(
3667 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3668 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003669 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003670 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003671 LoopIterationSpace &ResultIterSpace,
3672 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003673 // OpenMP [2.6, Canonical Loop Form]
3674 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003675 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003676 if (!For) {
3677 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003678 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3679 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3680 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3681 if (NestedLoopCount > 1) {
3682 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3683 SemaRef.Diag(DSA.getConstructLoc(),
3684 diag::note_omp_collapse_ordered_expr)
3685 << 2 << CollapseLoopCountExpr->getSourceRange()
3686 << OrderedLoopCountExpr->getSourceRange();
3687 else if (CollapseLoopCountExpr)
3688 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3689 diag::note_omp_collapse_ordered_expr)
3690 << 0 << CollapseLoopCountExpr->getSourceRange();
3691 else
3692 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3693 diag::note_omp_collapse_ordered_expr)
3694 << 1 << OrderedLoopCountExpr->getSourceRange();
3695 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003696 return true;
3697 }
3698 assert(For->getBody());
3699
3700 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3701
3702 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003703 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003704 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003705 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706
3707 bool HasErrors = false;
3708
3709 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003710 if (auto *LCDecl = ISC.GetLoopDecl()) {
3711 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003712
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003713 // OpenMP [2.6, Canonical Loop Form]
3714 // Var is one of the following:
3715 // A variable of signed or unsigned integer type.
3716 // For C++, a variable of a random access iterator type.
3717 // For C, a variable of a pointer type.
3718 auto VarType = LCDecl->getType().getNonReferenceType();
3719 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3720 !VarType->isPointerType() &&
3721 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3722 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3723 << SemaRef.getLangOpts().CPlusPlus;
3724 HasErrors = true;
3725 }
3726
3727 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3728 // a Construct
3729 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3730 // parallel for construct is (are) private.
3731 // The loop iteration variable in the associated for-loop of a simd
3732 // construct with just one associated for-loop is linear with a
3733 // constant-linear-step that is the increment of the associated for-loop.
3734 // Exclude loop var from the list of variables with implicitly defined data
3735 // sharing attributes.
3736 VarsWithImplicitDSA.erase(LCDecl);
3737
3738 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3739 // in a Construct, C/C++].
3740 // The loop iteration variable in the associated for-loop of a simd
3741 // construct with just one associated for-loop may be listed in a linear
3742 // clause with a constant-linear-step that is the increment of the
3743 // associated for-loop.
3744 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3745 // parallel for construct may be listed in a private or lastprivate clause.
3746 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3747 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3748 // declared in the loop and it is predetermined as a private.
3749 auto PredeterminedCKind =
3750 isOpenMPSimdDirective(DKind)
3751 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3752 : OMPC_private;
3753 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3754 DVar.CKind != PredeterminedCKind) ||
3755 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3756 isOpenMPDistributeDirective(DKind)) &&
3757 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3758 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3759 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3760 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3761 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3762 << getOpenMPClauseName(PredeterminedCKind);
3763 if (DVar.RefExpr == nullptr)
3764 DVar.CKind = PredeterminedCKind;
3765 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3766 HasErrors = true;
3767 } else if (LoopDeclRefExpr != nullptr) {
3768 // Make the loop iteration variable private (for worksharing constructs),
3769 // linear (for simd directives with the only one associated loop) or
3770 // lastprivate (for simd directives with several collapsed or ordered
3771 // loops).
3772 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003773 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3774 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003775 /*FromParent=*/false);
3776 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3777 }
3778
3779 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3780
3781 // Check test-expr.
3782 HasErrors |= ISC.CheckCond(For->getCond());
3783
3784 // Check incr-expr.
3785 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003786 }
3787
Alexander Musmana5f070a2014-10-01 06:03:56 +00003788 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003789 return HasErrors;
3790
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003792 ResultIterSpace.PreCond =
3793 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003794 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003795 DSA.getCurScope(),
3796 (isOpenMPWorksharingDirective(DKind) ||
3797 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3798 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003799 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003800 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003801 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3802 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3803 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3804 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3805 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3806 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3807
Alexey Bataev62dbb972015-04-22 11:59:37 +00003808 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3809 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003810 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003811 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003812 ResultIterSpace.CounterInit == nullptr ||
3813 ResultIterSpace.CounterStep == nullptr);
3814
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003815 return HasErrors;
3816}
3817
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003818/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003819static ExprResult
3820BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3821 ExprResult Start,
3822 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003823 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003824 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3825 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003826 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003827 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003828 VarRef.get()->getType())) {
3829 NewStart = SemaRef.PerformImplicitConversion(
3830 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3831 /*AllowExplicit=*/true);
3832 if (!NewStart.isUsable())
3833 return ExprError();
3834 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003835
3836 auto Init =
3837 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3838 return Init;
3839}
3840
Alexander Musmana5f070a2014-10-01 06:03:56 +00003841/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003842static ExprResult
3843BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3844 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3845 ExprResult Step, bool Subtract,
3846 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003847 // Add parentheses (for debugging purposes only).
3848 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3849 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3850 !Step.isUsable())
3851 return ExprError();
3852
Alexey Bataev5a3af132016-03-29 08:58:54 +00003853 ExprResult NewStep = Step;
3854 if (Captures)
3855 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003856 if (NewStep.isInvalid())
3857 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003858 ExprResult Update =
3859 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003860 if (!Update.isUsable())
3861 return ExprError();
3862
Alexey Bataevc0214e02016-02-16 12:13:49 +00003863 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3864 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003865 ExprResult NewStart = Start;
3866 if (Captures)
3867 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003868 if (NewStart.isInvalid())
3869 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003870
Alexey Bataevc0214e02016-02-16 12:13:49 +00003871 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3872 ExprResult SavedUpdate = Update;
3873 ExprResult UpdateVal;
3874 if (VarRef.get()->getType()->isOverloadableType() ||
3875 NewStart.get()->getType()->isOverloadableType() ||
3876 Update.get()->getType()->isOverloadableType()) {
3877 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3878 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3879 Update =
3880 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3881 if (Update.isUsable()) {
3882 UpdateVal =
3883 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3884 VarRef.get(), SavedUpdate.get());
3885 if (UpdateVal.isUsable()) {
3886 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3887 UpdateVal.get());
3888 }
3889 }
3890 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3891 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892
Alexey Bataevc0214e02016-02-16 12:13:49 +00003893 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3894 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3895 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3896 NewStart.get(), SavedUpdate.get());
3897 if (!Update.isUsable())
3898 return ExprError();
3899
Alexey Bataev11481f52016-02-17 10:29:05 +00003900 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3901 VarRef.get()->getType())) {
3902 Update = SemaRef.PerformImplicitConversion(
3903 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3904 if (!Update.isUsable())
3905 return ExprError();
3906 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003907
3908 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3909 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003910 return Update;
3911}
3912
3913/// \brief Convert integer expression \a E to make it have at least \a Bits
3914/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003915static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003916 if (E == nullptr)
3917 return ExprError();
3918 auto &C = SemaRef.Context;
3919 QualType OldType = E->getType();
3920 unsigned HasBits = C.getTypeSize(OldType);
3921 if (HasBits >= Bits)
3922 return ExprResult(E);
3923 // OK to convert to signed, because new type has more bits than old.
3924 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3925 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3926 true);
3927}
3928
3929/// \brief Check if the given expression \a E is a constant integer that fits
3930/// into \a Bits bits.
3931static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3932 if (E == nullptr)
3933 return false;
3934 llvm::APSInt Result;
3935 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3936 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3937 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003938}
3939
Alexey Bataev5a3af132016-03-29 08:58:54 +00003940/// Build preinits statement for the given declarations.
3941static Stmt *buildPreInits(ASTContext &Context,
3942 SmallVectorImpl<Decl *> &PreInits) {
3943 if (!PreInits.empty()) {
3944 return new (Context) DeclStmt(
3945 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3946 SourceLocation(), SourceLocation());
3947 }
3948 return nullptr;
3949}
3950
3951/// Build preinits statement for the given declarations.
3952static Stmt *buildPreInits(ASTContext &Context,
3953 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3954 if (!Captures.empty()) {
3955 SmallVector<Decl *, 16> PreInits;
3956 for (auto &Pair : Captures)
3957 PreInits.push_back(Pair.second->getDecl());
3958 return buildPreInits(Context, PreInits);
3959 }
3960 return nullptr;
3961}
3962
3963/// Build postupdate expression for the given list of postupdates expressions.
3964static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3965 Expr *PostUpdate = nullptr;
3966 if (!PostUpdates.empty()) {
3967 for (auto *E : PostUpdates) {
3968 Expr *ConvE = S.BuildCStyleCastExpr(
3969 E->getExprLoc(),
3970 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3971 E->getExprLoc(), E)
3972 .get();
3973 PostUpdate = PostUpdate
3974 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3975 PostUpdate, ConvE)
3976 .get()
3977 : ConvE;
3978 }
3979 }
3980 return PostUpdate;
3981}
3982
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003983/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003984/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3985/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003986static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003987CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3988 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3989 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003990 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003991 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003992 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003993 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003994 // Found 'collapse' clause - calculate collapse number.
3995 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003996 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003997 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003998 }
3999 if (OrderedLoopCountExpr) {
4000 // Found 'ordered' clause - calculate collapse number.
4001 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004002 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4003 if (Result.getLimitedValue() < NestedLoopCount) {
4004 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4005 diag::err_omp_wrong_ordered_loop_count)
4006 << OrderedLoopCountExpr->getSourceRange();
4007 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4008 diag::note_collapse_loop_count)
4009 << CollapseLoopCountExpr->getSourceRange();
4010 }
4011 NestedLoopCount = Result.getLimitedValue();
4012 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004013 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004014 // This is helper routine for loop directives (e.g., 'for', 'simd',
4015 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004016 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004017 SmallVector<LoopIterationSpace, 4> IterSpaces;
4018 IterSpaces.resize(NestedLoopCount);
4019 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004020 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004021 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004022 NestedLoopCount, CollapseLoopCountExpr,
4023 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004024 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004025 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004026 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004027 // OpenMP [2.8.1, simd construct, Restrictions]
4028 // All loops associated with the construct must be perfectly nested; that
4029 // is, there must be no intervening code nor any OpenMP directive between
4030 // any two loops.
4031 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004032 }
4033
Alexander Musmana5f070a2014-10-01 06:03:56 +00004034 Built.clear(/* size */ NestedLoopCount);
4035
4036 if (SemaRef.CurContext->isDependentContext())
4037 return NestedLoopCount;
4038
4039 // An example of what is generated for the following code:
4040 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004041 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004042 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004043 // for (k = 0; k < NK; ++k)
4044 // for (j = J0; j < NJ; j+=2) {
4045 // <loop body>
4046 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004047 //
4048 // We generate the code below.
4049 // Note: the loop body may be outlined in CodeGen.
4050 // Note: some counters may be C++ classes, operator- is used to find number of
4051 // iterations and operator+= to calculate counter value.
4052 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4053 // or i64 is currently supported).
4054 //
4055 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4056 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4057 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4058 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4059 // // similar updates for vars in clauses (e.g. 'linear')
4060 // <loop body (using local i and j)>
4061 // }
4062 // i = NI; // assign final values of counters
4063 // j = NJ;
4064 //
4065
4066 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4067 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004068 // Precondition tests if there is at least one iteration (all conditions are
4069 // true).
4070 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004071 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004072 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004073 32 /* Bits */, SemaRef
4074 .PerformImplicitConversion(
4075 N0->IgnoreImpCasts(), N0->getType(),
4076 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004077 .get(),
4078 SemaRef);
4079 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004080 64 /* Bits */, SemaRef
4081 .PerformImplicitConversion(
4082 N0->IgnoreImpCasts(), N0->getType(),
4083 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004084 .get(),
4085 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004086
4087 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4088 return NestedLoopCount;
4089
4090 auto &C = SemaRef.Context;
4091 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4092
4093 Scope *CurScope = DSA.getCurScope();
4094 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004095 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004096 PreCond =
4097 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4098 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004099 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004100 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004101 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004102 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4103 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004104 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004105 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004106 SemaRef
4107 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4108 Sema::AA_Converting,
4109 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004110 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004111 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004112 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004113 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004114 SemaRef
4115 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4116 Sema::AA_Converting,
4117 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004118 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004119 }
4120
4121 // Choose either the 32-bit or 64-bit version.
4122 ExprResult LastIteration = LastIteration64;
4123 if (LastIteration32.isUsable() &&
4124 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4125 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4126 FitsInto(
4127 32 /* Bits */,
4128 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4129 LastIteration64.get(), SemaRef)))
4130 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004131 QualType VType = LastIteration.get()->getType();
4132 QualType RealVType = VType;
4133 QualType StrideVType = VType;
4134 if (isOpenMPTaskLoopDirective(DKind)) {
4135 VType =
4136 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4137 StrideVType =
4138 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4139 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004140
4141 if (!LastIteration.isUsable())
4142 return 0;
4143
4144 // Save the number of iterations.
4145 ExprResult NumIterations = LastIteration;
4146 {
4147 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004148 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4149 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004150 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4151 if (!LastIteration.isUsable())
4152 return 0;
4153 }
4154
4155 // Calculate the last iteration number beforehand instead of doing this on
4156 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4157 llvm::APSInt Result;
4158 bool IsConstant =
4159 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4160 ExprResult CalcLastIteration;
4161 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004162 ExprResult SaveRef =
4163 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004164 LastIteration = SaveRef;
4165
4166 // Prepare SaveRef + 1.
4167 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004168 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004169 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4170 if (!NumIterations.isUsable())
4171 return 0;
4172 }
4173
4174 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4175
David Majnemer9d168222016-08-05 17:44:54 +00004176 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004177 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004178 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4179 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004180 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004181 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4182 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004183 SemaRef.AddInitializerToDecl(LBDecl,
4184 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4185 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004186
4187 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004188 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4189 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004190 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004191 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004192
4193 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4194 // This will be used to implement clause 'lastprivate'.
4195 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004196 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4197 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004198 SemaRef.AddInitializerToDecl(ILDecl,
4199 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4200 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004201
4202 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004203 VarDecl *STDecl =
4204 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4205 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004206 SemaRef.AddInitializerToDecl(STDecl,
4207 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4208 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004209
4210 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004211 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004212 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4213 UB.get(), LastIteration.get());
4214 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4215 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4216 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4217 CondOp.get());
4218 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004219
4220 // If we have a combined directive that combines 'distribute', 'for' or
4221 // 'simd' we need to be able to access the bounds of the schedule of the
4222 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4223 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4224 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004225
Carlo Bertolliffafe102017-04-20 00:39:39 +00004226 // Lower bound variable, initialized with zero.
4227 VarDecl *CombLBDecl =
4228 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4229 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4230 SemaRef.AddInitializerToDecl(
4231 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4232 /*DirectInit*/ false);
4233
4234 // Upper bound variable, initialized with last iteration number.
4235 VarDecl *CombUBDecl =
4236 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4237 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4238 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4239 /*DirectInit*/ false);
4240
4241 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4242 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4243 ExprResult CombCondOp =
4244 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4245 LastIteration.get(), CombUB.get());
4246 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4247 CombCondOp.get());
4248 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4249
4250 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004251 // We expect to have at least 2 more parameters than the 'parallel'
4252 // directive does - the lower and upper bounds of the previous schedule.
4253 assert(CD->getNumParams() >= 4 &&
4254 "Unexpected number of parameters in loop combined directive");
4255
4256 // Set the proper type for the bounds given what we learned from the
4257 // enclosed loops.
4258 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4259 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4260
4261 // Previous lower and upper bounds are obtained from the region
4262 // parameters.
4263 PrevLB =
4264 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4265 PrevUB =
4266 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4267 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004268 }
4269
4270 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004271 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004272 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004273 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004274 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4275 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004276 Expr *RHS =
4277 (isOpenMPWorksharingDirective(DKind) ||
4278 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4279 ? LB.get()
4280 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004281 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4282 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004283
4284 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4285 Expr *CombRHS =
4286 (isOpenMPWorksharingDirective(DKind) ||
4287 isOpenMPTaskLoopDirective(DKind) ||
4288 isOpenMPDistributeDirective(DKind))
4289 ? CombLB.get()
4290 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4291 CombInit =
4292 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4293 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4294 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004295 }
4296
Alexander Musmanc6388682014-12-15 07:07:06 +00004297 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004298 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004299 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004300 (isOpenMPWorksharingDirective(DKind) ||
4301 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004302 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4303 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4304 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004305 ExprResult CombCond;
4306 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4307 CombCond =
4308 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4309 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004310 // Loop increment (IV = IV + 1)
4311 SourceLocation IncLoc;
4312 ExprResult Inc =
4313 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4314 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4315 if (!Inc.isUsable())
4316 return 0;
4317 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004318 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4319 if (!Inc.isUsable())
4320 return 0;
4321
4322 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4323 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004324 // In combined construct, add combined version that use CombLB and CombUB
4325 // base variables for the update
4326 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004327 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4328 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004329 // LB + ST
4330 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4331 if (!NextLB.isUsable())
4332 return 0;
4333 // LB = LB + ST
4334 NextLB =
4335 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4336 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4337 if (!NextLB.isUsable())
4338 return 0;
4339 // UB + ST
4340 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4341 if (!NextUB.isUsable())
4342 return 0;
4343 // UB = UB + ST
4344 NextUB =
4345 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4346 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4347 if (!NextUB.isUsable())
4348 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004349 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4350 CombNextLB =
4351 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4352 if (!NextLB.isUsable())
4353 return 0;
4354 // LB = LB + ST
4355 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4356 CombNextLB.get());
4357 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4358 if (!CombNextLB.isUsable())
4359 return 0;
4360 // UB + ST
4361 CombNextUB =
4362 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4363 if (!CombNextUB.isUsable())
4364 return 0;
4365 // UB = UB + ST
4366 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4367 CombNextUB.get());
4368 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4369 if (!CombNextUB.isUsable())
4370 return 0;
4371 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004372 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004373
Carlo Bertolliffafe102017-04-20 00:39:39 +00004374 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004375 // directive with for as IV = IV + ST; ensure upper bound expression based
4376 // on PrevUB instead of NumIterations - used to implement 'for' when found
4377 // in combination with 'distribute', like in 'distribute parallel for'
4378 SourceLocation DistIncLoc;
4379 ExprResult DistCond, DistInc, PrevEUB;
4380 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4381 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4382 assert(DistCond.isUsable() && "distribute cond expr was not built");
4383
4384 DistInc =
4385 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4386 assert(DistInc.isUsable() && "distribute inc expr was not built");
4387 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4388 DistInc.get());
4389 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4390 assert(DistInc.isUsable() && "distribute inc expr was not built");
4391
4392 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4393 // construct
4394 SourceLocation DistEUBLoc;
4395 ExprResult IsUBGreater =
4396 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4397 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4398 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4399 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4400 CondOp.get());
4401 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4402 }
4403
Alexander Musmana5f070a2014-10-01 06:03:56 +00004404 // Build updates and final values of the loop counters.
4405 bool HasErrors = false;
4406 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004407 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004408 Built.Updates.resize(NestedLoopCount);
4409 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004410 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004411 {
4412 ExprResult Div;
4413 // Go from inner nested loop to outer.
4414 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4415 LoopIterationSpace &IS = IterSpaces[Cnt];
4416 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4417 // Build: Iter = (IV / Div) % IS.NumIters
4418 // where Div is product of previous iterations' IS.NumIters.
4419 ExprResult Iter;
4420 if (Div.isUsable()) {
4421 Iter =
4422 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4423 } else {
4424 Iter = IV;
4425 assert((Cnt == (int)NestedLoopCount - 1) &&
4426 "unusable div expected on first iteration only");
4427 }
4428
4429 if (Cnt != 0 && Iter.isUsable())
4430 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4431 IS.NumIterations);
4432 if (!Iter.isUsable()) {
4433 HasErrors = true;
4434 break;
4435 }
4436
Alexey Bataev39f915b82015-05-08 10:41:21 +00004437 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004438 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4439 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4440 IS.CounterVar->getExprLoc(),
4441 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004442 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004443 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004444 if (!Init.isUsable()) {
4445 HasErrors = true;
4446 break;
4447 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004448 ExprResult Update = BuildCounterUpdate(
4449 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4450 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004451 if (!Update.isUsable()) {
4452 HasErrors = true;
4453 break;
4454 }
4455
4456 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4457 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004458 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004459 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004460 if (!Final.isUsable()) {
4461 HasErrors = true;
4462 break;
4463 }
4464
4465 // Build Div for the next iteration: Div <- Div * IS.NumIters
4466 if (Cnt != 0) {
4467 if (Div.isUnset())
4468 Div = IS.NumIterations;
4469 else
4470 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4471 IS.NumIterations);
4472
4473 // Add parentheses (for debugging purposes only).
4474 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004475 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004476 if (!Div.isUsable()) {
4477 HasErrors = true;
4478 break;
4479 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004480 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004481 }
4482 if (!Update.isUsable() || !Final.isUsable()) {
4483 HasErrors = true;
4484 break;
4485 }
4486 // Save results
4487 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004488 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004489 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004490 Built.Updates[Cnt] = Update.get();
4491 Built.Finals[Cnt] = Final.get();
4492 }
4493 }
4494
4495 if (HasErrors)
4496 return 0;
4497
4498 // Save results
4499 Built.IterationVarRef = IV.get();
4500 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004501 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004502 Built.CalcLastIteration =
4503 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004504 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004505 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004506 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004507 Built.Init = Init.get();
4508 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004509 Built.LB = LB.get();
4510 Built.UB = UB.get();
4511 Built.IL = IL.get();
4512 Built.ST = ST.get();
4513 Built.EUB = EUB.get();
4514 Built.NLB = NextLB.get();
4515 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004516 Built.PrevLB = PrevLB.get();
4517 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004518 Built.DistInc = DistInc.get();
4519 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004520 Built.DistCombinedFields.LB = CombLB.get();
4521 Built.DistCombinedFields.UB = CombUB.get();
4522 Built.DistCombinedFields.EUB = CombEUB.get();
4523 Built.DistCombinedFields.Init = CombInit.get();
4524 Built.DistCombinedFields.Cond = CombCond.get();
4525 Built.DistCombinedFields.NLB = CombNextLB.get();
4526 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004527
Alexey Bataev8b427062016-05-25 12:36:08 +00004528 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4529 // Fill data for doacross depend clauses.
4530 for (auto Pair : DSA.getDoacrossDependClauses()) {
4531 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4532 Pair.first->setCounterValue(CounterVal);
4533 else {
4534 if (NestedLoopCount != Pair.second.size() ||
4535 NestedLoopCount != LoopMultipliers.size() + 1) {
4536 // Erroneous case - clause has some problems.
4537 Pair.first->setCounterValue(CounterVal);
4538 continue;
4539 }
4540 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4541 auto I = Pair.second.rbegin();
4542 auto IS = IterSpaces.rbegin();
4543 auto ILM = LoopMultipliers.rbegin();
4544 Expr *UpCounterVal = CounterVal;
4545 Expr *Multiplier = nullptr;
4546 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4547 if (I->first) {
4548 assert(IS->CounterStep);
4549 Expr *NormalizedOffset =
4550 SemaRef
4551 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4552 I->first, IS->CounterStep)
4553 .get();
4554 if (Multiplier) {
4555 NormalizedOffset =
4556 SemaRef
4557 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4558 NormalizedOffset, Multiplier)
4559 .get();
4560 }
4561 assert(I->second == OO_Plus || I->second == OO_Minus);
4562 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004563 UpCounterVal = SemaRef
4564 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4565 UpCounterVal, NormalizedOffset)
4566 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004567 }
4568 Multiplier = *ILM;
4569 ++I;
4570 ++IS;
4571 ++ILM;
4572 }
4573 Pair.first->setCounterValue(UpCounterVal);
4574 }
4575 }
4576
Alexey Bataevabfc0692014-06-25 06:52:00 +00004577 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004578}
4579
Alexey Bataev10e775f2015-07-30 11:36:16 +00004580static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004581 auto CollapseClauses =
4582 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4583 if (CollapseClauses.begin() != CollapseClauses.end())
4584 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004585 return nullptr;
4586}
4587
Alexey Bataev10e775f2015-07-30 11:36:16 +00004588static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004589 auto OrderedClauses =
4590 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4591 if (OrderedClauses.begin() != OrderedClauses.end())
4592 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004593 return nullptr;
4594}
4595
Kelvin Lic5609492016-07-15 04:39:07 +00004596static bool checkSimdlenSafelenSpecified(Sema &S,
4597 const ArrayRef<OMPClause *> Clauses) {
4598 OMPSafelenClause *Safelen = nullptr;
4599 OMPSimdlenClause *Simdlen = nullptr;
4600
4601 for (auto *Clause : Clauses) {
4602 if (Clause->getClauseKind() == OMPC_safelen)
4603 Safelen = cast<OMPSafelenClause>(Clause);
4604 else if (Clause->getClauseKind() == OMPC_simdlen)
4605 Simdlen = cast<OMPSimdlenClause>(Clause);
4606 if (Safelen && Simdlen)
4607 break;
4608 }
4609
4610 if (Simdlen && Safelen) {
4611 llvm::APSInt SimdlenRes, SafelenRes;
4612 auto SimdlenLength = Simdlen->getSimdlen();
4613 auto SafelenLength = Safelen->getSafelen();
4614 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4615 SimdlenLength->isInstantiationDependent() ||
4616 SimdlenLength->containsUnexpandedParameterPack())
4617 return false;
4618 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4619 SafelenLength->isInstantiationDependent() ||
4620 SafelenLength->containsUnexpandedParameterPack())
4621 return false;
4622 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4623 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4624 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4625 // If both simdlen and safelen clauses are specified, the value of the
4626 // simdlen parameter must be less than or equal to the value of the safelen
4627 // parameter.
4628 if (SimdlenRes > SafelenRes) {
4629 S.Diag(SimdlenLength->getExprLoc(),
4630 diag::err_omp_wrong_simdlen_safelen_values)
4631 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4632 return true;
4633 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004634 }
4635 return false;
4636}
4637
Alexey Bataev4acb8592014-07-07 13:01:15 +00004638StmtResult Sema::ActOnOpenMPSimdDirective(
4639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4640 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004641 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004642 if (!AStmt)
4643 return StmtError();
4644
4645 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004646 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004647 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4648 // define the nested loops number.
4649 unsigned NestedLoopCount = CheckOpenMPLoop(
4650 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4651 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004652 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004653 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004654
Alexander Musmana5f070a2014-10-01 06:03:56 +00004655 assert((CurContext->isDependentContext() || B.builtAll()) &&
4656 "omp simd loop exprs were not built");
4657
Alexander Musman3276a272015-03-21 10:12:56 +00004658 if (!CurContext->isDependentContext()) {
4659 // Finalize the clauses that need pre-built expressions for CodeGen.
4660 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004661 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004662 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004663 B.NumIterations, *this, CurScope,
4664 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004665 return StmtError();
4666 }
4667 }
4668
Kelvin Lic5609492016-07-15 04:39:07 +00004669 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004670 return StmtError();
4671
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004672 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004673 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4674 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004675}
4676
Alexey Bataev4acb8592014-07-07 13:01:15 +00004677StmtResult Sema::ActOnOpenMPForDirective(
4678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4679 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004681 if (!AStmt)
4682 return StmtError();
4683
4684 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004685 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004686 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4687 // define the nested loops number.
4688 unsigned NestedLoopCount = CheckOpenMPLoop(
4689 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4690 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004691 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004692 return StmtError();
4693
Alexander Musmana5f070a2014-10-01 06:03:56 +00004694 assert((CurContext->isDependentContext() || B.builtAll()) &&
4695 "omp for loop exprs were not built");
4696
Alexey Bataev54acd402015-08-04 11:18:19 +00004697 if (!CurContext->isDependentContext()) {
4698 // Finalize the clauses that need pre-built expressions for CodeGen.
4699 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004700 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004701 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004702 B.NumIterations, *this, CurScope,
4703 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004704 return StmtError();
4705 }
4706 }
4707
Alexey Bataevf29276e2014-06-18 04:14:57 +00004708 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004709 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004710 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004711}
4712
Alexander Musmanf82886e2014-09-18 05:12:34 +00004713StmtResult Sema::ActOnOpenMPForSimdDirective(
4714 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4715 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004716 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004717 if (!AStmt)
4718 return StmtError();
4719
4720 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004721 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004722 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4723 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004724 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004725 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4726 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4727 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004728 if (NestedLoopCount == 0)
4729 return StmtError();
4730
Alexander Musmanc6388682014-12-15 07:07:06 +00004731 assert((CurContext->isDependentContext() || B.builtAll()) &&
4732 "omp for simd loop exprs were not built");
4733
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004734 if (!CurContext->isDependentContext()) {
4735 // Finalize the clauses that need pre-built expressions for CodeGen.
4736 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004737 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004738 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004739 B.NumIterations, *this, CurScope,
4740 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004741 return StmtError();
4742 }
4743 }
4744
Kelvin Lic5609492016-07-15 04:39:07 +00004745 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004746 return StmtError();
4747
Alexander Musmanf82886e2014-09-18 05:12:34 +00004748 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004749 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4750 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004751}
4752
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004753StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4754 Stmt *AStmt,
4755 SourceLocation StartLoc,
4756 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004757 if (!AStmt)
4758 return StmtError();
4759
4760 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004761 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004762 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004763 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004764 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004765 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004766 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004767 return StmtError();
4768 // All associated statements must be '#pragma omp section' except for
4769 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004770 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004771 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4772 if (SectionStmt)
4773 Diag(SectionStmt->getLocStart(),
4774 diag::err_omp_sections_substmt_not_section);
4775 return StmtError();
4776 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004777 cast<OMPSectionDirective>(SectionStmt)
4778 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004779 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004780 } else {
4781 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4782 return StmtError();
4783 }
4784
4785 getCurFunction()->setHasBranchProtectedScope();
4786
Alexey Bataev25e5b442015-09-15 12:52:43 +00004787 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4788 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004789}
4790
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004791StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4792 SourceLocation StartLoc,
4793 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004794 if (!AStmt)
4795 return StmtError();
4796
4797 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004798
4799 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004800 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004801
Alexey Bataev25e5b442015-09-15 12:52:43 +00004802 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4803 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004804}
4805
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004806StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4807 Stmt *AStmt,
4808 SourceLocation StartLoc,
4809 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004810 if (!AStmt)
4811 return StmtError();
4812
4813 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004814
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004815 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004816
Alexey Bataev3255bf32015-01-19 05:20:46 +00004817 // OpenMP [2.7.3, single Construct, Restrictions]
4818 // The copyprivate clause must not be used with the nowait clause.
4819 OMPClause *Nowait = nullptr;
4820 OMPClause *Copyprivate = nullptr;
4821 for (auto *Clause : Clauses) {
4822 if (Clause->getClauseKind() == OMPC_nowait)
4823 Nowait = Clause;
4824 else if (Clause->getClauseKind() == OMPC_copyprivate)
4825 Copyprivate = Clause;
4826 if (Copyprivate && Nowait) {
4827 Diag(Copyprivate->getLocStart(),
4828 diag::err_omp_single_copyprivate_with_nowait);
4829 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4830 return StmtError();
4831 }
4832 }
4833
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004834 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4835}
4836
Alexander Musman80c22892014-07-17 08:54:58 +00004837StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4838 SourceLocation StartLoc,
4839 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004840 if (!AStmt)
4841 return StmtError();
4842
4843 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004844
4845 getCurFunction()->setHasBranchProtectedScope();
4846
4847 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4848}
4849
Alexey Bataev28c75412015-12-15 08:19:24 +00004850StmtResult Sema::ActOnOpenMPCriticalDirective(
4851 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4852 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004853 if (!AStmt)
4854 return StmtError();
4855
4856 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004857
Alexey Bataev28c75412015-12-15 08:19:24 +00004858 bool ErrorFound = false;
4859 llvm::APSInt Hint;
4860 SourceLocation HintLoc;
4861 bool DependentHint = false;
4862 for (auto *C : Clauses) {
4863 if (C->getClauseKind() == OMPC_hint) {
4864 if (!DirName.getName()) {
4865 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4866 ErrorFound = true;
4867 }
4868 Expr *E = cast<OMPHintClause>(C)->getHint();
4869 if (E->isTypeDependent() || E->isValueDependent() ||
4870 E->isInstantiationDependent())
4871 DependentHint = true;
4872 else {
4873 Hint = E->EvaluateKnownConstInt(Context);
4874 HintLoc = C->getLocStart();
4875 }
4876 }
4877 }
4878 if (ErrorFound)
4879 return StmtError();
4880 auto Pair = DSAStack->getCriticalWithHint(DirName);
4881 if (Pair.first && DirName.getName() && !DependentHint) {
4882 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4883 Diag(StartLoc, diag::err_omp_critical_with_hint);
4884 if (HintLoc.isValid()) {
4885 Diag(HintLoc, diag::note_omp_critical_hint_here)
4886 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4887 } else
4888 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4889 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4890 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4891 << 1
4892 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4893 /*Radix=*/10, /*Signed=*/false);
4894 } else
4895 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4896 }
4897 }
4898
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004899 getCurFunction()->setHasBranchProtectedScope();
4900
Alexey Bataev28c75412015-12-15 08:19:24 +00004901 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4902 Clauses, AStmt);
4903 if (!Pair.first && DirName.getName() && !DependentHint)
4904 DSAStack->addCriticalWithHint(Dir, Hint);
4905 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004906}
4907
Alexey Bataev4acb8592014-07-07 13:01:15 +00004908StmtResult Sema::ActOnOpenMPParallelForDirective(
4909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4910 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004911 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004912 if (!AStmt)
4913 return StmtError();
4914
Alexey Bataev4acb8592014-07-07 13:01:15 +00004915 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4916 // 1.2.2 OpenMP Language Terminology
4917 // Structured block - An executable statement with a single entry at the
4918 // top and a single exit at the bottom.
4919 // The point of exit cannot be a branch out of the structured block.
4920 // longjmp() and throw() must not violate the entry/exit criteria.
4921 CS->getCapturedDecl()->setNothrow();
4922
Alexander Musmanc6388682014-12-15 07:07:06 +00004923 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004924 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4925 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004926 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004927 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4928 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4929 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004930 if (NestedLoopCount == 0)
4931 return StmtError();
4932
Alexander Musmana5f070a2014-10-01 06:03:56 +00004933 assert((CurContext->isDependentContext() || B.builtAll()) &&
4934 "omp parallel for loop exprs were not built");
4935
Alexey Bataev54acd402015-08-04 11:18:19 +00004936 if (!CurContext->isDependentContext()) {
4937 // Finalize the clauses that need pre-built expressions for CodeGen.
4938 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004939 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004940 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004941 B.NumIterations, *this, CurScope,
4942 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004943 return StmtError();
4944 }
4945 }
4946
Alexey Bataev4acb8592014-07-07 13:01:15 +00004947 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004948 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004949 NestedLoopCount, Clauses, AStmt, B,
4950 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004951}
4952
Alexander Musmane4e893b2014-09-23 09:33:00 +00004953StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4954 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4955 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004956 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004957 if (!AStmt)
4958 return StmtError();
4959
Alexander Musmane4e893b2014-09-23 09:33:00 +00004960 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4961 // 1.2.2 OpenMP Language Terminology
4962 // Structured block - An executable statement with a single entry at the
4963 // top and a single exit at the bottom.
4964 // The point of exit cannot be a branch out of the structured block.
4965 // longjmp() and throw() must not violate the entry/exit criteria.
4966 CS->getCapturedDecl()->setNothrow();
4967
Alexander Musmanc6388682014-12-15 07:07:06 +00004968 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004969 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4970 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004971 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004972 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4973 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4974 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004975 if (NestedLoopCount == 0)
4976 return StmtError();
4977
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004978 if (!CurContext->isDependentContext()) {
4979 // Finalize the clauses that need pre-built expressions for CodeGen.
4980 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004981 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004982 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004983 B.NumIterations, *this, CurScope,
4984 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004985 return StmtError();
4986 }
4987 }
4988
Kelvin Lic5609492016-07-15 04:39:07 +00004989 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004990 return StmtError();
4991
Alexander Musmane4e893b2014-09-23 09:33:00 +00004992 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004993 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004994 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004995}
4996
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004997StmtResult
4998Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4999 Stmt *AStmt, SourceLocation StartLoc,
5000 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005001 if (!AStmt)
5002 return StmtError();
5003
5004 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005005 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005006 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005007 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005008 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005009 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005010 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005011 return StmtError();
5012 // All associated statements must be '#pragma omp section' except for
5013 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005014 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005015 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5016 if (SectionStmt)
5017 Diag(SectionStmt->getLocStart(),
5018 diag::err_omp_parallel_sections_substmt_not_section);
5019 return StmtError();
5020 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005021 cast<OMPSectionDirective>(SectionStmt)
5022 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005023 }
5024 } else {
5025 Diag(AStmt->getLocStart(),
5026 diag::err_omp_parallel_sections_not_compound_stmt);
5027 return StmtError();
5028 }
5029
5030 getCurFunction()->setHasBranchProtectedScope();
5031
Alexey Bataev25e5b442015-09-15 12:52:43 +00005032 return OMPParallelSectionsDirective::Create(
5033 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005034}
5035
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005036StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5037 Stmt *AStmt, SourceLocation StartLoc,
5038 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005039 if (!AStmt)
5040 return StmtError();
5041
David Majnemer9d168222016-08-05 17:44:54 +00005042 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005043 // 1.2.2 OpenMP Language Terminology
5044 // Structured block - An executable statement with a single entry at the
5045 // top and a single exit at the bottom.
5046 // The point of exit cannot be a branch out of the structured block.
5047 // longjmp() and throw() must not violate the entry/exit criteria.
5048 CS->getCapturedDecl()->setNothrow();
5049
5050 getCurFunction()->setHasBranchProtectedScope();
5051
Alexey Bataev25e5b442015-09-15 12:52:43 +00005052 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5053 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005054}
5055
Alexey Bataev68446b72014-07-18 07:47:19 +00005056StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5057 SourceLocation EndLoc) {
5058 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5059}
5060
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005061StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5062 SourceLocation EndLoc) {
5063 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5064}
5065
Alexey Bataev2df347a2014-07-18 10:17:07 +00005066StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5067 SourceLocation EndLoc) {
5068 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5069}
5070
Alexey Bataev169d96a2017-07-18 20:17:46 +00005071StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5072 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005073 SourceLocation StartLoc,
5074 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005075 if (!AStmt)
5076 return StmtError();
5077
5078 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005079
5080 getCurFunction()->setHasBranchProtectedScope();
5081
Alexey Bataev169d96a2017-07-18 20:17:46 +00005082 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5083 AStmt);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005084}
5085
Alexey Bataev6125da92014-07-21 11:26:11 +00005086StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5087 SourceLocation StartLoc,
5088 SourceLocation EndLoc) {
5089 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5090 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5091}
5092
Alexey Bataev346265e2015-09-25 10:37:12 +00005093StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5094 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005095 SourceLocation StartLoc,
5096 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005097 OMPClause *DependFound = nullptr;
5098 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005099 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005100 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005101 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005102 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005103 for (auto *C : Clauses) {
5104 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5105 DependFound = C;
5106 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5107 if (DependSourceClause) {
5108 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5109 << getOpenMPDirectiveName(OMPD_ordered)
5110 << getOpenMPClauseName(OMPC_depend) << 2;
5111 ErrorFound = true;
5112 } else
5113 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005114 if (DependSinkClause) {
5115 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5116 << 0;
5117 ErrorFound = true;
5118 }
5119 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5120 if (DependSourceClause) {
5121 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5122 << 1;
5123 ErrorFound = true;
5124 }
5125 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005126 }
5127 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005128 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005129 else if (C->getClauseKind() == OMPC_simd)
5130 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005131 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005132 if (!ErrorFound && !SC &&
5133 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005134 // OpenMP [2.8.1,simd Construct, Restrictions]
5135 // An ordered construct with the simd clause is the only OpenMP construct
5136 // that can appear in the simd region.
5137 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005138 ErrorFound = true;
5139 } else if (DependFound && (TC || SC)) {
5140 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5141 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5142 ErrorFound = true;
5143 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5144 Diag(DependFound->getLocStart(),
5145 diag::err_omp_ordered_directive_without_param);
5146 ErrorFound = true;
5147 } else if (TC || Clauses.empty()) {
5148 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5149 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5150 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5151 << (TC != nullptr);
5152 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5153 ErrorFound = true;
5154 }
5155 }
5156 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005157 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005158
5159 if (AStmt) {
5160 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5161
5162 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005163 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005164
5165 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005166}
5167
Alexey Bataev1d160b12015-03-13 12:27:31 +00005168namespace {
5169/// \brief Helper class for checking expression in 'omp atomic [update]'
5170/// construct.
5171class OpenMPAtomicUpdateChecker {
5172 /// \brief Error results for atomic update expressions.
5173 enum ExprAnalysisErrorCode {
5174 /// \brief A statement is not an expression statement.
5175 NotAnExpression,
5176 /// \brief Expression is not builtin binary or unary operation.
5177 NotABinaryOrUnaryExpression,
5178 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5179 NotAnUnaryIncDecExpression,
5180 /// \brief An expression is not of scalar type.
5181 NotAScalarType,
5182 /// \brief A binary operation is not an assignment operation.
5183 NotAnAssignmentOp,
5184 /// \brief RHS part of the binary operation is not a binary expression.
5185 NotABinaryExpression,
5186 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5187 /// expression.
5188 NotABinaryOperator,
5189 /// \brief RHS binary operation does not have reference to the updated LHS
5190 /// part.
5191 NotAnUpdateExpression,
5192 /// \brief No errors is found.
5193 NoError
5194 };
5195 /// \brief Reference to Sema.
5196 Sema &SemaRef;
5197 /// \brief A location for note diagnostics (when error is found).
5198 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005199 /// \brief 'x' lvalue part of the source atomic expression.
5200 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005201 /// \brief 'expr' rvalue part of the source atomic expression.
5202 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005203 /// \brief Helper expression of the form
5204 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5205 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5206 Expr *UpdateExpr;
5207 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5208 /// important for non-associative operations.
5209 bool IsXLHSInRHSPart;
5210 BinaryOperatorKind Op;
5211 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005212 /// \brief true if the source expression is a postfix unary operation, false
5213 /// if it is a prefix unary operation.
5214 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005215
5216public:
5217 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005218 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005219 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005220 /// \brief Check specified statement that it is suitable for 'atomic update'
5221 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005222 /// expression. If DiagId and NoteId == 0, then only check is performed
5223 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005224 /// \param DiagId Diagnostic which should be emitted if error is found.
5225 /// \param NoteId Diagnostic note for the main error message.
5226 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005227 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005228 /// \brief Return the 'x' lvalue part of the source atomic expression.
5229 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005230 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5231 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005232 /// \brief Return the update expression used in calculation of the updated
5233 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5234 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5235 Expr *getUpdateExpr() const { return UpdateExpr; }
5236 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5237 /// false otherwise.
5238 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5239
Alexey Bataevb78ca832015-04-01 03:33:17 +00005240 /// \brief true if the source expression is a postfix unary operation, false
5241 /// if it is a prefix unary operation.
5242 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5243
Alexey Bataev1d160b12015-03-13 12:27:31 +00005244private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005245 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5246 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005247};
5248} // namespace
5249
5250bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5251 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5252 ExprAnalysisErrorCode ErrorFound = NoError;
5253 SourceLocation ErrorLoc, NoteLoc;
5254 SourceRange ErrorRange, NoteRange;
5255 // Allowed constructs are:
5256 // x = x binop expr;
5257 // x = expr binop x;
5258 if (AtomicBinOp->getOpcode() == BO_Assign) {
5259 X = AtomicBinOp->getLHS();
5260 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5261 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5262 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5263 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5264 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005265 Op = AtomicInnerBinOp->getOpcode();
5266 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005267 auto *LHS = AtomicInnerBinOp->getLHS();
5268 auto *RHS = AtomicInnerBinOp->getRHS();
5269 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5270 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5271 /*Canonical=*/true);
5272 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5273 /*Canonical=*/true);
5274 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5275 /*Canonical=*/true);
5276 if (XId == LHSId) {
5277 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005278 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005279 } else if (XId == RHSId) {
5280 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005281 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005282 } else {
5283 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5284 ErrorRange = AtomicInnerBinOp->getSourceRange();
5285 NoteLoc = X->getExprLoc();
5286 NoteRange = X->getSourceRange();
5287 ErrorFound = NotAnUpdateExpression;
5288 }
5289 } else {
5290 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5291 ErrorRange = AtomicInnerBinOp->getSourceRange();
5292 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5293 NoteRange = SourceRange(NoteLoc, NoteLoc);
5294 ErrorFound = NotABinaryOperator;
5295 }
5296 } else {
5297 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5298 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5299 ErrorFound = NotABinaryExpression;
5300 }
5301 } else {
5302 ErrorLoc = AtomicBinOp->getExprLoc();
5303 ErrorRange = AtomicBinOp->getSourceRange();
5304 NoteLoc = AtomicBinOp->getOperatorLoc();
5305 NoteRange = SourceRange(NoteLoc, NoteLoc);
5306 ErrorFound = NotAnAssignmentOp;
5307 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005308 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005309 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5310 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5311 return true;
5312 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005313 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005314 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005315}
5316
5317bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5318 unsigned NoteId) {
5319 ExprAnalysisErrorCode ErrorFound = NoError;
5320 SourceLocation ErrorLoc, NoteLoc;
5321 SourceRange ErrorRange, NoteRange;
5322 // Allowed constructs are:
5323 // x++;
5324 // x--;
5325 // ++x;
5326 // --x;
5327 // x binop= expr;
5328 // x = x binop expr;
5329 // x = expr binop x;
5330 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5331 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5332 if (AtomicBody->getType()->isScalarType() ||
5333 AtomicBody->isInstantiationDependent()) {
5334 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5335 AtomicBody->IgnoreParenImpCasts())) {
5336 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005337 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005338 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005339 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005340 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005341 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005342 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005343 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5344 AtomicBody->IgnoreParenImpCasts())) {
5345 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005346 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005347 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005348 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5349 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005350 // Check for Unary Operation
5351 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005352 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005353 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5354 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005355 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005356 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5357 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005358 } else {
5359 ErrorFound = NotAnUnaryIncDecExpression;
5360 ErrorLoc = AtomicUnaryOp->getExprLoc();
5361 ErrorRange = AtomicUnaryOp->getSourceRange();
5362 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5363 NoteRange = SourceRange(NoteLoc, NoteLoc);
5364 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005365 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005366 ErrorFound = NotABinaryOrUnaryExpression;
5367 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5368 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5369 }
5370 } else {
5371 ErrorFound = NotAScalarType;
5372 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5373 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5374 }
5375 } else {
5376 ErrorFound = NotAnExpression;
5377 NoteLoc = ErrorLoc = S->getLocStart();
5378 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5379 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005380 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005381 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5382 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5383 return true;
5384 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005385 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005386 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005387 // Build an update expression of form 'OpaqueValueExpr(x) binop
5388 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5389 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5390 auto *OVEX = new (SemaRef.getASTContext())
5391 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5392 auto *OVEExpr = new (SemaRef.getASTContext())
5393 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5394 auto Update =
5395 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5396 IsXLHSInRHSPart ? OVEExpr : OVEX);
5397 if (Update.isInvalid())
5398 return true;
5399 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5400 Sema::AA_Casting);
5401 if (Update.isInvalid())
5402 return true;
5403 UpdateExpr = Update.get();
5404 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005405 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005406}
5407
Alexey Bataev0162e452014-07-22 10:10:35 +00005408StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5409 Stmt *AStmt,
5410 SourceLocation StartLoc,
5411 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005412 if (!AStmt)
5413 return StmtError();
5414
David Majnemer9d168222016-08-05 17:44:54 +00005415 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005416 // 1.2.2 OpenMP Language Terminology
5417 // Structured block - An executable statement with a single entry at the
5418 // top and a single exit at the bottom.
5419 // The point of exit cannot be a branch out of the structured block.
5420 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005421 OpenMPClauseKind AtomicKind = OMPC_unknown;
5422 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005423 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005424 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005425 C->getClauseKind() == OMPC_update ||
5426 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005427 if (AtomicKind != OMPC_unknown) {
5428 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5429 << SourceRange(C->getLocStart(), C->getLocEnd());
5430 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5431 << getOpenMPClauseName(AtomicKind);
5432 } else {
5433 AtomicKind = C->getClauseKind();
5434 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005435 }
5436 }
5437 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005438
Alexey Bataev459dec02014-07-24 06:46:57 +00005439 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005440 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5441 Body = EWC->getSubExpr();
5442
Alexey Bataev62cec442014-11-18 10:14:22 +00005443 Expr *X = nullptr;
5444 Expr *V = nullptr;
5445 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005446 Expr *UE = nullptr;
5447 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005448 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005449 // OpenMP [2.12.6, atomic Construct]
5450 // In the next expressions:
5451 // * x and v (as applicable) are both l-value expressions with scalar type.
5452 // * During the execution of an atomic region, multiple syntactic
5453 // occurrences of x must designate the same storage location.
5454 // * Neither of v and expr (as applicable) may access the storage location
5455 // designated by x.
5456 // * Neither of x and expr (as applicable) may access the storage location
5457 // designated by v.
5458 // * expr is an expression with scalar type.
5459 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5460 // * binop, binop=, ++, and -- are not overloaded operators.
5461 // * The expression x binop expr must be numerically equivalent to x binop
5462 // (expr). This requirement is satisfied if the operators in expr have
5463 // precedence greater than binop, or by using parentheses around expr or
5464 // subexpressions of expr.
5465 // * The expression expr binop x must be numerically equivalent to (expr)
5466 // binop x. This requirement is satisfied if the operators in expr have
5467 // precedence equal to or greater than binop, or by using parentheses around
5468 // expr or subexpressions of expr.
5469 // * For forms that allow multiple occurrences of x, the number of times
5470 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005471 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005472 enum {
5473 NotAnExpression,
5474 NotAnAssignmentOp,
5475 NotAScalarType,
5476 NotAnLValue,
5477 NoError
5478 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005479 SourceLocation ErrorLoc, NoteLoc;
5480 SourceRange ErrorRange, NoteRange;
5481 // If clause is read:
5482 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005483 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5484 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005485 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5486 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5487 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5488 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5489 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5490 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5491 if (!X->isLValue() || !V->isLValue()) {
5492 auto NotLValueExpr = X->isLValue() ? V : X;
5493 ErrorFound = NotAnLValue;
5494 ErrorLoc = AtomicBinOp->getExprLoc();
5495 ErrorRange = AtomicBinOp->getSourceRange();
5496 NoteLoc = NotLValueExpr->getExprLoc();
5497 NoteRange = NotLValueExpr->getSourceRange();
5498 }
5499 } else if (!X->isInstantiationDependent() ||
5500 !V->isInstantiationDependent()) {
5501 auto NotScalarExpr =
5502 (X->isInstantiationDependent() || X->getType()->isScalarType())
5503 ? V
5504 : X;
5505 ErrorFound = NotAScalarType;
5506 ErrorLoc = AtomicBinOp->getExprLoc();
5507 ErrorRange = AtomicBinOp->getSourceRange();
5508 NoteLoc = NotScalarExpr->getExprLoc();
5509 NoteRange = NotScalarExpr->getSourceRange();
5510 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005511 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005512 ErrorFound = NotAnAssignmentOp;
5513 ErrorLoc = AtomicBody->getExprLoc();
5514 ErrorRange = AtomicBody->getSourceRange();
5515 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5516 : AtomicBody->getExprLoc();
5517 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5518 : AtomicBody->getSourceRange();
5519 }
5520 } else {
5521 ErrorFound = NotAnExpression;
5522 NoteLoc = ErrorLoc = Body->getLocStart();
5523 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005524 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005525 if (ErrorFound != NoError) {
5526 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5527 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005528 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5529 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005530 return StmtError();
5531 } else if (CurContext->isDependentContext())
5532 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005533 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005534 enum {
5535 NotAnExpression,
5536 NotAnAssignmentOp,
5537 NotAScalarType,
5538 NotAnLValue,
5539 NoError
5540 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005541 SourceLocation ErrorLoc, NoteLoc;
5542 SourceRange ErrorRange, NoteRange;
5543 // If clause is write:
5544 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005545 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5546 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005547 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5548 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005549 X = AtomicBinOp->getLHS();
5550 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005551 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5552 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5553 if (!X->isLValue()) {
5554 ErrorFound = NotAnLValue;
5555 ErrorLoc = AtomicBinOp->getExprLoc();
5556 ErrorRange = AtomicBinOp->getSourceRange();
5557 NoteLoc = X->getExprLoc();
5558 NoteRange = X->getSourceRange();
5559 }
5560 } else if (!X->isInstantiationDependent() ||
5561 !E->isInstantiationDependent()) {
5562 auto NotScalarExpr =
5563 (X->isInstantiationDependent() || X->getType()->isScalarType())
5564 ? E
5565 : X;
5566 ErrorFound = NotAScalarType;
5567 ErrorLoc = AtomicBinOp->getExprLoc();
5568 ErrorRange = AtomicBinOp->getSourceRange();
5569 NoteLoc = NotScalarExpr->getExprLoc();
5570 NoteRange = NotScalarExpr->getSourceRange();
5571 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005572 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005573 ErrorFound = NotAnAssignmentOp;
5574 ErrorLoc = AtomicBody->getExprLoc();
5575 ErrorRange = AtomicBody->getSourceRange();
5576 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5577 : AtomicBody->getExprLoc();
5578 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5579 : AtomicBody->getSourceRange();
5580 }
5581 } else {
5582 ErrorFound = NotAnExpression;
5583 NoteLoc = ErrorLoc = Body->getLocStart();
5584 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005585 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005586 if (ErrorFound != NoError) {
5587 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5588 << ErrorRange;
5589 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5590 << NoteRange;
5591 return StmtError();
5592 } else if (CurContext->isDependentContext())
5593 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005594 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005595 // If clause is update:
5596 // x++;
5597 // x--;
5598 // ++x;
5599 // --x;
5600 // x binop= expr;
5601 // x = x binop expr;
5602 // x = expr binop x;
5603 OpenMPAtomicUpdateChecker Checker(*this);
5604 if (Checker.checkStatement(
5605 Body, (AtomicKind == OMPC_update)
5606 ? diag::err_omp_atomic_update_not_expression_statement
5607 : diag::err_omp_atomic_not_expression_statement,
5608 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005609 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005610 if (!CurContext->isDependentContext()) {
5611 E = Checker.getExpr();
5612 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005613 UE = Checker.getUpdateExpr();
5614 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005615 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005616 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005617 enum {
5618 NotAnAssignmentOp,
5619 NotACompoundStatement,
5620 NotTwoSubstatements,
5621 NotASpecificExpression,
5622 NoError
5623 } ErrorFound = NoError;
5624 SourceLocation ErrorLoc, NoteLoc;
5625 SourceRange ErrorRange, NoteRange;
5626 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5627 // If clause is a capture:
5628 // v = x++;
5629 // v = x--;
5630 // v = ++x;
5631 // v = --x;
5632 // v = x binop= expr;
5633 // v = x = x binop expr;
5634 // v = x = expr binop x;
5635 auto *AtomicBinOp =
5636 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5637 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5638 V = AtomicBinOp->getLHS();
5639 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5640 OpenMPAtomicUpdateChecker Checker(*this);
5641 if (Checker.checkStatement(
5642 Body, diag::err_omp_atomic_capture_not_expression_statement,
5643 diag::note_omp_atomic_update))
5644 return StmtError();
5645 E = Checker.getExpr();
5646 X = Checker.getX();
5647 UE = Checker.getUpdateExpr();
5648 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5649 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005650 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005651 ErrorLoc = AtomicBody->getExprLoc();
5652 ErrorRange = AtomicBody->getSourceRange();
5653 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5654 : AtomicBody->getExprLoc();
5655 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5656 : AtomicBody->getSourceRange();
5657 ErrorFound = NotAnAssignmentOp;
5658 }
5659 if (ErrorFound != NoError) {
5660 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5661 << ErrorRange;
5662 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5663 return StmtError();
5664 } else if (CurContext->isDependentContext()) {
5665 UE = V = E = X = nullptr;
5666 }
5667 } else {
5668 // If clause is a capture:
5669 // { v = x; x = expr; }
5670 // { v = x; x++; }
5671 // { v = x; x--; }
5672 // { v = x; ++x; }
5673 // { v = x; --x; }
5674 // { v = x; x binop= expr; }
5675 // { v = x; x = x binop expr; }
5676 // { v = x; x = expr binop x; }
5677 // { x++; v = x; }
5678 // { x--; v = x; }
5679 // { ++x; v = x; }
5680 // { --x; v = x; }
5681 // { x binop= expr; v = x; }
5682 // { x = x binop expr; v = x; }
5683 // { x = expr binop x; v = x; }
5684 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5685 // Check that this is { expr1; expr2; }
5686 if (CS->size() == 2) {
5687 auto *First = CS->body_front();
5688 auto *Second = CS->body_back();
5689 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5690 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5691 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5692 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5693 // Need to find what subexpression is 'v' and what is 'x'.
5694 OpenMPAtomicUpdateChecker Checker(*this);
5695 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5696 BinaryOperator *BinOp = nullptr;
5697 if (IsUpdateExprFound) {
5698 BinOp = dyn_cast<BinaryOperator>(First);
5699 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5700 }
5701 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5702 // { v = x; x++; }
5703 // { v = x; x--; }
5704 // { v = x; ++x; }
5705 // { v = x; --x; }
5706 // { v = x; x binop= expr; }
5707 // { v = x; x = x binop expr; }
5708 // { v = x; x = expr binop x; }
5709 // Check that the first expression has form v = x.
5710 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5711 llvm::FoldingSetNodeID XId, PossibleXId;
5712 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5713 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5714 IsUpdateExprFound = XId == PossibleXId;
5715 if (IsUpdateExprFound) {
5716 V = BinOp->getLHS();
5717 X = Checker.getX();
5718 E = Checker.getExpr();
5719 UE = Checker.getUpdateExpr();
5720 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005721 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005722 }
5723 }
5724 if (!IsUpdateExprFound) {
5725 IsUpdateExprFound = !Checker.checkStatement(First);
5726 BinOp = nullptr;
5727 if (IsUpdateExprFound) {
5728 BinOp = dyn_cast<BinaryOperator>(Second);
5729 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5730 }
5731 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5732 // { x++; v = x; }
5733 // { x--; v = x; }
5734 // { ++x; v = x; }
5735 // { --x; v = x; }
5736 // { x binop= expr; v = x; }
5737 // { x = x binop expr; v = x; }
5738 // { x = expr binop x; v = x; }
5739 // Check that the second expression has form v = x.
5740 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5741 llvm::FoldingSetNodeID XId, PossibleXId;
5742 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5743 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5744 IsUpdateExprFound = XId == PossibleXId;
5745 if (IsUpdateExprFound) {
5746 V = BinOp->getLHS();
5747 X = Checker.getX();
5748 E = Checker.getExpr();
5749 UE = Checker.getUpdateExpr();
5750 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005751 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005752 }
5753 }
5754 }
5755 if (!IsUpdateExprFound) {
5756 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005757 auto *FirstExpr = dyn_cast<Expr>(First);
5758 auto *SecondExpr = dyn_cast<Expr>(Second);
5759 if (!FirstExpr || !SecondExpr ||
5760 !(FirstExpr->isInstantiationDependent() ||
5761 SecondExpr->isInstantiationDependent())) {
5762 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5763 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005764 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005765 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5766 : First->getLocStart();
5767 NoteRange = ErrorRange = FirstBinOp
5768 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005769 : SourceRange(ErrorLoc, ErrorLoc);
5770 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005771 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5772 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5773 ErrorFound = NotAnAssignmentOp;
5774 NoteLoc = ErrorLoc = SecondBinOp
5775 ? SecondBinOp->getOperatorLoc()
5776 : Second->getLocStart();
5777 NoteRange = ErrorRange =
5778 SecondBinOp ? SecondBinOp->getSourceRange()
5779 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005780 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005781 auto *PossibleXRHSInFirst =
5782 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5783 auto *PossibleXLHSInSecond =
5784 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5785 llvm::FoldingSetNodeID X1Id, X2Id;
5786 PossibleXRHSInFirst->Profile(X1Id, Context,
5787 /*Canonical=*/true);
5788 PossibleXLHSInSecond->Profile(X2Id, Context,
5789 /*Canonical=*/true);
5790 IsUpdateExprFound = X1Id == X2Id;
5791 if (IsUpdateExprFound) {
5792 V = FirstBinOp->getLHS();
5793 X = SecondBinOp->getLHS();
5794 E = SecondBinOp->getRHS();
5795 UE = nullptr;
5796 IsXLHSInRHSPart = false;
5797 IsPostfixUpdate = true;
5798 } else {
5799 ErrorFound = NotASpecificExpression;
5800 ErrorLoc = FirstBinOp->getExprLoc();
5801 ErrorRange = FirstBinOp->getSourceRange();
5802 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5803 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5804 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005805 }
5806 }
5807 }
5808 }
5809 } else {
5810 NoteLoc = ErrorLoc = Body->getLocStart();
5811 NoteRange = ErrorRange =
5812 SourceRange(Body->getLocStart(), Body->getLocStart());
5813 ErrorFound = NotTwoSubstatements;
5814 }
5815 } else {
5816 NoteLoc = ErrorLoc = Body->getLocStart();
5817 NoteRange = ErrorRange =
5818 SourceRange(Body->getLocStart(), Body->getLocStart());
5819 ErrorFound = NotACompoundStatement;
5820 }
5821 if (ErrorFound != NoError) {
5822 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5823 << ErrorRange;
5824 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5825 return StmtError();
5826 } else if (CurContext->isDependentContext()) {
5827 UE = V = E = X = nullptr;
5828 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005829 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005830 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005831
5832 getCurFunction()->setHasBranchProtectedScope();
5833
Alexey Bataev62cec442014-11-18 10:14:22 +00005834 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005835 X, V, E, UE, IsXLHSInRHSPart,
5836 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005837}
5838
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005839StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5840 Stmt *AStmt,
5841 SourceLocation StartLoc,
5842 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005843 if (!AStmt)
5844 return StmtError();
5845
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005846 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5847 // 1.2.2 OpenMP Language Terminology
5848 // Structured block - An executable statement with a single entry at the
5849 // top and a single exit at the bottom.
5850 // The point of exit cannot be a branch out of the structured block.
5851 // longjmp() and throw() must not violate the entry/exit criteria.
5852 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005853
Alexey Bataev13314bf2014-10-09 04:18:56 +00005854 // OpenMP [2.16, Nesting of Regions]
5855 // If specified, a teams construct must be contained within a target
5856 // construct. That target construct must contain no statements or directives
5857 // outside of the teams construct.
5858 if (DSAStack->hasInnerTeamsRegion()) {
5859 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5860 bool OMPTeamsFound = true;
5861 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5862 auto I = CS->body_begin();
5863 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005864 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005865 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5866 OMPTeamsFound = false;
5867 break;
5868 }
5869 ++I;
5870 }
5871 assert(I != CS->body_end() && "Not found statement");
5872 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005873 } else {
5874 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5875 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005876 }
5877 if (!OMPTeamsFound) {
5878 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5879 Diag(DSAStack->getInnerTeamsRegionLoc(),
5880 diag::note_omp_nested_teams_construct_here);
5881 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5882 << isa<OMPExecutableDirective>(S);
5883 return StmtError();
5884 }
5885 }
5886
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005887 getCurFunction()->setHasBranchProtectedScope();
5888
5889 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5890}
5891
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005892StmtResult
5893Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5894 Stmt *AStmt, SourceLocation StartLoc,
5895 SourceLocation EndLoc) {
5896 if (!AStmt)
5897 return StmtError();
5898
5899 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5900 // 1.2.2 OpenMP Language Terminology
5901 // Structured block - An executable statement with a single entry at the
5902 // top and a single exit at the bottom.
5903 // The point of exit cannot be a branch out of the structured block.
5904 // longjmp() and throw() must not violate the entry/exit criteria.
5905 CS->getCapturedDecl()->setNothrow();
5906
5907 getCurFunction()->setHasBranchProtectedScope();
5908
5909 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5910 AStmt);
5911}
5912
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005913StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5914 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5915 SourceLocation EndLoc,
5916 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5917 if (!AStmt)
5918 return StmtError();
5919
5920 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5921 // 1.2.2 OpenMP Language Terminology
5922 // Structured block - An executable statement with a single entry at the
5923 // top and a single exit at the bottom.
5924 // The point of exit cannot be a branch out of the structured block.
5925 // longjmp() and throw() must not violate the entry/exit criteria.
5926 CS->getCapturedDecl()->setNothrow();
5927
5928 OMPLoopDirective::HelperExprs B;
5929 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5930 // define the nested loops number.
5931 unsigned NestedLoopCount =
5932 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5933 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5934 VarsWithImplicitDSA, B);
5935 if (NestedLoopCount == 0)
5936 return StmtError();
5937
5938 assert((CurContext->isDependentContext() || B.builtAll()) &&
5939 "omp target parallel for loop exprs were not built");
5940
5941 if (!CurContext->isDependentContext()) {
5942 // Finalize the clauses that need pre-built expressions for CodeGen.
5943 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005944 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005945 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005946 B.NumIterations, *this, CurScope,
5947 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005948 return StmtError();
5949 }
5950 }
5951
5952 getCurFunction()->setHasBranchProtectedScope();
5953 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5954 NestedLoopCount, Clauses, AStmt,
5955 B, DSAStack->isCancelRegion());
5956}
5957
Alexey Bataev95b64a92017-05-30 16:00:04 +00005958/// Check for existence of a map clause in the list of clauses.
5959static bool hasClauses(ArrayRef<OMPClause *> Clauses,
5960 const OpenMPClauseKind K) {
5961 return llvm::any_of(
5962 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
5963}
Samuel Antaodf67fc42016-01-19 19:15:56 +00005964
Alexey Bataev95b64a92017-05-30 16:00:04 +00005965template <typename... Params>
5966static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
5967 const Params... ClauseTypes) {
5968 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00005969}
5970
Michael Wong65f367f2015-07-21 13:44:28 +00005971StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5972 Stmt *AStmt,
5973 SourceLocation StartLoc,
5974 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005975 if (!AStmt)
5976 return StmtError();
5977
5978 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5979
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005980 // OpenMP [2.10.1, Restrictions, p. 97]
5981 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00005982 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
5983 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
5984 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00005985 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005986 return StmtError();
5987 }
5988
Michael Wong65f367f2015-07-21 13:44:28 +00005989 getCurFunction()->setHasBranchProtectedScope();
5990
5991 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5992 AStmt);
5993}
5994
Samuel Antaodf67fc42016-01-19 19:15:56 +00005995StmtResult
5996Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5997 SourceLocation StartLoc,
5998 SourceLocation EndLoc) {
5999 // OpenMP [2.10.2, Restrictions, p. 99]
6000 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006001 if (!hasClauses(Clauses, OMPC_map)) {
6002 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6003 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006004 return StmtError();
6005 }
6006
6007 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6008 Clauses);
6009}
6010
Samuel Antao72590762016-01-19 20:04:50 +00006011StmtResult
6012Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6013 SourceLocation StartLoc,
6014 SourceLocation EndLoc) {
6015 // OpenMP [2.10.3, Restrictions, p. 102]
6016 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006017 if (!hasClauses(Clauses, OMPC_map)) {
6018 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6019 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006020 return StmtError();
6021 }
6022
6023 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6024}
6025
Samuel Antao686c70c2016-05-26 17:30:50 +00006026StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6027 SourceLocation StartLoc,
6028 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006029 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006030 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6031 return StmtError();
6032 }
6033 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6034}
6035
Alexey Bataev13314bf2014-10-09 04:18:56 +00006036StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6037 Stmt *AStmt, SourceLocation StartLoc,
6038 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006039 if (!AStmt)
6040 return StmtError();
6041
Alexey Bataev13314bf2014-10-09 04:18:56 +00006042 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6043 // 1.2.2 OpenMP Language Terminology
6044 // Structured block - An executable statement with a single entry at the
6045 // top and a single exit at the bottom.
6046 // The point of exit cannot be a branch out of the structured block.
6047 // longjmp() and throw() must not violate the entry/exit criteria.
6048 CS->getCapturedDecl()->setNothrow();
6049
6050 getCurFunction()->setHasBranchProtectedScope();
6051
6052 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6053}
6054
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006055StmtResult
6056Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6057 SourceLocation EndLoc,
6058 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006059 if (DSAStack->isParentNowaitRegion()) {
6060 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6061 return StmtError();
6062 }
6063 if (DSAStack->isParentOrderedRegion()) {
6064 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6065 return StmtError();
6066 }
6067 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6068 CancelRegion);
6069}
6070
Alexey Bataev87933c72015-09-18 08:07:34 +00006071StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6072 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006073 SourceLocation EndLoc,
6074 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006075 if (DSAStack->isParentNowaitRegion()) {
6076 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6077 return StmtError();
6078 }
6079 if (DSAStack->isParentOrderedRegion()) {
6080 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6081 return StmtError();
6082 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006083 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006084 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6085 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006086}
6087
Alexey Bataev382967a2015-12-08 12:06:20 +00006088static bool checkGrainsizeNumTasksClauses(Sema &S,
6089 ArrayRef<OMPClause *> Clauses) {
6090 OMPClause *PrevClause = nullptr;
6091 bool ErrorFound = false;
6092 for (auto *C : Clauses) {
6093 if (C->getClauseKind() == OMPC_grainsize ||
6094 C->getClauseKind() == OMPC_num_tasks) {
6095 if (!PrevClause)
6096 PrevClause = C;
6097 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6098 S.Diag(C->getLocStart(),
6099 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6100 << getOpenMPClauseName(C->getClauseKind())
6101 << getOpenMPClauseName(PrevClause->getClauseKind());
6102 S.Diag(PrevClause->getLocStart(),
6103 diag::note_omp_previous_grainsize_num_tasks)
6104 << getOpenMPClauseName(PrevClause->getClauseKind());
6105 ErrorFound = true;
6106 }
6107 }
6108 }
6109 return ErrorFound;
6110}
6111
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006112static bool checkReductionClauseWithNogroup(Sema &S,
6113 ArrayRef<OMPClause *> Clauses) {
6114 OMPClause *ReductionClause = nullptr;
6115 OMPClause *NogroupClause = nullptr;
6116 for (auto *C : Clauses) {
6117 if (C->getClauseKind() == OMPC_reduction) {
6118 ReductionClause = C;
6119 if (NogroupClause)
6120 break;
6121 continue;
6122 }
6123 if (C->getClauseKind() == OMPC_nogroup) {
6124 NogroupClause = C;
6125 if (ReductionClause)
6126 break;
6127 continue;
6128 }
6129 }
6130 if (ReductionClause && NogroupClause) {
6131 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6132 << SourceRange(NogroupClause->getLocStart(),
6133 NogroupClause->getLocEnd());
6134 return true;
6135 }
6136 return false;
6137}
6138
Alexey Bataev49f6e782015-12-01 04:18:41 +00006139StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6140 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6141 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006142 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006143 if (!AStmt)
6144 return StmtError();
6145
6146 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6147 OMPLoopDirective::HelperExprs B;
6148 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6149 // define the nested loops number.
6150 unsigned NestedLoopCount =
6151 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006152 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006153 VarsWithImplicitDSA, B);
6154 if (NestedLoopCount == 0)
6155 return StmtError();
6156
6157 assert((CurContext->isDependentContext() || B.builtAll()) &&
6158 "omp for loop exprs were not built");
6159
Alexey Bataev382967a2015-12-08 12:06:20 +00006160 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6161 // The grainsize clause and num_tasks clause are mutually exclusive and may
6162 // not appear on the same taskloop directive.
6163 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6164 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006165 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6166 // If a reduction clause is present on the taskloop directive, the nogroup
6167 // clause must not be specified.
6168 if (checkReductionClauseWithNogroup(*this, Clauses))
6169 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006170
Alexey Bataev49f6e782015-12-01 04:18:41 +00006171 getCurFunction()->setHasBranchProtectedScope();
6172 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6173 NestedLoopCount, Clauses, AStmt, B);
6174}
6175
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006176StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6177 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6178 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006179 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006180 if (!AStmt)
6181 return StmtError();
6182
6183 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6184 OMPLoopDirective::HelperExprs B;
6185 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6186 // define the nested loops number.
6187 unsigned NestedLoopCount =
6188 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6189 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6190 VarsWithImplicitDSA, B);
6191 if (NestedLoopCount == 0)
6192 return StmtError();
6193
6194 assert((CurContext->isDependentContext() || B.builtAll()) &&
6195 "omp for loop exprs were not built");
6196
Alexey Bataev5a3af132016-03-29 08:58:54 +00006197 if (!CurContext->isDependentContext()) {
6198 // Finalize the clauses that need pre-built expressions for CodeGen.
6199 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006200 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006201 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006202 B.NumIterations, *this, CurScope,
6203 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006204 return StmtError();
6205 }
6206 }
6207
Alexey Bataev382967a2015-12-08 12:06:20 +00006208 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6209 // The grainsize clause and num_tasks clause are mutually exclusive and may
6210 // not appear on the same taskloop directive.
6211 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6212 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006213 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6214 // If a reduction clause is present on the taskloop directive, the nogroup
6215 // clause must not be specified.
6216 if (checkReductionClauseWithNogroup(*this, Clauses))
6217 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006218
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006219 getCurFunction()->setHasBranchProtectedScope();
6220 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6221 NestedLoopCount, Clauses, AStmt, B);
6222}
6223
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006224StmtResult Sema::ActOnOpenMPDistributeDirective(
6225 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6226 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006227 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006228 if (!AStmt)
6229 return StmtError();
6230
6231 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6232 OMPLoopDirective::HelperExprs B;
6233 // In presence of clause 'collapse' with number of loops, it will
6234 // define the nested loops number.
6235 unsigned NestedLoopCount =
6236 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6237 nullptr /*ordered not a clause on distribute*/, AStmt,
6238 *this, *DSAStack, VarsWithImplicitDSA, B);
6239 if (NestedLoopCount == 0)
6240 return StmtError();
6241
6242 assert((CurContext->isDependentContext() || B.builtAll()) &&
6243 "omp for loop exprs were not built");
6244
6245 getCurFunction()->setHasBranchProtectedScope();
6246 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6247 NestedLoopCount, Clauses, AStmt, B);
6248}
6249
Carlo Bertolli9925f152016-06-27 14:55:37 +00006250StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6251 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6252 SourceLocation EndLoc,
6253 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6254 if (!AStmt)
6255 return StmtError();
6256
6257 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6258 // 1.2.2 OpenMP Language Terminology
6259 // Structured block - An executable statement with a single entry at the
6260 // top and a single exit at the bottom.
6261 // The point of exit cannot be a branch out of the structured block.
6262 // longjmp() and throw() must not violate the entry/exit criteria.
6263 CS->getCapturedDecl()->setNothrow();
6264
6265 OMPLoopDirective::HelperExprs B;
6266 // In presence of clause 'collapse' with number of loops, it will
6267 // define the nested loops number.
6268 unsigned NestedLoopCount = CheckOpenMPLoop(
6269 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6270 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6271 VarsWithImplicitDSA, B);
6272 if (NestedLoopCount == 0)
6273 return StmtError();
6274
6275 assert((CurContext->isDependentContext() || B.builtAll()) &&
6276 "omp for loop exprs were not built");
6277
6278 getCurFunction()->setHasBranchProtectedScope();
6279 return OMPDistributeParallelForDirective::Create(
6280 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6281}
6282
Kelvin Li4a39add2016-07-05 05:00:15 +00006283StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6284 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6285 SourceLocation EndLoc,
6286 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6287 if (!AStmt)
6288 return StmtError();
6289
6290 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6291 // 1.2.2 OpenMP Language Terminology
6292 // Structured block - An executable statement with a single entry at the
6293 // top and a single exit at the bottom.
6294 // The point of exit cannot be a branch out of the structured block.
6295 // longjmp() and throw() must not violate the entry/exit criteria.
6296 CS->getCapturedDecl()->setNothrow();
6297
6298 OMPLoopDirective::HelperExprs B;
6299 // In presence of clause 'collapse' with number of loops, it will
6300 // define the nested loops number.
6301 unsigned NestedLoopCount = CheckOpenMPLoop(
6302 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6303 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6304 VarsWithImplicitDSA, B);
6305 if (NestedLoopCount == 0)
6306 return StmtError();
6307
6308 assert((CurContext->isDependentContext() || B.builtAll()) &&
6309 "omp for loop exprs were not built");
6310
Kelvin Lic5609492016-07-15 04:39:07 +00006311 if (checkSimdlenSafelenSpecified(*this, Clauses))
6312 return StmtError();
6313
Kelvin Li4a39add2016-07-05 05:00:15 +00006314 getCurFunction()->setHasBranchProtectedScope();
6315 return OMPDistributeParallelForSimdDirective::Create(
6316 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6317}
6318
Kelvin Li787f3fc2016-07-06 04:45:38 +00006319StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6320 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6321 SourceLocation EndLoc,
6322 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6323 if (!AStmt)
6324 return StmtError();
6325
6326 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6327 // 1.2.2 OpenMP Language Terminology
6328 // Structured block - An executable statement with a single entry at the
6329 // top and a single exit at the bottom.
6330 // The point of exit cannot be a branch out of the structured block.
6331 // longjmp() and throw() must not violate the entry/exit criteria.
6332 CS->getCapturedDecl()->setNothrow();
6333
6334 OMPLoopDirective::HelperExprs B;
6335 // In presence of clause 'collapse' with number of loops, it will
6336 // define the nested loops number.
6337 unsigned NestedLoopCount =
6338 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6339 nullptr /*ordered not a clause on distribute*/, AStmt,
6340 *this, *DSAStack, VarsWithImplicitDSA, B);
6341 if (NestedLoopCount == 0)
6342 return StmtError();
6343
6344 assert((CurContext->isDependentContext() || B.builtAll()) &&
6345 "omp for loop exprs were not built");
6346
Kelvin Lic5609492016-07-15 04:39:07 +00006347 if (checkSimdlenSafelenSpecified(*this, Clauses))
6348 return StmtError();
6349
Kelvin Li787f3fc2016-07-06 04:45:38 +00006350 getCurFunction()->setHasBranchProtectedScope();
6351 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6352 NestedLoopCount, Clauses, AStmt, B);
6353}
6354
Kelvin Lia579b912016-07-14 02:54:56 +00006355StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6356 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6357 SourceLocation EndLoc,
6358 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6359 if (!AStmt)
6360 return StmtError();
6361
6362 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6363 // 1.2.2 OpenMP Language Terminology
6364 // Structured block - An executable statement with a single entry at the
6365 // top and a single exit at the bottom.
6366 // The point of exit cannot be a branch out of the structured block.
6367 // longjmp() and throw() must not violate the entry/exit criteria.
6368 CS->getCapturedDecl()->setNothrow();
6369
6370 OMPLoopDirective::HelperExprs B;
6371 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6372 // define the nested loops number.
6373 unsigned NestedLoopCount = CheckOpenMPLoop(
6374 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6375 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6376 VarsWithImplicitDSA, B);
6377 if (NestedLoopCount == 0)
6378 return StmtError();
6379
6380 assert((CurContext->isDependentContext() || B.builtAll()) &&
6381 "omp target parallel for simd loop exprs were not built");
6382
6383 if (!CurContext->isDependentContext()) {
6384 // Finalize the clauses that need pre-built expressions for CodeGen.
6385 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006386 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006387 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6388 B.NumIterations, *this, CurScope,
6389 DSAStack))
6390 return StmtError();
6391 }
6392 }
Kelvin Lic5609492016-07-15 04:39:07 +00006393 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006394 return StmtError();
6395
6396 getCurFunction()->setHasBranchProtectedScope();
6397 return OMPTargetParallelForSimdDirective::Create(
6398 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6399}
6400
Kelvin Li986330c2016-07-20 22:57:10 +00006401StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6402 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6403 SourceLocation EndLoc,
6404 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6405 if (!AStmt)
6406 return StmtError();
6407
6408 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6409 // 1.2.2 OpenMP Language Terminology
6410 // Structured block - An executable statement with a single entry at the
6411 // top and a single exit at the bottom.
6412 // The point of exit cannot be a branch out of the structured block.
6413 // longjmp() and throw() must not violate the entry/exit criteria.
6414 CS->getCapturedDecl()->setNothrow();
6415
6416 OMPLoopDirective::HelperExprs B;
6417 // In presence of clause 'collapse' with number of loops, it will define the
6418 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006419 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006420 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6421 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6422 VarsWithImplicitDSA, B);
6423 if (NestedLoopCount == 0)
6424 return StmtError();
6425
6426 assert((CurContext->isDependentContext() || B.builtAll()) &&
6427 "omp target simd loop exprs were not built");
6428
6429 if (!CurContext->isDependentContext()) {
6430 // Finalize the clauses that need pre-built expressions for CodeGen.
6431 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006432 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6434 B.NumIterations, *this, CurScope,
6435 DSAStack))
6436 return StmtError();
6437 }
6438 }
6439
6440 if (checkSimdlenSafelenSpecified(*this, Clauses))
6441 return StmtError();
6442
6443 getCurFunction()->setHasBranchProtectedScope();
6444 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6445 NestedLoopCount, Clauses, AStmt, B);
6446}
6447
Kelvin Li02532872016-08-05 14:37:37 +00006448StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6449 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6450 SourceLocation EndLoc,
6451 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6452 if (!AStmt)
6453 return StmtError();
6454
6455 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6456 // 1.2.2 OpenMP Language Terminology
6457 // Structured block - An executable statement with a single entry at the
6458 // top and a single exit at the bottom.
6459 // The point of exit cannot be a branch out of the structured block.
6460 // longjmp() and throw() must not violate the entry/exit criteria.
6461 CS->getCapturedDecl()->setNothrow();
6462
6463 OMPLoopDirective::HelperExprs B;
6464 // In presence of clause 'collapse' with number of loops, it will
6465 // define the nested loops number.
6466 unsigned NestedLoopCount =
6467 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6468 nullptr /*ordered not a clause on distribute*/, AStmt,
6469 *this, *DSAStack, VarsWithImplicitDSA, B);
6470 if (NestedLoopCount == 0)
6471 return StmtError();
6472
6473 assert((CurContext->isDependentContext() || B.builtAll()) &&
6474 "omp teams distribute loop exprs were not built");
6475
6476 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006477 return OMPTeamsDistributeDirective::Create(
6478 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006479}
6480
Kelvin Li4e325f72016-10-25 12:50:55 +00006481StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6482 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6483 SourceLocation EndLoc,
6484 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6485 if (!AStmt)
6486 return StmtError();
6487
6488 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6489 // 1.2.2 OpenMP Language Terminology
6490 // Structured block - An executable statement with a single entry at the
6491 // top and a single exit at the bottom.
6492 // The point of exit cannot be a branch out of the structured block.
6493 // longjmp() and throw() must not violate the entry/exit criteria.
6494 CS->getCapturedDecl()->setNothrow();
6495
6496 OMPLoopDirective::HelperExprs B;
6497 // In presence of clause 'collapse' with number of loops, it will
6498 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006499 unsigned NestedLoopCount = CheckOpenMPLoop(
6500 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6501 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6502 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006503
6504 if (NestedLoopCount == 0)
6505 return StmtError();
6506
6507 assert((CurContext->isDependentContext() || B.builtAll()) &&
6508 "omp teams distribute simd loop exprs were not built");
6509
6510 if (!CurContext->isDependentContext()) {
6511 // Finalize the clauses that need pre-built expressions for CodeGen.
6512 for (auto C : Clauses) {
6513 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6514 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6515 B.NumIterations, *this, CurScope,
6516 DSAStack))
6517 return StmtError();
6518 }
6519 }
6520
6521 if (checkSimdlenSafelenSpecified(*this, Clauses))
6522 return StmtError();
6523
6524 getCurFunction()->setHasBranchProtectedScope();
6525 return OMPTeamsDistributeSimdDirective::Create(
6526 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6527}
6528
Kelvin Li579e41c2016-11-30 23:51:03 +00006529StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6530 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6531 SourceLocation EndLoc,
6532 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6533 if (!AStmt)
6534 return StmtError();
6535
6536 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6537 // 1.2.2 OpenMP Language Terminology
6538 // Structured block - An executable statement with a single entry at the
6539 // top and a single exit at the bottom.
6540 // The point of exit cannot be a branch out of the structured block.
6541 // longjmp() and throw() must not violate the entry/exit criteria.
6542 CS->getCapturedDecl()->setNothrow();
6543
6544 OMPLoopDirective::HelperExprs B;
6545 // In presence of clause 'collapse' with number of loops, it will
6546 // define the nested loops number.
6547 auto NestedLoopCount = CheckOpenMPLoop(
6548 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6549 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6550 VarsWithImplicitDSA, B);
6551
6552 if (NestedLoopCount == 0)
6553 return StmtError();
6554
6555 assert((CurContext->isDependentContext() || B.builtAll()) &&
6556 "omp for loop exprs were not built");
6557
6558 if (!CurContext->isDependentContext()) {
6559 // Finalize the clauses that need pre-built expressions for CodeGen.
6560 for (auto C : Clauses) {
6561 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6562 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6563 B.NumIterations, *this, CurScope,
6564 DSAStack))
6565 return StmtError();
6566 }
6567 }
6568
6569 if (checkSimdlenSafelenSpecified(*this, Clauses))
6570 return StmtError();
6571
6572 getCurFunction()->setHasBranchProtectedScope();
6573 return OMPTeamsDistributeParallelForSimdDirective::Create(
6574 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6575}
6576
Kelvin Li7ade93f2016-12-09 03:24:30 +00006577StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6578 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6579 SourceLocation EndLoc,
6580 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6581 if (!AStmt)
6582 return StmtError();
6583
6584 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6585 // 1.2.2 OpenMP Language Terminology
6586 // Structured block - An executable statement with a single entry at the
6587 // top and a single exit at the bottom.
6588 // The point of exit cannot be a branch out of the structured block.
6589 // longjmp() and throw() must not violate the entry/exit criteria.
6590 CS->getCapturedDecl()->setNothrow();
6591
6592 OMPLoopDirective::HelperExprs B;
6593 // In presence of clause 'collapse' with number of loops, it will
6594 // define the nested loops number.
6595 unsigned NestedLoopCount = CheckOpenMPLoop(
6596 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6597 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6598 VarsWithImplicitDSA, B);
6599
6600 if (NestedLoopCount == 0)
6601 return StmtError();
6602
6603 assert((CurContext->isDependentContext() || B.builtAll()) &&
6604 "omp for loop exprs were not built");
6605
6606 if (!CurContext->isDependentContext()) {
6607 // Finalize the clauses that need pre-built expressions for CodeGen.
6608 for (auto C : Clauses) {
6609 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6610 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6611 B.NumIterations, *this, CurScope,
6612 DSAStack))
6613 return StmtError();
6614 }
6615 }
6616
6617 getCurFunction()->setHasBranchProtectedScope();
6618 return OMPTeamsDistributeParallelForDirective::Create(
6619 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6620}
6621
Kelvin Libf594a52016-12-17 05:48:59 +00006622StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6623 Stmt *AStmt,
6624 SourceLocation StartLoc,
6625 SourceLocation EndLoc) {
6626 if (!AStmt)
6627 return StmtError();
6628
6629 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6630 // 1.2.2 OpenMP Language Terminology
6631 // Structured block - An executable statement with a single entry at the
6632 // top and a single exit at the bottom.
6633 // The point of exit cannot be a branch out of the structured block.
6634 // longjmp() and throw() must not violate the entry/exit criteria.
6635 CS->getCapturedDecl()->setNothrow();
6636
6637 getCurFunction()->setHasBranchProtectedScope();
6638
6639 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6640 AStmt);
6641}
6642
Kelvin Li83c451e2016-12-25 04:52:54 +00006643StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6644 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6645 SourceLocation EndLoc,
6646 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6647 if (!AStmt)
6648 return StmtError();
6649
6650 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6651 // 1.2.2 OpenMP Language Terminology
6652 // Structured block - An executable statement with a single entry at the
6653 // top and a single exit at the bottom.
6654 // The point of exit cannot be a branch out of the structured block.
6655 // longjmp() and throw() must not violate the entry/exit criteria.
6656 CS->getCapturedDecl()->setNothrow();
6657
6658 OMPLoopDirective::HelperExprs B;
6659 // In presence of clause 'collapse' with number of loops, it will
6660 // define the nested loops number.
6661 auto NestedLoopCount = CheckOpenMPLoop(
6662 OMPD_target_teams_distribute,
6663 getCollapseNumberExpr(Clauses),
6664 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6665 VarsWithImplicitDSA, B);
6666 if (NestedLoopCount == 0)
6667 return StmtError();
6668
6669 assert((CurContext->isDependentContext() || B.builtAll()) &&
6670 "omp target teams distribute loop exprs were not built");
6671
6672 getCurFunction()->setHasBranchProtectedScope();
6673 return OMPTargetTeamsDistributeDirective::Create(
6674 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6675}
6676
Kelvin Li80e8f562016-12-29 22:16:30 +00006677StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6679 SourceLocation EndLoc,
6680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6681 if (!AStmt)
6682 return StmtError();
6683
6684 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6685 // 1.2.2 OpenMP Language Terminology
6686 // Structured block - An executable statement with a single entry at the
6687 // top and a single exit at the bottom.
6688 // The point of exit cannot be a branch out of the structured block.
6689 // longjmp() and throw() must not violate the entry/exit criteria.
6690 CS->getCapturedDecl()->setNothrow();
6691
6692 OMPLoopDirective::HelperExprs B;
6693 // In presence of clause 'collapse' with number of loops, it will
6694 // define the nested loops number.
6695 auto NestedLoopCount = CheckOpenMPLoop(
6696 OMPD_target_teams_distribute_parallel_for,
6697 getCollapseNumberExpr(Clauses),
6698 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6699 VarsWithImplicitDSA, B);
6700 if (NestedLoopCount == 0)
6701 return StmtError();
6702
6703 assert((CurContext->isDependentContext() || B.builtAll()) &&
6704 "omp target teams distribute parallel for loop exprs were not built");
6705
6706 if (!CurContext->isDependentContext()) {
6707 // Finalize the clauses that need pre-built expressions for CodeGen.
6708 for (auto C : Clauses) {
6709 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6710 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6711 B.NumIterations, *this, CurScope,
6712 DSAStack))
6713 return StmtError();
6714 }
6715 }
6716
6717 getCurFunction()->setHasBranchProtectedScope();
6718 return OMPTargetTeamsDistributeParallelForDirective::Create(
6719 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6720}
6721
Kelvin Li1851df52017-01-03 05:23:48 +00006722StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6723 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6724 SourceLocation EndLoc,
6725 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6726 if (!AStmt)
6727 return StmtError();
6728
6729 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6730 // 1.2.2 OpenMP Language Terminology
6731 // Structured block - An executable statement with a single entry at the
6732 // top and a single exit at the bottom.
6733 // The point of exit cannot be a branch out of the structured block.
6734 // longjmp() and throw() must not violate the entry/exit criteria.
6735 CS->getCapturedDecl()->setNothrow();
6736
6737 OMPLoopDirective::HelperExprs B;
6738 // In presence of clause 'collapse' with number of loops, it will
6739 // define the nested loops number.
6740 auto NestedLoopCount = CheckOpenMPLoop(
6741 OMPD_target_teams_distribute_parallel_for_simd,
6742 getCollapseNumberExpr(Clauses),
6743 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6744 VarsWithImplicitDSA, B);
6745 if (NestedLoopCount == 0)
6746 return StmtError();
6747
6748 assert((CurContext->isDependentContext() || B.builtAll()) &&
6749 "omp target teams distribute parallel for simd loop exprs were not "
6750 "built");
6751
6752 if (!CurContext->isDependentContext()) {
6753 // Finalize the clauses that need pre-built expressions for CodeGen.
6754 for (auto C : Clauses) {
6755 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6756 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6757 B.NumIterations, *this, CurScope,
6758 DSAStack))
6759 return StmtError();
6760 }
6761 }
6762
6763 getCurFunction()->setHasBranchProtectedScope();
6764 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6765 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6766}
6767
Kelvin Lida681182017-01-10 18:08:18 +00006768StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6769 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6770 SourceLocation EndLoc,
6771 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6772 if (!AStmt)
6773 return StmtError();
6774
6775 auto *CS = cast<CapturedStmt>(AStmt);
6776 // 1.2.2 OpenMP Language Terminology
6777 // Structured block - An executable statement with a single entry at the
6778 // top and a single exit at the bottom.
6779 // The point of exit cannot be a branch out of the structured block.
6780 // longjmp() and throw() must not violate the entry/exit criteria.
6781 CS->getCapturedDecl()->setNothrow();
6782
6783 OMPLoopDirective::HelperExprs B;
6784 // In presence of clause 'collapse' with number of loops, it will
6785 // define the nested loops number.
6786 auto NestedLoopCount = CheckOpenMPLoop(
6787 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6788 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6789 VarsWithImplicitDSA, B);
6790 if (NestedLoopCount == 0)
6791 return StmtError();
6792
6793 assert((CurContext->isDependentContext() || B.builtAll()) &&
6794 "omp target teams distribute simd loop exprs were not built");
6795
6796 getCurFunction()->setHasBranchProtectedScope();
6797 return OMPTargetTeamsDistributeSimdDirective::Create(
6798 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6799}
6800
Alexey Bataeved09d242014-05-28 05:53:51 +00006801OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006802 SourceLocation StartLoc,
6803 SourceLocation LParenLoc,
6804 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006805 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006806 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006807 case OMPC_final:
6808 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6809 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006810 case OMPC_num_threads:
6811 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6812 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006813 case OMPC_safelen:
6814 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6815 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006816 case OMPC_simdlen:
6817 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6818 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006819 case OMPC_collapse:
6820 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6821 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006822 case OMPC_ordered:
6823 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6824 break;
Michael Wonge710d542015-08-07 16:16:36 +00006825 case OMPC_device:
6826 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6827 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006828 case OMPC_num_teams:
6829 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6830 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006831 case OMPC_thread_limit:
6832 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6833 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006834 case OMPC_priority:
6835 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6836 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006837 case OMPC_grainsize:
6838 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6839 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006840 case OMPC_num_tasks:
6841 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6842 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006843 case OMPC_hint:
6844 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6845 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006846 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006847 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006848 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006849 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006850 case OMPC_private:
6851 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006852 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006853 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006854 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00006855 case OMPC_task_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006856 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006857 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006858 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006859 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006860 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006861 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006862 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006863 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006864 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006865 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006866 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006867 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006868 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006869 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006870 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006871 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006872 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006873 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006874 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006875 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006876 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006877 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006878 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006879 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006880 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006881 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006882 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006883 llvm_unreachable("Clause is not allowed.");
6884 }
6885 return Res;
6886}
6887
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006888// An OpenMP directive such as 'target parallel' has two captured regions:
6889// for the 'target' and 'parallel' respectively. This function returns
6890// the region in which to capture expressions associated with a clause.
6891// A return value of OMPD_unknown signifies that the expression should not
6892// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006893static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6894 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6895 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006896 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6897
6898 switch (CKind) {
6899 case OMPC_if:
6900 switch (DKind) {
6901 case OMPD_target_parallel:
6902 // If this clause applies to the nested 'parallel' region, capture within
6903 // the 'target' region, otherwise do not capture.
6904 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6905 CaptureRegion = OMPD_target;
6906 break;
6907 case OMPD_cancel:
6908 case OMPD_parallel:
6909 case OMPD_parallel_sections:
6910 case OMPD_parallel_for:
6911 case OMPD_parallel_for_simd:
6912 case OMPD_target:
6913 case OMPD_target_simd:
6914 case OMPD_target_parallel_for:
6915 case OMPD_target_parallel_for_simd:
6916 case OMPD_target_teams:
6917 case OMPD_target_teams_distribute:
6918 case OMPD_target_teams_distribute_simd:
6919 case OMPD_target_teams_distribute_parallel_for:
6920 case OMPD_target_teams_distribute_parallel_for_simd:
6921 case OMPD_teams_distribute_parallel_for:
6922 case OMPD_teams_distribute_parallel_for_simd:
6923 case OMPD_distribute_parallel_for:
6924 case OMPD_distribute_parallel_for_simd:
6925 case OMPD_task:
6926 case OMPD_taskloop:
6927 case OMPD_taskloop_simd:
6928 case OMPD_target_data:
6929 case OMPD_target_enter_data:
6930 case OMPD_target_exit_data:
6931 case OMPD_target_update:
6932 // Do not capture if-clause expressions.
6933 break;
6934 case OMPD_threadprivate:
6935 case OMPD_taskyield:
6936 case OMPD_barrier:
6937 case OMPD_taskwait:
6938 case OMPD_cancellation_point:
6939 case OMPD_flush:
6940 case OMPD_declare_reduction:
6941 case OMPD_declare_simd:
6942 case OMPD_declare_target:
6943 case OMPD_end_declare_target:
6944 case OMPD_teams:
6945 case OMPD_simd:
6946 case OMPD_for:
6947 case OMPD_for_simd:
6948 case OMPD_sections:
6949 case OMPD_section:
6950 case OMPD_single:
6951 case OMPD_master:
6952 case OMPD_critical:
6953 case OMPD_taskgroup:
6954 case OMPD_distribute:
6955 case OMPD_ordered:
6956 case OMPD_atomic:
6957 case OMPD_distribute_simd:
6958 case OMPD_teams_distribute:
6959 case OMPD_teams_distribute_simd:
6960 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6961 case OMPD_unknown:
6962 llvm_unreachable("Unknown OpenMP directive");
6963 }
6964 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006965 case OMPC_num_threads:
6966 switch (DKind) {
6967 case OMPD_target_parallel:
6968 CaptureRegion = OMPD_target;
6969 break;
6970 case OMPD_cancel:
6971 case OMPD_parallel:
6972 case OMPD_parallel_sections:
6973 case OMPD_parallel_for:
6974 case OMPD_parallel_for_simd:
6975 case OMPD_target:
6976 case OMPD_target_simd:
6977 case OMPD_target_parallel_for:
6978 case OMPD_target_parallel_for_simd:
6979 case OMPD_target_teams:
6980 case OMPD_target_teams_distribute:
6981 case OMPD_target_teams_distribute_simd:
6982 case OMPD_target_teams_distribute_parallel_for:
6983 case OMPD_target_teams_distribute_parallel_for_simd:
6984 case OMPD_teams_distribute_parallel_for:
6985 case OMPD_teams_distribute_parallel_for_simd:
6986 case OMPD_distribute_parallel_for:
6987 case OMPD_distribute_parallel_for_simd:
6988 case OMPD_task:
6989 case OMPD_taskloop:
6990 case OMPD_taskloop_simd:
6991 case OMPD_target_data:
6992 case OMPD_target_enter_data:
6993 case OMPD_target_exit_data:
6994 case OMPD_target_update:
6995 // Do not capture num_threads-clause expressions.
6996 break;
6997 case OMPD_threadprivate:
6998 case OMPD_taskyield:
6999 case OMPD_barrier:
7000 case OMPD_taskwait:
7001 case OMPD_cancellation_point:
7002 case OMPD_flush:
7003 case OMPD_declare_reduction:
7004 case OMPD_declare_simd:
7005 case OMPD_declare_target:
7006 case OMPD_end_declare_target:
7007 case OMPD_teams:
7008 case OMPD_simd:
7009 case OMPD_for:
7010 case OMPD_for_simd:
7011 case OMPD_sections:
7012 case OMPD_section:
7013 case OMPD_single:
7014 case OMPD_master:
7015 case OMPD_critical:
7016 case OMPD_taskgroup:
7017 case OMPD_distribute:
7018 case OMPD_ordered:
7019 case OMPD_atomic:
7020 case OMPD_distribute_simd:
7021 case OMPD_teams_distribute:
7022 case OMPD_teams_distribute_simd:
7023 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7024 case OMPD_unknown:
7025 llvm_unreachable("Unknown OpenMP directive");
7026 }
7027 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007028 case OMPC_num_teams:
7029 switch (DKind) {
7030 case OMPD_target_teams:
7031 CaptureRegion = OMPD_target;
7032 break;
7033 case OMPD_cancel:
7034 case OMPD_parallel:
7035 case OMPD_parallel_sections:
7036 case OMPD_parallel_for:
7037 case OMPD_parallel_for_simd:
7038 case OMPD_target:
7039 case OMPD_target_simd:
7040 case OMPD_target_parallel:
7041 case OMPD_target_parallel_for:
7042 case OMPD_target_parallel_for_simd:
7043 case OMPD_target_teams_distribute:
7044 case OMPD_target_teams_distribute_simd:
7045 case OMPD_target_teams_distribute_parallel_for:
7046 case OMPD_target_teams_distribute_parallel_for_simd:
7047 case OMPD_teams_distribute_parallel_for:
7048 case OMPD_teams_distribute_parallel_for_simd:
7049 case OMPD_distribute_parallel_for:
7050 case OMPD_distribute_parallel_for_simd:
7051 case OMPD_task:
7052 case OMPD_taskloop:
7053 case OMPD_taskloop_simd:
7054 case OMPD_target_data:
7055 case OMPD_target_enter_data:
7056 case OMPD_target_exit_data:
7057 case OMPD_target_update:
7058 case OMPD_teams:
7059 case OMPD_teams_distribute:
7060 case OMPD_teams_distribute_simd:
7061 // Do not capture num_teams-clause expressions.
7062 break;
7063 case OMPD_threadprivate:
7064 case OMPD_taskyield:
7065 case OMPD_barrier:
7066 case OMPD_taskwait:
7067 case OMPD_cancellation_point:
7068 case OMPD_flush:
7069 case OMPD_declare_reduction:
7070 case OMPD_declare_simd:
7071 case OMPD_declare_target:
7072 case OMPD_end_declare_target:
7073 case OMPD_simd:
7074 case OMPD_for:
7075 case OMPD_for_simd:
7076 case OMPD_sections:
7077 case OMPD_section:
7078 case OMPD_single:
7079 case OMPD_master:
7080 case OMPD_critical:
7081 case OMPD_taskgroup:
7082 case OMPD_distribute:
7083 case OMPD_ordered:
7084 case OMPD_atomic:
7085 case OMPD_distribute_simd:
7086 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7087 case OMPD_unknown:
7088 llvm_unreachable("Unknown OpenMP directive");
7089 }
7090 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007091 case OMPC_thread_limit:
7092 switch (DKind) {
7093 case OMPD_target_teams:
7094 CaptureRegion = OMPD_target;
7095 break;
7096 case OMPD_cancel:
7097 case OMPD_parallel:
7098 case OMPD_parallel_sections:
7099 case OMPD_parallel_for:
7100 case OMPD_parallel_for_simd:
7101 case OMPD_target:
7102 case OMPD_target_simd:
7103 case OMPD_target_parallel:
7104 case OMPD_target_parallel_for:
7105 case OMPD_target_parallel_for_simd:
7106 case OMPD_target_teams_distribute:
7107 case OMPD_target_teams_distribute_simd:
7108 case OMPD_target_teams_distribute_parallel_for:
7109 case OMPD_target_teams_distribute_parallel_for_simd:
7110 case OMPD_teams_distribute_parallel_for:
7111 case OMPD_teams_distribute_parallel_for_simd:
7112 case OMPD_distribute_parallel_for:
7113 case OMPD_distribute_parallel_for_simd:
7114 case OMPD_task:
7115 case OMPD_taskloop:
7116 case OMPD_taskloop_simd:
7117 case OMPD_target_data:
7118 case OMPD_target_enter_data:
7119 case OMPD_target_exit_data:
7120 case OMPD_target_update:
7121 case OMPD_teams:
7122 case OMPD_teams_distribute:
7123 case OMPD_teams_distribute_simd:
7124 // Do not capture thread_limit-clause expressions.
7125 break;
7126 case OMPD_threadprivate:
7127 case OMPD_taskyield:
7128 case OMPD_barrier:
7129 case OMPD_taskwait:
7130 case OMPD_cancellation_point:
7131 case OMPD_flush:
7132 case OMPD_declare_reduction:
7133 case OMPD_declare_simd:
7134 case OMPD_declare_target:
7135 case OMPD_end_declare_target:
7136 case OMPD_simd:
7137 case OMPD_for:
7138 case OMPD_for_simd:
7139 case OMPD_sections:
7140 case OMPD_section:
7141 case OMPD_single:
7142 case OMPD_master:
7143 case OMPD_critical:
7144 case OMPD_taskgroup:
7145 case OMPD_distribute:
7146 case OMPD_ordered:
7147 case OMPD_atomic:
7148 case OMPD_distribute_simd:
7149 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7150 case OMPD_unknown:
7151 llvm_unreachable("Unknown OpenMP directive");
7152 }
7153 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007154 case OMPC_schedule:
7155 case OMPC_dist_schedule:
7156 case OMPC_firstprivate:
7157 case OMPC_lastprivate:
7158 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007159 case OMPC_task_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007160 case OMPC_linear:
7161 case OMPC_default:
7162 case OMPC_proc_bind:
7163 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007164 case OMPC_safelen:
7165 case OMPC_simdlen:
7166 case OMPC_collapse:
7167 case OMPC_private:
7168 case OMPC_shared:
7169 case OMPC_aligned:
7170 case OMPC_copyin:
7171 case OMPC_copyprivate:
7172 case OMPC_ordered:
7173 case OMPC_nowait:
7174 case OMPC_untied:
7175 case OMPC_mergeable:
7176 case OMPC_threadprivate:
7177 case OMPC_flush:
7178 case OMPC_read:
7179 case OMPC_write:
7180 case OMPC_update:
7181 case OMPC_capture:
7182 case OMPC_seq_cst:
7183 case OMPC_depend:
7184 case OMPC_device:
7185 case OMPC_threads:
7186 case OMPC_simd:
7187 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007188 case OMPC_priority:
7189 case OMPC_grainsize:
7190 case OMPC_nogroup:
7191 case OMPC_num_tasks:
7192 case OMPC_hint:
7193 case OMPC_defaultmap:
7194 case OMPC_unknown:
7195 case OMPC_uniform:
7196 case OMPC_to:
7197 case OMPC_from:
7198 case OMPC_use_device_ptr:
7199 case OMPC_is_device_ptr:
7200 llvm_unreachable("Unexpected OpenMP clause.");
7201 }
7202 return CaptureRegion;
7203}
7204
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007205OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7206 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007207 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007208 SourceLocation NameModifierLoc,
7209 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007210 SourceLocation EndLoc) {
7211 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007212 Stmt *HelperValStmt = nullptr;
7213 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007214 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7215 !Condition->isInstantiationDependent() &&
7216 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007217 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007218 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007219 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007220
Richard Smith03a4aa32016-06-23 19:02:52 +00007221 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007222
7223 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7224 CaptureRegion =
7225 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7226 if (CaptureRegion != OMPD_unknown) {
7227 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7228 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7229 HelperValStmt = buildPreInits(Context, Captures);
7230 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007231 }
7232
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007233 return new (Context)
7234 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7235 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007236}
7237
Alexey Bataev3778b602014-07-17 07:32:53 +00007238OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7239 SourceLocation StartLoc,
7240 SourceLocation LParenLoc,
7241 SourceLocation EndLoc) {
7242 Expr *ValExpr = Condition;
7243 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7244 !Condition->isInstantiationDependent() &&
7245 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007246 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007247 if (Val.isInvalid())
7248 return nullptr;
7249
Richard Smith03a4aa32016-06-23 19:02:52 +00007250 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007251 }
7252
7253 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7254}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007255ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7256 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007257 if (!Op)
7258 return ExprError();
7259
7260 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7261 public:
7262 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007263 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007264 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7265 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007266 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7267 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007268 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7269 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007270 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7271 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007272 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7273 QualType T,
7274 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007275 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7276 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007277 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7278 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007279 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007280 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007281 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007282 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7283 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007284 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7285 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007286 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7287 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007288 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007289 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007290 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007291 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7292 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007293 llvm_unreachable("conversion functions are permitted");
7294 }
7295 } ConvertDiagnoser;
7296 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7297}
7298
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007299static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007300 OpenMPClauseKind CKind,
7301 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007302 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7303 !ValExpr->isInstantiationDependent()) {
7304 SourceLocation Loc = ValExpr->getExprLoc();
7305 ExprResult Value =
7306 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7307 if (Value.isInvalid())
7308 return false;
7309
7310 ValExpr = Value.get();
7311 // The expression must evaluate to a non-negative integer value.
7312 llvm::APSInt Result;
7313 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007314 Result.isSigned() &&
7315 !((!StrictlyPositive && Result.isNonNegative()) ||
7316 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007317 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007318 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7319 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007320 return false;
7321 }
7322 }
7323 return true;
7324}
7325
Alexey Bataev568a8332014-03-06 06:15:19 +00007326OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7327 SourceLocation StartLoc,
7328 SourceLocation LParenLoc,
7329 SourceLocation EndLoc) {
7330 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007331 Stmt *HelperValStmt = nullptr;
7332 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007333
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007334 // OpenMP [2.5, Restrictions]
7335 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007336 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7337 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007338 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007339
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007340 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7341 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7342 if (CaptureRegion != OMPD_unknown) {
7343 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7344 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7345 HelperValStmt = buildPreInits(Context, Captures);
7346 }
7347
7348 return new (Context) OMPNumThreadsClause(
7349 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007350}
7351
Alexey Bataev62c87d22014-03-21 04:51:18 +00007352ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007353 OpenMPClauseKind CKind,
7354 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007355 if (!E)
7356 return ExprError();
7357 if (E->isValueDependent() || E->isTypeDependent() ||
7358 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007359 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007360 llvm::APSInt Result;
7361 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7362 if (ICE.isInvalid())
7363 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007364 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7365 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007366 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007367 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7368 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007369 return ExprError();
7370 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007371 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7372 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7373 << E->getSourceRange();
7374 return ExprError();
7375 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007376 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7377 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007378 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007379 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007380 return ICE;
7381}
7382
7383OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7384 SourceLocation LParenLoc,
7385 SourceLocation EndLoc) {
7386 // OpenMP [2.8.1, simd construct, Description]
7387 // The parameter of the safelen clause must be a constant
7388 // positive integer expression.
7389 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7390 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007391 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007392 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007393 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007394}
7395
Alexey Bataev66b15b52015-08-21 11:14:16 +00007396OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7397 SourceLocation LParenLoc,
7398 SourceLocation EndLoc) {
7399 // OpenMP [2.8.1, simd construct, Description]
7400 // The parameter of the simdlen clause must be a constant
7401 // positive integer expression.
7402 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7403 if (Simdlen.isInvalid())
7404 return nullptr;
7405 return new (Context)
7406 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7407}
7408
Alexander Musman64d33f12014-06-04 07:53:32 +00007409OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7410 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007411 SourceLocation LParenLoc,
7412 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007413 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007414 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007415 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007416 // The parameter of the collapse clause must be a constant
7417 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007418 ExprResult NumForLoopsResult =
7419 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7420 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007421 return nullptr;
7422 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007423 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007424}
7425
Alexey Bataev10e775f2015-07-30 11:36:16 +00007426OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7427 SourceLocation EndLoc,
7428 SourceLocation LParenLoc,
7429 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007430 // OpenMP [2.7.1, loop construct, Description]
7431 // OpenMP [2.8.1, simd construct, Description]
7432 // OpenMP [2.9.6, distribute construct, Description]
7433 // The parameter of the ordered clause must be a constant
7434 // positive integer expression if any.
7435 if (NumForLoops && LParenLoc.isValid()) {
7436 ExprResult NumForLoopsResult =
7437 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7438 if (NumForLoopsResult.isInvalid())
7439 return nullptr;
7440 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007441 } else
7442 NumForLoops = nullptr;
7443 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007444 return new (Context)
7445 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7446}
7447
Alexey Bataeved09d242014-05-28 05:53:51 +00007448OMPClause *Sema::ActOnOpenMPSimpleClause(
7449 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7450 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007451 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007452 switch (Kind) {
7453 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007454 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007455 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7456 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007457 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007458 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007459 Res = ActOnOpenMPProcBindClause(
7460 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7461 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007462 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007463 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007464 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007465 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007466 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007467 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007468 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007469 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007470 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007471 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007472 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007473 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007474 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007475 case OMPC_task_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007476 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007477 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007478 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007479 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007480 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007481 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007482 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007483 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007484 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007485 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007486 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007487 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007488 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007489 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007490 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007491 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007492 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007493 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007494 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007495 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007496 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007497 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007498 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007499 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007500 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007501 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007502 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007503 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007504 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007505 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007506 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007507 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007508 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007509 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007510 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007511 llvm_unreachable("Clause is not allowed.");
7512 }
7513 return Res;
7514}
7515
Alexey Bataev6402bca2015-12-28 07:25:51 +00007516static std::string
7517getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7518 ArrayRef<unsigned> Exclude = llvm::None) {
7519 std::string Values;
7520 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7521 unsigned Skipped = Exclude.size();
7522 auto S = Exclude.begin(), E = Exclude.end();
7523 for (unsigned i = First; i < Last; ++i) {
7524 if (std::find(S, E, i) != E) {
7525 --Skipped;
7526 continue;
7527 }
7528 Values += "'";
7529 Values += getOpenMPSimpleClauseTypeName(K, i);
7530 Values += "'";
7531 if (i == Bound - Skipped)
7532 Values += " or ";
7533 else if (i != Bound + 1 - Skipped)
7534 Values += ", ";
7535 }
7536 return Values;
7537}
7538
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007539OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7540 SourceLocation KindKwLoc,
7541 SourceLocation StartLoc,
7542 SourceLocation LParenLoc,
7543 SourceLocation EndLoc) {
7544 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007545 static_assert(OMPC_DEFAULT_unknown > 0,
7546 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007547 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007548 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7549 /*Last=*/OMPC_DEFAULT_unknown)
7550 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007551 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007552 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007553 switch (Kind) {
7554 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007555 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007556 break;
7557 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007558 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007559 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007560 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007561 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007562 break;
7563 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007564 return new (Context)
7565 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007566}
7567
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007568OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7569 SourceLocation KindKwLoc,
7570 SourceLocation StartLoc,
7571 SourceLocation LParenLoc,
7572 SourceLocation EndLoc) {
7573 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007574 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007575 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7576 /*Last=*/OMPC_PROC_BIND_unknown)
7577 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007578 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007579 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007580 return new (Context)
7581 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007582}
7583
Alexey Bataev56dafe82014-06-20 07:16:17 +00007584OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007585 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007586 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007587 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007588 SourceLocation EndLoc) {
7589 OMPClause *Res = nullptr;
7590 switch (Kind) {
7591 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007592 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7593 assert(Argument.size() == NumberOfElements &&
7594 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007595 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007596 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7597 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7598 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7599 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7600 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007601 break;
7602 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007603 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7604 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7605 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7606 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007607 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007608 case OMPC_dist_schedule:
7609 Res = ActOnOpenMPDistScheduleClause(
7610 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7611 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7612 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007613 case OMPC_defaultmap:
7614 enum { Modifier, DefaultmapKind };
7615 Res = ActOnOpenMPDefaultmapClause(
7616 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7617 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007618 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7619 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007620 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007621 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007622 case OMPC_num_threads:
7623 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007624 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007625 case OMPC_collapse:
7626 case OMPC_default:
7627 case OMPC_proc_bind:
7628 case OMPC_private:
7629 case OMPC_firstprivate:
7630 case OMPC_lastprivate:
7631 case OMPC_shared:
7632 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007633 case OMPC_task_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007634 case OMPC_linear:
7635 case OMPC_aligned:
7636 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007637 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007638 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007639 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007640 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007641 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007642 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007643 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007644 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007645 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007646 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007647 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007648 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007649 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007650 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007651 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007652 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007653 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007654 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007655 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007656 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007657 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007658 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007659 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007660 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007661 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007662 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007663 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007664 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007665 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007666 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007667 llvm_unreachable("Clause is not allowed.");
7668 }
7669 return Res;
7670}
7671
Alexey Bataev6402bca2015-12-28 07:25:51 +00007672static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7673 OpenMPScheduleClauseModifier M2,
7674 SourceLocation M1Loc, SourceLocation M2Loc) {
7675 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7676 SmallVector<unsigned, 2> Excluded;
7677 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7678 Excluded.push_back(M2);
7679 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7680 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7681 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7682 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7683 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7684 << getListOfPossibleValues(OMPC_schedule,
7685 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7686 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7687 Excluded)
7688 << getOpenMPClauseName(OMPC_schedule);
7689 return true;
7690 }
7691 return false;
7692}
7693
Alexey Bataev56dafe82014-06-20 07:16:17 +00007694OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007695 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007696 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007697 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7698 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7699 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7700 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7701 return nullptr;
7702 // OpenMP, 2.7.1, Loop Construct, Restrictions
7703 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7704 // but not both.
7705 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7706 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7707 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7708 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7709 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7710 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7711 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7712 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7713 return nullptr;
7714 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007715 if (Kind == OMPC_SCHEDULE_unknown) {
7716 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007717 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7718 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7719 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7720 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7721 Exclude);
7722 } else {
7723 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7724 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007725 }
7726 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7727 << Values << getOpenMPClauseName(OMPC_schedule);
7728 return nullptr;
7729 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007730 // OpenMP, 2.7.1, Loop Construct, Restrictions
7731 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7732 // schedule(guided).
7733 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7734 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7735 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7736 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7737 diag::err_omp_schedule_nonmonotonic_static);
7738 return nullptr;
7739 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007740 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007741 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007742 if (ChunkSize) {
7743 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7744 !ChunkSize->isInstantiationDependent() &&
7745 !ChunkSize->containsUnexpandedParameterPack()) {
7746 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7747 ExprResult Val =
7748 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7749 if (Val.isInvalid())
7750 return nullptr;
7751
7752 ValExpr = Val.get();
7753
7754 // OpenMP [2.7.1, Restrictions]
7755 // chunk_size must be a loop invariant integer expression with a positive
7756 // value.
7757 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007758 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7759 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7760 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007761 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007762 return nullptr;
7763 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007764 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7765 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007766 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7767 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7768 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007769 }
7770 }
7771 }
7772
Alexey Bataev6402bca2015-12-28 07:25:51 +00007773 return new (Context)
7774 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007775 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007776}
7777
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007778OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7779 SourceLocation StartLoc,
7780 SourceLocation EndLoc) {
7781 OMPClause *Res = nullptr;
7782 switch (Kind) {
7783 case OMPC_ordered:
7784 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7785 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007786 case OMPC_nowait:
7787 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7788 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007789 case OMPC_untied:
7790 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7791 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007792 case OMPC_mergeable:
7793 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7794 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007795 case OMPC_read:
7796 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7797 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007798 case OMPC_write:
7799 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7800 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007801 case OMPC_update:
7802 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7803 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007804 case OMPC_capture:
7805 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7806 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007807 case OMPC_seq_cst:
7808 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7809 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007810 case OMPC_threads:
7811 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7812 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007813 case OMPC_simd:
7814 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7815 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007816 case OMPC_nogroup:
7817 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7818 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007819 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007820 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007821 case OMPC_num_threads:
7822 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007823 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007824 case OMPC_collapse:
7825 case OMPC_schedule:
7826 case OMPC_private:
7827 case OMPC_firstprivate:
7828 case OMPC_lastprivate:
7829 case OMPC_shared:
7830 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007831 case OMPC_task_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007832 case OMPC_linear:
7833 case OMPC_aligned:
7834 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007835 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007836 case OMPC_default:
7837 case OMPC_proc_bind:
7838 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007839 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007840 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007841 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007842 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007843 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007844 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007845 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007846 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007847 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007848 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007849 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007850 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007851 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007852 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007853 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007854 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007855 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007856 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007857 llvm_unreachable("Clause is not allowed.");
7858 }
7859 return Res;
7860}
7861
Alexey Bataev236070f2014-06-20 11:19:47 +00007862OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7863 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007864 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007865 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7866}
7867
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007868OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7869 SourceLocation EndLoc) {
7870 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7871}
7872
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007873OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7874 SourceLocation EndLoc) {
7875 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7876}
7877
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007878OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7879 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007880 return new (Context) OMPReadClause(StartLoc, EndLoc);
7881}
7882
Alexey Bataevdea47612014-07-23 07:46:59 +00007883OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7884 SourceLocation EndLoc) {
7885 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7886}
7887
Alexey Bataev67a4f222014-07-23 10:25:33 +00007888OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7889 SourceLocation EndLoc) {
7890 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7891}
7892
Alexey Bataev459dec02014-07-24 06:46:57 +00007893OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7894 SourceLocation EndLoc) {
7895 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7896}
7897
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007898OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7899 SourceLocation EndLoc) {
7900 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7901}
7902
Alexey Bataev346265e2015-09-25 10:37:12 +00007903OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7904 SourceLocation EndLoc) {
7905 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7906}
7907
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007908OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7909 SourceLocation EndLoc) {
7910 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7911}
7912
Alexey Bataevb825de12015-12-07 10:51:44 +00007913OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7914 SourceLocation EndLoc) {
7915 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7916}
7917
Alexey Bataevc5e02582014-06-16 07:08:35 +00007918OMPClause *Sema::ActOnOpenMPVarListClause(
7919 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7920 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7921 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007922 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007923 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7924 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7925 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007926 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007927 switch (Kind) {
7928 case OMPC_private:
7929 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7930 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007931 case OMPC_firstprivate:
7932 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7933 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007934 case OMPC_lastprivate:
7935 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7936 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007937 case OMPC_shared:
7938 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7939 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007940 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007941 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7942 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007943 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00007944 case OMPC_task_reduction:
7945 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7946 EndLoc, ReductionIdScopeSpec,
7947 ReductionId);
7948 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007949 case OMPC_linear:
7950 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007951 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007952 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007953 case OMPC_aligned:
7954 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7955 ColonLoc, EndLoc);
7956 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007957 case OMPC_copyin:
7958 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7959 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007960 case OMPC_copyprivate:
7961 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7962 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007963 case OMPC_flush:
7964 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7965 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007966 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007967 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007968 StartLoc, LParenLoc, EndLoc);
7969 break;
7970 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007971 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7972 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7973 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007974 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007975 case OMPC_to:
7976 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7977 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007978 case OMPC_from:
7979 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7980 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007981 case OMPC_use_device_ptr:
7982 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7983 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007984 case OMPC_is_device_ptr:
7985 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7986 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007987 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007988 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007989 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007990 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007991 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007992 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007993 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007994 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007995 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007996 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007997 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007998 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007999 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008000 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008001 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008002 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008003 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008004 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008005 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008006 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008007 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008008 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008009 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008010 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008011 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008012 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008013 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008014 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008015 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008016 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008017 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008018 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008019 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008020 llvm_unreachable("Clause is not allowed.");
8021 }
8022 return Res;
8023}
8024
Alexey Bataev90c228f2016-02-08 09:29:13 +00008025ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008026 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008027 ExprResult Res = BuildDeclRefExpr(
8028 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8029 if (!Res.isUsable())
8030 return ExprError();
8031 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8032 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8033 if (!Res.isUsable())
8034 return ExprError();
8035 }
8036 if (VK != VK_LValue && Res.get()->isGLValue()) {
8037 Res = DefaultLvalueConversion(Res.get());
8038 if (!Res.isUsable())
8039 return ExprError();
8040 }
8041 return Res;
8042}
8043
Alexey Bataev60da77e2016-02-29 05:54:20 +00008044static std::pair<ValueDecl *, bool>
8045getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8046 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008047 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8048 RefExpr->containsUnexpandedParameterPack())
8049 return std::make_pair(nullptr, true);
8050
Alexey Bataevd985eda2016-02-10 11:29:16 +00008051 // OpenMP [3.1, C/C++]
8052 // A list item is a variable name.
8053 // OpenMP [2.9.3.3, Restrictions, p.1]
8054 // A variable that is part of another variable (as an array or
8055 // structure element) cannot appear in a private clause.
8056 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008057 enum {
8058 NoArrayExpr = -1,
8059 ArraySubscript = 0,
8060 OMPArraySection = 1
8061 } IsArrayExpr = NoArrayExpr;
8062 if (AllowArraySection) {
8063 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8064 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8065 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8066 Base = TempASE->getBase()->IgnoreParenImpCasts();
8067 RefExpr = Base;
8068 IsArrayExpr = ArraySubscript;
8069 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8070 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8071 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8072 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8073 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8074 Base = TempASE->getBase()->IgnoreParenImpCasts();
8075 RefExpr = Base;
8076 IsArrayExpr = OMPArraySection;
8077 }
8078 }
8079 ELoc = RefExpr->getExprLoc();
8080 ERange = RefExpr->getSourceRange();
8081 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008082 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8083 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8084 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8085 (S.getCurrentThisType().isNull() || !ME ||
8086 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8087 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008088 if (IsArrayExpr != NoArrayExpr)
8089 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8090 << ERange;
8091 else {
8092 S.Diag(ELoc,
8093 AllowArraySection
8094 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8095 : diag::err_omp_expected_var_name_member_expr)
8096 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8097 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008098 return std::make_pair(nullptr, false);
8099 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008100 return std::make_pair(
8101 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008102}
8103
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008104OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8105 SourceLocation StartLoc,
8106 SourceLocation LParenLoc,
8107 SourceLocation EndLoc) {
8108 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008109 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008110 for (auto &RefExpr : VarList) {
8111 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008112 SourceLocation ELoc;
8113 SourceRange ERange;
8114 Expr *SimpleRefExpr = RefExpr;
8115 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008116 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008117 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008118 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008119 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008120 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008121 ValueDecl *D = Res.first;
8122 if (!D)
8123 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008124
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008125 QualType Type = D->getType();
8126 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008127
8128 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8129 // A variable that appears in a private clause must not have an incomplete
8130 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008131 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008132 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008133 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008134
Alexey Bataev758e55e2013-09-06 18:03:48 +00008135 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8136 // in a Construct]
8137 // Variables with the predetermined data-sharing attributes may not be
8138 // listed in data-sharing attributes clauses, except for the cases
8139 // listed below. For these exceptions only, listing a predetermined
8140 // variable in a data-sharing attribute clause is allowed and overrides
8141 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008142 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008143 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008144 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8145 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008146 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008147 continue;
8148 }
8149
Kelvin Libf594a52016-12-17 05:48:59 +00008150 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008151 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008152 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008153 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008154 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8155 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008156 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008157 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008158 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008159 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008160 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008161 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008162 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008163 continue;
8164 }
8165
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008166 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8167 // A list item cannot appear in both a map clause and a data-sharing
8168 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008169 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008170 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008171 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008172 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008173 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008174 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008175 CurrDir == OMPD_target_parallel_for_simd ||
8176 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008177 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008178 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008179 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008180 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8181 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8182 ConflictKind = WhereFoundClauseKind;
8183 return true;
8184 })) {
8185 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008186 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008187 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008188 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008189 ReportOriginalDSA(*this, DSAStack, D, DVar);
8190 continue;
8191 }
8192 }
8193
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008194 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8195 // A variable of class type (or array thereof) that appears in a private
8196 // clause requires an accessible, unambiguous default constructor for the
8197 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008198 // Generate helper private variable and initialize it with the default
8199 // value. The address of the original variable is replaced by the address of
8200 // the new private variable in CodeGen. This new variable is not added to
8201 // IdResolver, so the code in the OpenMP region uses original variable for
8202 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008203 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008204 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8205 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008206 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008207 if (VDPrivate->isInvalidDecl())
8208 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008209 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008210 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008211
Alexey Bataev90c228f2016-02-08 09:29:13 +00008212 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008213 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008214 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008215 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008216 Vars.push_back((VD || CurContext->isDependentContext())
8217 ? RefExpr->IgnoreParens()
8218 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008219 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008220 }
8221
Alexey Bataeved09d242014-05-28 05:53:51 +00008222 if (Vars.empty())
8223 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008224
Alexey Bataev03b340a2014-10-21 03:16:40 +00008225 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8226 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008227}
8228
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008229namespace {
8230class DiagsUninitializedSeveretyRAII {
8231private:
8232 DiagnosticsEngine &Diags;
8233 SourceLocation SavedLoc;
8234 bool IsIgnored;
8235
8236public:
8237 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8238 bool IsIgnored)
8239 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8240 if (!IsIgnored) {
8241 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8242 /*Map*/ diag::Severity::Ignored, Loc);
8243 }
8244 }
8245 ~DiagsUninitializedSeveretyRAII() {
8246 if (!IsIgnored)
8247 Diags.popMappings(SavedLoc);
8248 }
8249};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008250}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008251
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008252OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8253 SourceLocation StartLoc,
8254 SourceLocation LParenLoc,
8255 SourceLocation EndLoc) {
8256 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008257 SmallVector<Expr *, 8> PrivateCopies;
8258 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008259 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008260 bool IsImplicitClause =
8261 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8262 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8263
Alexey Bataeved09d242014-05-28 05:53:51 +00008264 for (auto &RefExpr : VarList) {
8265 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008266 SourceLocation ELoc;
8267 SourceRange ERange;
8268 Expr *SimpleRefExpr = RefExpr;
8269 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008270 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008271 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008272 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008273 PrivateCopies.push_back(nullptr);
8274 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008275 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008276 ValueDecl *D = Res.first;
8277 if (!D)
8278 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008279
Alexey Bataev60da77e2016-02-29 05:54:20 +00008280 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008281 QualType Type = D->getType();
8282 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008283
8284 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8285 // A variable that appears in a private clause must not have an incomplete
8286 // type or a reference type.
8287 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008288 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008289 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008290 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008291
8292 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8293 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008294 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008295 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008296 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008297
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008298 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008299 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008300 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008301 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008302 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008303 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008304 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008305 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8306 // A list item that specifies a given variable may not appear in more
8307 // than one clause on the same directive, except that a variable may be
8308 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008309 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8310 // A list item may appear in a firstprivate or lastprivate clause but not
8311 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008312 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008313 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8314 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008315 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008316 << getOpenMPClauseName(DVar.CKind)
8317 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008318 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008319 continue;
8320 }
8321
8322 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8323 // in a Construct]
8324 // Variables with the predetermined data-sharing attributes may not be
8325 // listed in data-sharing attributes clauses, except for the cases
8326 // listed below. For these exceptions only, listing a predetermined
8327 // variable in a data-sharing attribute clause is allowed and overrides
8328 // the variable's predetermined data-sharing attributes.
8329 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8330 // in a Construct, C/C++, p.2]
8331 // Variables with const-qualified type having no mutable member may be
8332 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008333 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008334 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8335 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008336 << getOpenMPClauseName(DVar.CKind)
8337 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008338 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008339 continue;
8340 }
8341
8342 // OpenMP [2.9.3.4, Restrictions, p.2]
8343 // A list item that is private within a parallel region must not appear
8344 // in a firstprivate clause on a worksharing construct if any of the
8345 // worksharing regions arising from the worksharing construct ever bind
8346 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008347 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8348 // A list item that is private within a teams region must not appear in a
8349 // firstprivate clause on a distribute construct if any of the distribute
8350 // regions arising from the distribute construct ever bind to any of the
8351 // teams regions arising from the teams construct.
8352 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8353 // A list item that appears in a reduction clause of a teams construct
8354 // must not appear in a firstprivate clause on a distribute construct if
8355 // any of the distribute regions arising from the distribute construct
8356 // ever bind to any of the teams regions arising from the teams construct.
8357 if ((isOpenMPWorksharingDirective(CurrDir) ||
8358 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008359 !isOpenMPParallelDirective(CurrDir) &&
8360 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008361 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008362 if (DVar.CKind != OMPC_shared &&
8363 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008364 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008365 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008366 Diag(ELoc, diag::err_omp_required_access)
8367 << getOpenMPClauseName(OMPC_firstprivate)
8368 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008369 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008370 continue;
8371 }
8372 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008373 // OpenMP [2.9.3.4, Restrictions, p.3]
8374 // A list item that appears in a reduction clause of a parallel construct
8375 // must not appear in a firstprivate clause on a worksharing or task
8376 // construct if any of the worksharing or task regions arising from the
8377 // worksharing or task construct ever bind to any of the parallel regions
8378 // arising from the parallel construct.
8379 // OpenMP [2.9.3.4, Restrictions, p.4]
8380 // A list item that appears in a reduction clause in worksharing
8381 // construct must not appear in a firstprivate clause in a task construct
8382 // encountered during execution of any of the worksharing regions arising
8383 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008384 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008385 DVar = DSAStack->hasInnermostDSA(
8386 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8387 [](OpenMPDirectiveKind K) -> bool {
8388 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008389 isOpenMPWorksharingDirective(K) ||
8390 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008391 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008392 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008393 if (DVar.CKind == OMPC_reduction &&
8394 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008395 isOpenMPWorksharingDirective(DVar.DKind) ||
8396 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008397 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8398 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008399 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008400 continue;
8401 }
8402 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008403
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008404 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8405 // A list item cannot appear in both a map clause and a data-sharing
8406 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008407 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008408 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008409 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008410 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008411 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008412 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008413 CurrDir == OMPD_target_parallel_for_simd ||
8414 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008415 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008416 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008417 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008418 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8419 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8420 ConflictKind = WhereFoundClauseKind;
8421 return true;
8422 })) {
8423 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008424 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008425 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008426 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8427 ReportOriginalDSA(*this, DSAStack, D, DVar);
8428 continue;
8429 }
8430 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008431 }
8432
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008433 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008434 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008435 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008436 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8437 << getOpenMPClauseName(OMPC_firstprivate) << Type
8438 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8439 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008440 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008441 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008442 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008443 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008444 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008445 continue;
8446 }
8447
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008448 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008449 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8450 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008451 // Generate helper private variable and initialize it with the value of the
8452 // original variable. The address of the original variable is replaced by
8453 // the address of the new private variable in the CodeGen. This new variable
8454 // is not added to IdResolver, so the code in the OpenMP region uses
8455 // original variable for proper diagnostics and variable capturing.
8456 Expr *VDInitRefExpr = nullptr;
8457 // For arrays generate initializer for single element and replace it by the
8458 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008459 if (Type->isArrayType()) {
8460 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008461 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008462 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008463 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008464 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008465 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008466 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008467 InitializedEntity Entity =
8468 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008469 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8470
8471 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8472 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8473 if (Result.isInvalid())
8474 VDPrivate->setInvalidDecl();
8475 else
8476 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008477 // Remove temp variable declaration.
8478 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008479 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008480 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8481 ".firstprivate.temp");
8482 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8483 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008484 AddInitializerToDecl(VDPrivate,
8485 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008486 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008487 }
8488 if (VDPrivate->isInvalidDecl()) {
8489 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008490 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008491 diag::note_omp_task_predetermined_firstprivate_here);
8492 }
8493 continue;
8494 }
8495 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008496 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008497 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8498 RefExpr->getExprLoc());
8499 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008500 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008501 if (TopDVar.CKind == OMPC_lastprivate)
8502 Ref = TopDVar.PrivateCopy;
8503 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008504 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008505 if (!IsOpenMPCapturedDecl(D))
8506 ExprCaptures.push_back(Ref->getDecl());
8507 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008508 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008509 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008510 Vars.push_back((VD || CurContext->isDependentContext())
8511 ? RefExpr->IgnoreParens()
8512 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008513 PrivateCopies.push_back(VDPrivateRefExpr);
8514 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008515 }
8516
Alexey Bataeved09d242014-05-28 05:53:51 +00008517 if (Vars.empty())
8518 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008519
8520 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008521 Vars, PrivateCopies, Inits,
8522 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008523}
8524
Alexander Musman1bb328c2014-06-04 13:06:39 +00008525OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8526 SourceLocation StartLoc,
8527 SourceLocation LParenLoc,
8528 SourceLocation EndLoc) {
8529 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008530 SmallVector<Expr *, 8> SrcExprs;
8531 SmallVector<Expr *, 8> DstExprs;
8532 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008533 SmallVector<Decl *, 4> ExprCaptures;
8534 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008535 for (auto &RefExpr : VarList) {
8536 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008537 SourceLocation ELoc;
8538 SourceRange ERange;
8539 Expr *SimpleRefExpr = RefExpr;
8540 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008541 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008542 // It will be analyzed later.
8543 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008544 SrcExprs.push_back(nullptr);
8545 DstExprs.push_back(nullptr);
8546 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008547 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008548 ValueDecl *D = Res.first;
8549 if (!D)
8550 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008551
Alexey Bataev74caaf22016-02-20 04:09:36 +00008552 QualType Type = D->getType();
8553 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008554
8555 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8556 // A variable that appears in a lastprivate clause must not have an
8557 // incomplete type or a reference type.
8558 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008559 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008560 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008561 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008562
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008563 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008564 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8565 // in a Construct]
8566 // Variables with the predetermined data-sharing attributes may not be
8567 // listed in data-sharing attributes clauses, except for the cases
8568 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008569 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8570 // A list item may appear in a firstprivate or lastprivate clause but not
8571 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008572 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008573 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008574 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00008575 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8576 Diag(ELoc, diag::err_omp_wrong_dsa)
8577 << getOpenMPClauseName(DVar.CKind)
8578 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008579 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008580 continue;
8581 }
8582
Alexey Bataevf29276e2014-06-18 04:14:57 +00008583 // OpenMP [2.14.3.5, Restrictions, p.2]
8584 // A list item that is private within a parallel region, or that appears in
8585 // the reduction clause of a parallel construct, must not appear in a
8586 // lastprivate clause on a worksharing construct if any of the corresponding
8587 // worksharing regions ever binds to any of the corresponding parallel
8588 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008589 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008590 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008591 !isOpenMPParallelDirective(CurrDir) &&
8592 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008593 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008594 if (DVar.CKind != OMPC_shared) {
8595 Diag(ELoc, diag::err_omp_required_access)
8596 << getOpenMPClauseName(OMPC_lastprivate)
8597 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008598 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008599 continue;
8600 }
8601 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008602
Alexander Musman1bb328c2014-06-04 13:06:39 +00008603 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008604 // A variable of class type (or array thereof) that appears in a
8605 // lastprivate clause requires an accessible, unambiguous default
8606 // constructor for the class type, unless the list item is also specified
8607 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008608 // A variable of class type (or array thereof) that appears in a
8609 // lastprivate clause requires an accessible, unambiguous copy assignment
8610 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008611 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008612 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008613 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008614 D->hasAttrs() ? &D->getAttrs() : nullptr);
8615 auto *PseudoSrcExpr =
8616 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008617 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008618 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008619 D->hasAttrs() ? &D->getAttrs() : nullptr);
8620 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008621 // For arrays generate assignment operation for single element and replace
8622 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008623 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008624 PseudoDstExpr, PseudoSrcExpr);
8625 if (AssignmentOp.isInvalid())
8626 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008627 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008628 /*DiscardedValue=*/true);
8629 if (AssignmentOp.isInvalid())
8630 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008631
Alexey Bataev74caaf22016-02-20 04:09:36 +00008632 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008633 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008634 if (TopDVar.CKind == OMPC_firstprivate)
8635 Ref = TopDVar.PrivateCopy;
8636 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008637 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008638 if (!IsOpenMPCapturedDecl(D))
8639 ExprCaptures.push_back(Ref->getDecl());
8640 }
8641 if (TopDVar.CKind == OMPC_firstprivate ||
8642 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008643 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008644 ExprResult RefRes = DefaultLvalueConversion(Ref);
8645 if (!RefRes.isUsable())
8646 continue;
8647 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008648 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8649 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008650 if (!PostUpdateRes.isUsable())
8651 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008652 ExprPostUpdates.push_back(
8653 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008654 }
8655 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008656 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008657 Vars.push_back((VD || CurContext->isDependentContext())
8658 ? RefExpr->IgnoreParens()
8659 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008660 SrcExprs.push_back(PseudoSrcExpr);
8661 DstExprs.push_back(PseudoDstExpr);
8662 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008663 }
8664
8665 if (Vars.empty())
8666 return nullptr;
8667
8668 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008669 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008670 buildPreInits(Context, ExprCaptures),
8671 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008672}
8673
Alexey Bataev758e55e2013-09-06 18:03:48 +00008674OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8675 SourceLocation StartLoc,
8676 SourceLocation LParenLoc,
8677 SourceLocation EndLoc) {
8678 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008679 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008680 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008681 SourceLocation ELoc;
8682 SourceRange ERange;
8683 Expr *SimpleRefExpr = RefExpr;
8684 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008685 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008686 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008687 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008688 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008689 ValueDecl *D = Res.first;
8690 if (!D)
8691 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008692
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008693 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008694 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8695 // in a Construct]
8696 // Variables with the predetermined data-sharing attributes may not be
8697 // listed in data-sharing attributes clauses, except for the cases
8698 // listed below. For these exceptions only, listing a predetermined
8699 // variable in a data-sharing attribute clause is allowed and overrides
8700 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008701 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008702 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8703 DVar.RefExpr) {
8704 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8705 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008706 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008707 continue;
8708 }
8709
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008710 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008711 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008712 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008713 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008714 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8715 ? RefExpr->IgnoreParens()
8716 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008717 }
8718
Alexey Bataeved09d242014-05-28 05:53:51 +00008719 if (Vars.empty())
8720 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008721
8722 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8723}
8724
Alexey Bataevc5e02582014-06-16 07:08:35 +00008725namespace {
8726class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8727 DSAStackTy *Stack;
8728
8729public:
8730 bool VisitDeclRefExpr(DeclRefExpr *E) {
8731 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008732 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008733 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8734 return false;
8735 if (DVar.CKind != OMPC_unknown)
8736 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008737 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8738 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008739 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008740 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008741 return true;
8742 return false;
8743 }
8744 return false;
8745 }
8746 bool VisitStmt(Stmt *S) {
8747 for (auto Child : S->children()) {
8748 if (Child && Visit(Child))
8749 return true;
8750 }
8751 return false;
8752 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008753 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008754};
Alexey Bataev23b69422014-06-18 07:08:49 +00008755} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008756
Alexey Bataev60da77e2016-02-29 05:54:20 +00008757namespace {
8758// Transform MemberExpression for specified FieldDecl of current class to
8759// DeclRefExpr to specified OMPCapturedExprDecl.
8760class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8761 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8762 ValueDecl *Field;
8763 DeclRefExpr *CapturedExpr;
8764
8765public:
8766 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8767 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8768
8769 ExprResult TransformMemberExpr(MemberExpr *E) {
8770 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8771 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008772 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008773 return CapturedExpr;
8774 }
8775 return BaseTransform::TransformMemberExpr(E);
8776 }
8777 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8778};
8779} // namespace
8780
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008781template <typename T>
8782static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8783 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8784 for (auto &Set : Lookups) {
8785 for (auto *D : Set) {
8786 if (auto Res = Gen(cast<ValueDecl>(D)))
8787 return Res;
8788 }
8789 }
8790 return T();
8791}
8792
8793static ExprResult
8794buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8795 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8796 const DeclarationNameInfo &ReductionId, QualType Ty,
8797 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8798 if (ReductionIdScopeSpec.isInvalid())
8799 return ExprError();
8800 SmallVector<UnresolvedSet<8>, 4> Lookups;
8801 if (S) {
8802 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8803 Lookup.suppressDiagnostics();
8804 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8805 auto *D = Lookup.getRepresentativeDecl();
8806 do {
8807 S = S->getParent();
8808 } while (S && !S->isDeclScope(D));
8809 if (S)
8810 S = S->getParent();
8811 Lookups.push_back(UnresolvedSet<8>());
8812 Lookups.back().append(Lookup.begin(), Lookup.end());
8813 Lookup.clear();
8814 }
8815 } else if (auto *ULE =
8816 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8817 Lookups.push_back(UnresolvedSet<8>());
8818 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008819 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008820 if (D == PrevD)
8821 Lookups.push_back(UnresolvedSet<8>());
8822 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8823 Lookups.back().addDecl(DRD);
8824 PrevD = D;
8825 }
8826 }
8827 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8828 Ty->containsUnexpandedParameterPack() ||
8829 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8830 return !D->isInvalidDecl() &&
8831 (D->getType()->isDependentType() ||
8832 D->getType()->isInstantiationDependentType() ||
8833 D->getType()->containsUnexpandedParameterPack());
8834 })) {
8835 UnresolvedSet<8> ResSet;
8836 for (auto &Set : Lookups) {
8837 ResSet.append(Set.begin(), Set.end());
8838 // The last item marks the end of all declarations at the specified scope.
8839 ResSet.addDecl(Set[Set.size() - 1]);
8840 }
8841 return UnresolvedLookupExpr::Create(
8842 SemaRef.Context, /*NamingClass=*/nullptr,
8843 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8844 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8845 }
8846 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8847 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8848 if (!D->isInvalidDecl() &&
8849 SemaRef.Context.hasSameType(D->getType(), Ty))
8850 return D;
8851 return nullptr;
8852 }))
8853 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8854 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8855 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8856 if (!D->isInvalidDecl() &&
8857 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8858 !Ty.isMoreQualifiedThan(D->getType()))
8859 return D;
8860 return nullptr;
8861 })) {
8862 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8863 /*DetectVirtual=*/false);
8864 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8865 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8866 VD->getType().getUnqualifiedType()))) {
8867 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8868 /*DiagID=*/0) !=
8869 Sema::AR_inaccessible) {
8870 SemaRef.BuildBasePathArray(Paths, BasePath);
8871 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8872 }
8873 }
8874 }
8875 }
8876 if (ReductionIdScopeSpec.isSet()) {
8877 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8878 return ExprError();
8879 }
8880 return ExprEmpty();
8881}
8882
Alexey Bataevfad872fc2017-07-18 15:32:58 +00008883namespace {
8884/// Data for the reduction-based clauses.
8885struct ReductionData {
8886 /// List of original reduction items.
8887 SmallVector<Expr *, 8> Vars;
8888 /// List of private copies of the reduction items.
8889 SmallVector<Expr *, 8> Privates;
8890 /// LHS expressions for the reduction_op expressions.
8891 SmallVector<Expr *, 8> LHSs;
8892 /// RHS expressions for the reduction_op expressions.
8893 SmallVector<Expr *, 8> RHSs;
8894 /// Reduction operation expression.
8895 SmallVector<Expr *, 8> ReductionOps;
8896 /// List of captures for clause.
8897 SmallVector<Decl *, 4> ExprCaptures;
8898 /// List of postupdate expressions.
8899 SmallVector<Expr *, 4> ExprPostUpdates;
8900 ReductionData() = delete;
8901 /// Reserves required memory for the reduction data.
8902 ReductionData(unsigned Size) {
8903 Vars.reserve(Size);
8904 Privates.reserve(Size);
8905 LHSs.reserve(Size);
8906 RHSs.reserve(Size);
8907 ReductionOps.reserve(Size);
8908 ExprCaptures.reserve(Size);
8909 ExprPostUpdates.reserve(Size);
8910 }
8911 /// Stores reduction item and reduction operation only (required for dependent
8912 /// reduction item).
8913 void push(Expr *Item, Expr *ReductionOp) {
8914 Vars.emplace_back(Item);
8915 Privates.emplace_back(nullptr);
8916 LHSs.emplace_back(nullptr);
8917 RHSs.emplace_back(nullptr);
8918 ReductionOps.emplace_back(ReductionOp);
8919 }
8920 /// Stores reduction data.
8921 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS,
8922 Expr *ReductionOp) {
8923 Vars.emplace_back(Item);
8924 Privates.emplace_back(Private);
8925 LHSs.emplace_back(LHS);
8926 RHSs.emplace_back(RHS);
8927 ReductionOps.emplace_back(ReductionOp);
8928 }
8929};
8930} // namespace
8931
8932static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00008933 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
8934 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8935 SourceLocation ColonLoc, SourceLocation EndLoc,
8936 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00008937 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008938 auto DN = ReductionId.getName();
8939 auto OOK = DN.getCXXOverloadedOperator();
8940 BinaryOperatorKind BOK = BO_Comma;
8941
Alexey Bataevfad872fc2017-07-18 15:32:58 +00008942 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008943 // OpenMP [2.14.3.6, reduction clause]
8944 // C
8945 // reduction-identifier is either an identifier or one of the following
8946 // operators: +, -, *, &, |, ^, && and ||
8947 // C++
8948 // reduction-identifier is either an id-expression or one of the following
8949 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00008950 switch (OOK) {
8951 case OO_Plus:
8952 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008953 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008954 break;
8955 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008956 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008957 break;
8958 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008959 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008960 break;
8961 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008962 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008963 break;
8964 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008965 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008966 break;
8967 case OO_AmpAmp:
8968 BOK = BO_LAnd;
8969 break;
8970 case OO_PipePipe:
8971 BOK = BO_LOr;
8972 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008973 case OO_New:
8974 case OO_Delete:
8975 case OO_Array_New:
8976 case OO_Array_Delete:
8977 case OO_Slash:
8978 case OO_Percent:
8979 case OO_Tilde:
8980 case OO_Exclaim:
8981 case OO_Equal:
8982 case OO_Less:
8983 case OO_Greater:
8984 case OO_LessEqual:
8985 case OO_GreaterEqual:
8986 case OO_PlusEqual:
8987 case OO_MinusEqual:
8988 case OO_StarEqual:
8989 case OO_SlashEqual:
8990 case OO_PercentEqual:
8991 case OO_CaretEqual:
8992 case OO_AmpEqual:
8993 case OO_PipeEqual:
8994 case OO_LessLess:
8995 case OO_GreaterGreater:
8996 case OO_LessLessEqual:
8997 case OO_GreaterGreaterEqual:
8998 case OO_EqualEqual:
8999 case OO_ExclaimEqual:
9000 case OO_PlusPlus:
9001 case OO_MinusMinus:
9002 case OO_Comma:
9003 case OO_ArrowStar:
9004 case OO_Arrow:
9005 case OO_Call:
9006 case OO_Subscript:
9007 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009008 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009009 case NUM_OVERLOADED_OPERATORS:
9010 llvm_unreachable("Unexpected reduction identifier");
9011 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009012 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009013 if (II->isStr("max"))
9014 BOK = BO_GT;
9015 else if (II->isStr("min"))
9016 BOK = BO_LT;
9017 }
9018 break;
9019 }
9020 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009021 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009022 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009023 else
9024 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009025 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009026
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009027 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9028 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009029 for (auto RefExpr : VarList) {
9030 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009031 // OpenMP [2.1, C/C++]
9032 // A list item is a variable or array section, subject to the restrictions
9033 // specified in Section 2.4 on page 42 and in each of the sections
9034 // describing clauses and directives for which a list appears.
9035 // OpenMP [2.14.3.3, Restrictions, p.1]
9036 // A variable that is part of another variable (as an array or
9037 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009038 if (!FirstIter && IR != ER)
9039 ++IR;
9040 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009041 SourceLocation ELoc;
9042 SourceRange ERange;
9043 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009044 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009045 /*AllowArraySection=*/true);
9046 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009047 // Try to find 'declare reduction' corresponding construct before using
9048 // builtin/overloaded operators.
9049 QualType Type = Context.DependentTy;
9050 CXXCastPath BasePath;
9051 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009052 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009053 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009054 Expr *ReductionOp = nullptr;
9055 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009056 (DeclareReductionRef.isUnset() ||
9057 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009058 ReductionOp = DeclareReductionRef.get();
9059 // It will be analyzed later.
9060 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009061 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009062 ValueDecl *D = Res.first;
9063 if (!D)
9064 continue;
9065
Alexey Bataeva1764212015-09-30 09:22:36 +00009066 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009067 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9068 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9069 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009070 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009071 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009072 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9073 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9074 Type = ATy->getElementType();
9075 else
9076 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009077 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009078 } else
9079 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9080 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009081
Alexey Bataevc5e02582014-06-16 07:08:35 +00009082 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9083 // A variable that appears in a private clause must not have an incomplete
9084 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009085 if (S.RequireCompleteType(ELoc, Type,
9086 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009087 continue;
9088 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009089 // A list item that appears in a reduction clause must not be
9090 // const-qualified.
9091 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009092 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009093 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009094 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9095 VarDecl::DeclarationOnly;
9096 S.Diag(D->getLocation(),
9097 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009098 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009099 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009100 continue;
9101 }
9102 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9103 // If a list-item is a reference type then it must bind to the same object
9104 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009105 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009106 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009107 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009108 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009109 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009110 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9111 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009112 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009113 continue;
9114 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009115 }
9116 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009117
Alexey Bataevc5e02582014-06-16 07:08:35 +00009118 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9119 // in a Construct]
9120 // Variables with the predetermined data-sharing attributes may not be
9121 // listed in data-sharing attributes clauses, except for the cases
9122 // listed below. For these exceptions only, listing a predetermined
9123 // variable in a data-sharing attribute clause is allowed and overrides
9124 // the variable's predetermined data-sharing attributes.
9125 // OpenMP [2.14.3.6, Restrictions, p.3]
9126 // Any number of reduction clauses can be specified on the directive,
9127 // but a list item can appear only once in the reduction clauses for that
9128 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009129 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009130 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009131 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009132 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009133 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009134 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009135 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009136 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009137 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009138 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009139 << getOpenMPClauseName(DVar.CKind)
9140 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009141 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009142 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009143 }
9144
9145 // OpenMP [2.14.3.6, Restrictions, p.1]
9146 // A list item that appears in a reduction clause of a worksharing
9147 // construct must be shared in the parallel regions to which any of the
9148 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009149 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009150 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009151 !isOpenMPParallelDirective(CurrDir) &&
9152 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009153 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009154 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009155 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009156 << getOpenMPClauseName(OMPC_reduction)
9157 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009158 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009159 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009160 }
9161 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009162
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009163 // Try to find 'declare reduction' corresponding construct before using
9164 // builtin/overloaded operators.
9165 CXXCastPath BasePath;
9166 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009167 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009168 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9169 if (DeclareReductionRef.isInvalid())
9170 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009171 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009172 (DeclareReductionRef.isUnset() ||
9173 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009174 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009175 continue;
9176 }
9177 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9178 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009179 S.Diag(ReductionId.getLocStart(),
9180 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009181 << Type << ReductionIdRange;
9182 continue;
9183 }
9184
9185 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9186 // The type of a list item that appears in a reduction clause must be valid
9187 // for the reduction-identifier. For a max or min reduction in C, the type
9188 // of the list item must be an allowed arithmetic data type: char, int,
9189 // float, double, or _Bool, possibly modified with long, short, signed, or
9190 // unsigned. For a max or min reduction in C++, the type of the list item
9191 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9192 // double, or bool, possibly modified with long, short, signed, or unsigned.
9193 if (DeclareReductionRef.isUnset()) {
9194 if ((BOK == BO_GT || BOK == BO_LT) &&
9195 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009196 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9197 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009198 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009199 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009200 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9201 VarDecl::DeclarationOnly;
9202 S.Diag(D->getLocation(),
9203 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009204 << D;
9205 }
9206 continue;
9207 }
9208 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009209 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009210 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9211 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009212 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009213 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9214 VarDecl::DeclarationOnly;
9215 S.Diag(D->getLocation(),
9216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009217 << D;
9218 }
9219 continue;
9220 }
9221 }
9222
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009223 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009224 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009225 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009226 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009227 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009228 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009229 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009230 (!ASE &&
9231 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009232 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009233 // Create pseudo array type for private copy. The size for this array will
9234 // be generated during codegen.
9235 // For array subscripts or single variables Private Ty is the same as Type
9236 // (type of the variable or single array element).
9237 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009238 Type,
9239 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9240 VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009241 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009242 } else if (!ASE && !OASE &&
9243 Context.getAsArrayType(D->getType().getNonReferenceType()))
9244 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009245 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009246 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009247 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009248 // Add initializer for private variable.
9249 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009250 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9251 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009252 if (DeclareReductionRef.isUsable()) {
9253 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9254 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9255 if (DRD->getInitializer()) {
9256 Init = DRDRef;
9257 RHSVD->setInit(DRDRef);
9258 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009259 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009260 } else {
9261 switch (BOK) {
9262 case BO_Add:
9263 case BO_Xor:
9264 case BO_Or:
9265 case BO_LOr:
9266 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9267 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009268 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009269 break;
9270 case BO_Mul:
9271 case BO_LAnd:
9272 if (Type->isScalarType() || Type->isAnyComplexType()) {
9273 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009274 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009275 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009276 break;
9277 case BO_And: {
9278 // '&' reduction op - initializer is '~0'.
9279 QualType OrigType = Type;
9280 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9281 Type = ComplexTy->getElementType();
9282 if (Type->isRealFloatingType()) {
9283 llvm::APFloat InitValue =
9284 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9285 /*isIEEE=*/true);
9286 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9287 Type, ELoc);
9288 } else if (Type->isScalarType()) {
9289 auto Size = Context.getTypeSize(Type);
9290 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9291 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9292 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9293 }
9294 if (Init && OrigType->isAnyComplexType()) {
9295 // Init = 0xFFFF + 0xFFFFi;
9296 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009297 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009298 }
9299 Type = OrigType;
9300 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009301 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009302 case BO_LT:
9303 case BO_GT: {
9304 // 'min' reduction op - initializer is 'Largest representable number in
9305 // the reduction list item type'.
9306 // 'max' reduction op - initializer is 'Least representable number in
9307 // the reduction list item type'.
9308 if (Type->isIntegerType() || Type->isPointerType()) {
9309 bool IsSigned = Type->hasSignedIntegerRepresentation();
9310 auto Size = Context.getTypeSize(Type);
9311 QualType IntTy =
9312 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9313 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009314 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9315 : llvm::APInt::getMinValue(Size)
9316 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9317 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009318 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9319 if (Type->isPointerType()) {
9320 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009321 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009322 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9323 SourceLocation(), Init);
9324 if (CastExpr.isInvalid())
9325 continue;
9326 Init = CastExpr.get();
9327 }
9328 } else if (Type->isRealFloatingType()) {
9329 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9330 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9331 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9332 Type, ELoc);
9333 }
9334 break;
9335 }
9336 case BO_PtrMemD:
9337 case BO_PtrMemI:
9338 case BO_MulAssign:
9339 case BO_Div:
9340 case BO_Rem:
9341 case BO_Sub:
9342 case BO_Shl:
9343 case BO_Shr:
9344 case BO_LE:
9345 case BO_GE:
9346 case BO_EQ:
9347 case BO_NE:
9348 case BO_AndAssign:
9349 case BO_XorAssign:
9350 case BO_OrAssign:
9351 case BO_Assign:
9352 case BO_AddAssign:
9353 case BO_SubAssign:
9354 case BO_DivAssign:
9355 case BO_RemAssign:
9356 case BO_ShlAssign:
9357 case BO_ShrAssign:
9358 case BO_Comma:
9359 llvm_unreachable("Unexpected reduction operation");
9360 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009361 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009362 if (Init && DeclareReductionRef.isUnset())
9363 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9364 else if (!Init)
9365 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009366 if (RHSVD->isInvalidDecl())
9367 continue;
9368 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009369 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9370 << Type << ReductionIdRange;
9371 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9372 VarDecl::DeclarationOnly;
9373 S.Diag(D->getLocation(),
9374 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009375 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009376 continue;
9377 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009378 // Store initializer for single element in private copy. Will be used during
9379 // codegen.
9380 PrivateVD->setInit(RHSVD->getInit());
9381 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009382 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009383 ExprResult ReductionOp;
9384 if (DeclareReductionRef.isUsable()) {
9385 QualType RedTy = DeclareReductionRef.get()->getType();
9386 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009387 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9388 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009389 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009390 LHS = S.DefaultLvalueConversion(LHS.get());
9391 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009392 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9393 CK_UncheckedDerivedToBase, LHS.get(),
9394 &BasePath, LHS.get()->getValueKind());
9395 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9396 CK_UncheckedDerivedToBase, RHS.get(),
9397 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009398 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009399 FunctionProtoType::ExtProtoInfo EPI;
9400 QualType Params[] = {PtrRedTy, PtrRedTy};
9401 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9402 auto *OVE = new (Context) OpaqueValueExpr(
9403 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009404 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009405 Expr *Args[] = {LHS.get(), RHS.get()};
9406 ReductionOp = new (Context)
9407 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9408 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009409 ReductionOp = S.BuildBinOp(
9410 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009411 if (ReductionOp.isUsable()) {
9412 if (BOK != BO_LT && BOK != BO_GT) {
9413 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009414 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9415 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009416 } else {
9417 auto *ConditionalOp = new (Context) ConditionalOperator(
9418 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9419 RHSDRE, Type, VK_LValue, OK_Ordinary);
9420 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009421 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9422 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009423 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009424 if (ReductionOp.isUsable())
9425 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009426 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009427 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009428 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009429 }
9430
Alexey Bataev60da77e2016-02-29 05:54:20 +00009431 DeclRefExpr *Ref = nullptr;
9432 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009433 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009434 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009435 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009436 VarsExpr =
9437 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9438 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009439 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009440 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009441 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009442 if (!S.IsOpenMPCapturedDecl(D)) {
9443 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009444 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009445 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009446 if (!RefRes.isUsable())
9447 continue;
9448 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009449 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9450 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009451 if (!PostUpdateRes.isUsable())
9452 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009453 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9454 Stack->getCurrentDirective() == OMPD_taskgroup) {
9455 S.Diag(RefExpr->getExprLoc(),
9456 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009457 << RefExpr->getSourceRange();
9458 continue;
9459 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009460 RD.ExprPostUpdates.emplace_back(
9461 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009462 }
9463 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009464 }
Alexey Bataev169d96a2017-07-18 20:17:46 +00009465 // All reduction items are still marked as reduction (to do not increase
9466 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009467 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9468 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009469 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009470 return RD.Vars.empty();
9471}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009472
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009473OMPClause *Sema::ActOnOpenMPReductionClause(
9474 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9475 SourceLocation ColonLoc, SourceLocation EndLoc,
9476 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9477 ArrayRef<Expr *> UnresolvedReductions) {
9478 ReductionData RD(VarList.size());
9479
Alexey Bataev169d96a2017-07-18 20:17:46 +00009480 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
9481 StartLoc, LParenLoc, ColonLoc, EndLoc,
9482 ReductionIdScopeSpec, ReductionId,
9483 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009484 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009485
Alexey Bataevc5e02582014-06-16 07:08:35 +00009486 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009487 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9488 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9489 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9490 buildPreInits(Context, RD.ExprCaptures),
9491 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009492}
9493
Alexey Bataev169d96a2017-07-18 20:17:46 +00009494OMPClause *Sema::ActOnOpenMPTaskReductionClause(
9495 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9496 SourceLocation ColonLoc, SourceLocation EndLoc,
9497 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9498 ArrayRef<Expr *> UnresolvedReductions) {
9499 ReductionData RD(VarList.size());
9500
9501 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
9502 VarList, StartLoc, LParenLoc, ColonLoc,
9503 EndLoc, ReductionIdScopeSpec, ReductionId,
9504 UnresolvedReductions, RD))
9505 return nullptr;
9506
9507 return OMPTaskReductionClause::Create(
9508 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9509 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9510 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9511 buildPreInits(Context, RD.ExprCaptures),
9512 buildPostUpdate(*this, RD.ExprPostUpdates));
9513}
9514
Alexey Bataevecba70f2016-04-12 11:02:11 +00009515bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9516 SourceLocation LinLoc) {
9517 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9518 LinKind == OMPC_LINEAR_unknown) {
9519 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9520 return true;
9521 }
9522 return false;
9523}
9524
9525bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9526 OpenMPLinearClauseKind LinKind,
9527 QualType Type) {
9528 auto *VD = dyn_cast_or_null<VarDecl>(D);
9529 // A variable must not have an incomplete type or a reference type.
9530 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9531 return true;
9532 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9533 !Type->isReferenceType()) {
9534 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9535 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9536 return true;
9537 }
9538 Type = Type.getNonReferenceType();
9539
9540 // A list item must not be const-qualified.
9541 if (Type.isConstant(Context)) {
9542 Diag(ELoc, diag::err_omp_const_variable)
9543 << getOpenMPClauseName(OMPC_linear);
9544 if (D) {
9545 bool IsDecl =
9546 !VD ||
9547 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9548 Diag(D->getLocation(),
9549 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9550 << D;
9551 }
9552 return true;
9553 }
9554
9555 // A list item must be of integral or pointer type.
9556 Type = Type.getUnqualifiedType().getCanonicalType();
9557 const auto *Ty = Type.getTypePtrOrNull();
9558 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9559 !Ty->isPointerType())) {
9560 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9561 if (D) {
9562 bool IsDecl =
9563 !VD ||
9564 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9565 Diag(D->getLocation(),
9566 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9567 << D;
9568 }
9569 return true;
9570 }
9571 return false;
9572}
9573
Alexey Bataev182227b2015-08-20 10:54:39 +00009574OMPClause *Sema::ActOnOpenMPLinearClause(
9575 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9576 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9577 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009578 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009579 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009580 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009581 SmallVector<Decl *, 4> ExprCaptures;
9582 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009583 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009584 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009585 for (auto &RefExpr : VarList) {
9586 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009587 SourceLocation ELoc;
9588 SourceRange ERange;
9589 Expr *SimpleRefExpr = RefExpr;
9590 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9591 /*AllowArraySection=*/false);
9592 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009593 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009594 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009595 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009596 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009597 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009598 ValueDecl *D = Res.first;
9599 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009600 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009601
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009602 QualType Type = D->getType();
9603 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009604
9605 // OpenMP [2.14.3.7, linear clause]
9606 // A list-item cannot appear in more than one linear clause.
9607 // A list-item that appears in a linear clause cannot appear in any
9608 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009609 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009610 if (DVar.RefExpr) {
9611 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9612 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009613 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009614 continue;
9615 }
9616
Alexey Bataevecba70f2016-04-12 11:02:11 +00009617 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009618 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009619 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009620
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009621 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009622 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9623 D->hasAttrs() ? &D->getAttrs() : nullptr);
9624 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009625 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009626 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009627 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009628 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009629 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009630 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9631 if (!IsOpenMPCapturedDecl(D)) {
9632 ExprCaptures.push_back(Ref->getDecl());
9633 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9634 ExprResult RefRes = DefaultLvalueConversion(Ref);
9635 if (!RefRes.isUsable())
9636 continue;
9637 ExprResult PostUpdateRes =
9638 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9639 SimpleRefExpr, RefRes.get());
9640 if (!PostUpdateRes.isUsable())
9641 continue;
9642 ExprPostUpdates.push_back(
9643 IgnoredValueConversions(PostUpdateRes.get()).get());
9644 }
9645 }
9646 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009647 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009648 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009649 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009650 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009651 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009652 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009653 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9654
9655 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009656 Vars.push_back((VD || CurContext->isDependentContext())
9657 ? RefExpr->IgnoreParens()
9658 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009659 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009660 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009661 }
9662
9663 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009664 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009665
9666 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009667 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009668 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9669 !Step->isInstantiationDependent() &&
9670 !Step->containsUnexpandedParameterPack()) {
9671 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009672 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009673 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009674 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009675 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009676
Alexander Musman3276a272015-03-21 10:12:56 +00009677 // Build var to save the step value.
9678 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009679 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009680 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009681 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009682 ExprResult CalcStep =
9683 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009684 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009685
Alexander Musman8dba6642014-04-22 13:09:42 +00009686 // Warn about zero linear step (it would be probably better specified as
9687 // making corresponding variables 'const').
9688 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009689 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9690 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009691 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9692 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009693 if (!IsConstant && CalcStep.isUsable()) {
9694 // Calculate the step beforehand instead of doing this on each iteration.
9695 // (This is not used if the number of iterations may be kfold-ed).
9696 CalcStepExpr = CalcStep.get();
9697 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009698 }
9699
Alexey Bataev182227b2015-08-20 10:54:39 +00009700 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9701 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009702 StepExpr, CalcStepExpr,
9703 buildPreInits(Context, ExprCaptures),
9704 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009705}
9706
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009707static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9708 Expr *NumIterations, Sema &SemaRef,
9709 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009710 // Walk the vars and build update/final expressions for the CodeGen.
9711 SmallVector<Expr *, 8> Updates;
9712 SmallVector<Expr *, 8> Finals;
9713 Expr *Step = Clause.getStep();
9714 Expr *CalcStep = Clause.getCalcStep();
9715 // OpenMP [2.14.3.7, linear clause]
9716 // If linear-step is not specified it is assumed to be 1.
9717 if (Step == nullptr)
9718 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009719 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009720 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009721 }
Alexander Musman3276a272015-03-21 10:12:56 +00009722 bool HasErrors = false;
9723 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009724 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009725 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009726 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009727 SourceLocation ELoc;
9728 SourceRange ERange;
9729 Expr *SimpleRefExpr = RefExpr;
9730 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9731 /*AllowArraySection=*/false);
9732 ValueDecl *D = Res.first;
9733 if (Res.second || !D) {
9734 Updates.push_back(nullptr);
9735 Finals.push_back(nullptr);
9736 HasErrors = true;
9737 continue;
9738 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009739 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009740 Expr *InitExpr = *CurInit;
9741
9742 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009743 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009744 Expr *CapturedRef;
9745 if (LinKind == OMPC_LINEAR_uval)
9746 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9747 else
9748 CapturedRef =
9749 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9750 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9751 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009752
9753 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009754 ExprResult Update;
9755 if (!Info.first) {
9756 Update =
9757 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9758 InitExpr, IV, Step, /* Subtract */ false);
9759 } else
9760 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009761 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9762 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009763
9764 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009765 ExprResult Final;
9766 if (!Info.first) {
9767 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9768 InitExpr, NumIterations, Step,
9769 /* Subtract */ false);
9770 } else
9771 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009772 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9773 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009774
Alexander Musman3276a272015-03-21 10:12:56 +00009775 if (!Update.isUsable() || !Final.isUsable()) {
9776 Updates.push_back(nullptr);
9777 Finals.push_back(nullptr);
9778 HasErrors = true;
9779 } else {
9780 Updates.push_back(Update.get());
9781 Finals.push_back(Final.get());
9782 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009783 ++CurInit;
9784 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009785 }
9786 Clause.setUpdates(Updates);
9787 Clause.setFinals(Finals);
9788 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009789}
9790
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009791OMPClause *Sema::ActOnOpenMPAlignedClause(
9792 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9793 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9794
9795 SmallVector<Expr *, 8> Vars;
9796 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009797 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9798 SourceLocation ELoc;
9799 SourceRange ERange;
9800 Expr *SimpleRefExpr = RefExpr;
9801 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9802 /*AllowArraySection=*/false);
9803 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009804 // It will be analyzed later.
9805 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009806 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009807 ValueDecl *D = Res.first;
9808 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009809 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009810
Alexey Bataev1efd1662016-03-29 10:59:56 +00009811 QualType QType = D->getType();
9812 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009813
9814 // OpenMP [2.8.1, simd construct, Restrictions]
9815 // The type of list items appearing in the aligned clause must be
9816 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009817 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009818 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009819 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009820 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009821 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009822 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009823 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009824 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009825 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009826 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009827 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009828 continue;
9829 }
9830
9831 // OpenMP [2.8.1, simd construct, Restrictions]
9832 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009833 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009834 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009835 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9836 << getOpenMPClauseName(OMPC_aligned);
9837 continue;
9838 }
9839
Alexey Bataev1efd1662016-03-29 10:59:56 +00009840 DeclRefExpr *Ref = nullptr;
9841 if (!VD && IsOpenMPCapturedDecl(D))
9842 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9843 Vars.push_back(DefaultFunctionArrayConversion(
9844 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9845 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009846 }
9847
9848 // OpenMP [2.8.1, simd construct, Description]
9849 // The parameter of the aligned clause, alignment, must be a constant
9850 // positive integer expression.
9851 // If no optional parameter is specified, implementation-defined default
9852 // alignments for SIMD instructions on the target platforms are assumed.
9853 if (Alignment != nullptr) {
9854 ExprResult AlignResult =
9855 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9856 if (AlignResult.isInvalid())
9857 return nullptr;
9858 Alignment = AlignResult.get();
9859 }
9860 if (Vars.empty())
9861 return nullptr;
9862
9863 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9864 EndLoc, Vars, Alignment);
9865}
9866
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009867OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9868 SourceLocation StartLoc,
9869 SourceLocation LParenLoc,
9870 SourceLocation EndLoc) {
9871 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009872 SmallVector<Expr *, 8> SrcExprs;
9873 SmallVector<Expr *, 8> DstExprs;
9874 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009875 for (auto &RefExpr : VarList) {
9876 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9877 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009878 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009879 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009880 SrcExprs.push_back(nullptr);
9881 DstExprs.push_back(nullptr);
9882 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009883 continue;
9884 }
9885
Alexey Bataeved09d242014-05-28 05:53:51 +00009886 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009887 // OpenMP [2.1, C/C++]
9888 // A list item is a variable name.
9889 // OpenMP [2.14.4.1, Restrictions, p.1]
9890 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009891 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009892 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009893 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9894 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009895 continue;
9896 }
9897
9898 Decl *D = DE->getDecl();
9899 VarDecl *VD = cast<VarDecl>(D);
9900
9901 QualType Type = VD->getType();
9902 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9903 // It will be analyzed later.
9904 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009905 SrcExprs.push_back(nullptr);
9906 DstExprs.push_back(nullptr);
9907 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009908 continue;
9909 }
9910
9911 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9912 // A list item that appears in a copyin clause must be threadprivate.
9913 if (!DSAStack->isThreadPrivate(VD)) {
9914 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009915 << getOpenMPClauseName(OMPC_copyin)
9916 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009917 continue;
9918 }
9919
9920 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9921 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009922 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009923 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009924 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009925 auto *SrcVD =
9926 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9927 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009928 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009929 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9930 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009931 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9932 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009933 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009934 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009935 // For arrays generate assignment operation for single element and replace
9936 // it by the original array element in CodeGen.
9937 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9938 PseudoDstExpr, PseudoSrcExpr);
9939 if (AssignmentOp.isInvalid())
9940 continue;
9941 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9942 /*DiscardedValue=*/true);
9943 if (AssignmentOp.isInvalid())
9944 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009945
9946 DSAStack->addDSA(VD, DE, OMPC_copyin);
9947 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009948 SrcExprs.push_back(PseudoSrcExpr);
9949 DstExprs.push_back(PseudoDstExpr);
9950 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009951 }
9952
Alexey Bataeved09d242014-05-28 05:53:51 +00009953 if (Vars.empty())
9954 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009955
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009956 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9957 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009958}
9959
Alexey Bataevbae9a792014-06-27 10:37:06 +00009960OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9961 SourceLocation StartLoc,
9962 SourceLocation LParenLoc,
9963 SourceLocation EndLoc) {
9964 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009965 SmallVector<Expr *, 8> SrcExprs;
9966 SmallVector<Expr *, 8> DstExprs;
9967 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009968 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009969 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9970 SourceLocation ELoc;
9971 SourceRange ERange;
9972 Expr *SimpleRefExpr = RefExpr;
9973 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9974 /*AllowArraySection=*/false);
9975 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009976 // It will be analyzed later.
9977 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009978 SrcExprs.push_back(nullptr);
9979 DstExprs.push_back(nullptr);
9980 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009981 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009982 ValueDecl *D = Res.first;
9983 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009984 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009985
Alexey Bataeve122da12016-03-17 10:50:17 +00009986 QualType Type = D->getType();
9987 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009988
9989 // OpenMP [2.14.4.2, Restrictions, p.2]
9990 // A list item that appears in a copyprivate clause may not appear in a
9991 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009992 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9993 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009994 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9995 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009996 Diag(ELoc, diag::err_omp_wrong_dsa)
9997 << getOpenMPClauseName(DVar.CKind)
9998 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009999 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010000 continue;
10001 }
10002
10003 // OpenMP [2.11.4.2, Restrictions, p.1]
10004 // All list items that appear in a copyprivate clause must be either
10005 // threadprivate or private in the enclosing context.
10006 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010007 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010008 if (DVar.CKind == OMPC_shared) {
10009 Diag(ELoc, diag::err_omp_required_access)
10010 << getOpenMPClauseName(OMPC_copyprivate)
10011 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010012 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010013 continue;
10014 }
10015 }
10016 }
10017
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010018 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010019 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010020 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010021 << getOpenMPClauseName(OMPC_copyprivate) << Type
10022 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010023 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010024 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010025 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010026 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010027 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010028 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010029 continue;
10030 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010031
Alexey Bataevbae9a792014-06-27 10:37:06 +000010032 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10033 // A variable of class type (or array thereof) that appears in a
10034 // copyin clause requires an accessible, unambiguous copy assignment
10035 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010036 Type = Context.getBaseElementType(Type.getNonReferenceType())
10037 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010038 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010039 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10040 D->hasAttrs() ? &D->getAttrs() : nullptr);
10041 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010042 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010043 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10044 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010045 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010046 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010047 PseudoDstExpr, PseudoSrcExpr);
10048 if (AssignmentOp.isInvalid())
10049 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010050 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010051 /*DiscardedValue=*/true);
10052 if (AssignmentOp.isInvalid())
10053 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010054
10055 // No need to mark vars as copyprivate, they are already threadprivate or
10056 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010057 assert(VD || IsOpenMPCapturedDecl(D));
10058 Vars.push_back(
10059 VD ? RefExpr->IgnoreParens()
10060 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010061 SrcExprs.push_back(PseudoSrcExpr);
10062 DstExprs.push_back(PseudoDstExpr);
10063 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010064 }
10065
10066 if (Vars.empty())
10067 return nullptr;
10068
Alexey Bataeva63048e2015-03-23 06:18:07 +000010069 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10070 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010071}
10072
Alexey Bataev6125da92014-07-21 11:26:11 +000010073OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10074 SourceLocation StartLoc,
10075 SourceLocation LParenLoc,
10076 SourceLocation EndLoc) {
10077 if (VarList.empty())
10078 return nullptr;
10079
10080 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10081}
Alexey Bataevdea47612014-07-23 07:46:59 +000010082
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010083OMPClause *
10084Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10085 SourceLocation DepLoc, SourceLocation ColonLoc,
10086 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10087 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010088 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010089 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010090 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010091 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010092 return nullptr;
10093 }
10094 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010095 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10096 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010097 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010098 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010099 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10100 /*Last=*/OMPC_DEPEND_unknown, Except)
10101 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010102 return nullptr;
10103 }
10104 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010105 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010106 llvm::APSInt DepCounter(/*BitWidth=*/32);
10107 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10108 if (DepKind == OMPC_DEPEND_sink) {
10109 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10110 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10111 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010112 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010113 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010114 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10115 DSAStack->getParentOrderedRegionParam()) {
10116 for (auto &RefExpr : VarList) {
10117 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010118 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010119 // It will be analyzed later.
10120 Vars.push_back(RefExpr);
10121 continue;
10122 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010123
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010124 SourceLocation ELoc = RefExpr->getExprLoc();
10125 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10126 if (DepKind == OMPC_DEPEND_sink) {
10127 if (DepCounter >= TotalDepCount) {
10128 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10129 continue;
10130 }
10131 ++DepCounter;
10132 // OpenMP [2.13.9, Summary]
10133 // depend(dependence-type : vec), where dependence-type is:
10134 // 'sink' and where vec is the iteration vector, which has the form:
10135 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10136 // where n is the value specified by the ordered clause in the loop
10137 // directive, xi denotes the loop iteration variable of the i-th nested
10138 // loop associated with the loop directive, and di is a constant
10139 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010140 if (CurContext->isDependentContext()) {
10141 // It will be analyzed later.
10142 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010143 continue;
10144 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010145 SimpleExpr = SimpleExpr->IgnoreImplicit();
10146 OverloadedOperatorKind OOK = OO_None;
10147 SourceLocation OOLoc;
10148 Expr *LHS = SimpleExpr;
10149 Expr *RHS = nullptr;
10150 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10151 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10152 OOLoc = BO->getOperatorLoc();
10153 LHS = BO->getLHS()->IgnoreParenImpCasts();
10154 RHS = BO->getRHS()->IgnoreParenImpCasts();
10155 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10156 OOK = OCE->getOperator();
10157 OOLoc = OCE->getOperatorLoc();
10158 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10159 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10160 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10161 OOK = MCE->getMethodDecl()
10162 ->getNameInfo()
10163 .getName()
10164 .getCXXOverloadedOperator();
10165 OOLoc = MCE->getCallee()->getExprLoc();
10166 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10167 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10168 }
10169 SourceLocation ELoc;
10170 SourceRange ERange;
10171 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10172 /*AllowArraySection=*/false);
10173 if (Res.second) {
10174 // It will be analyzed later.
10175 Vars.push_back(RefExpr);
10176 }
10177 ValueDecl *D = Res.first;
10178 if (!D)
10179 continue;
10180
10181 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10182 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10183 continue;
10184 }
10185 if (RHS) {
10186 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10187 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10188 if (RHSRes.isInvalid())
10189 continue;
10190 }
10191 if (!CurContext->isDependentContext() &&
10192 DSAStack->getParentOrderedRegionParam() &&
10193 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10194 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10195 << DSAStack->getParentLoopControlVariable(
10196 DepCounter.getZExtValue());
10197 continue;
10198 }
10199 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010200 } else {
10201 // OpenMP [2.11.1.1, Restrictions, p.3]
10202 // A variable that is part of another variable (such as a field of a
10203 // structure) but is not an array element or an array section cannot
10204 // appear in a depend clause.
10205 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10206 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10207 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10208 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10209 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010210 (ASE &&
10211 !ASE->getBase()
10212 ->getType()
10213 .getNonReferenceType()
10214 ->isPointerType() &&
10215 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010216 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10217 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010218 continue;
10219 }
10220 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010221 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10222 }
10223
10224 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10225 TotalDepCount > VarList.size() &&
10226 DSAStack->getParentOrderedRegionParam()) {
10227 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10228 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10229 }
10230 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10231 Vars.empty())
10232 return nullptr;
10233 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010234 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10235 DepKind, DepLoc, ColonLoc, Vars);
10236 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10237 DSAStack->addDoacrossDependClause(C, OpsOffs);
10238 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010239}
Michael Wonge710d542015-08-07 16:16:36 +000010240
10241OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10242 SourceLocation LParenLoc,
10243 SourceLocation EndLoc) {
10244 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010245
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010246 // OpenMP [2.9.1, Restrictions]
10247 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010248 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10249 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010250 return nullptr;
10251
Michael Wonge710d542015-08-07 16:16:36 +000010252 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10253}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010254
10255static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10256 DSAStackTy *Stack, CXXRecordDecl *RD) {
10257 if (!RD || RD->isInvalidDecl())
10258 return true;
10259
10260 auto QTy = SemaRef.Context.getRecordType(RD);
10261 if (RD->isDynamicClass()) {
10262 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10263 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10264 return false;
10265 }
10266 auto *DC = RD;
10267 bool IsCorrect = true;
10268 for (auto *I : DC->decls()) {
10269 if (I) {
10270 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10271 if (MD->isStatic()) {
10272 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10273 SemaRef.Diag(MD->getLocation(),
10274 diag::note_omp_static_member_in_target);
10275 IsCorrect = false;
10276 }
10277 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10278 if (VD->isStaticDataMember()) {
10279 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10280 SemaRef.Diag(VD->getLocation(),
10281 diag::note_omp_static_member_in_target);
10282 IsCorrect = false;
10283 }
10284 }
10285 }
10286 }
10287
10288 for (auto &I : RD->bases()) {
10289 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10290 I.getType()->getAsCXXRecordDecl()))
10291 IsCorrect = false;
10292 }
10293 return IsCorrect;
10294}
10295
10296static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10297 DSAStackTy *Stack, QualType QTy) {
10298 NamedDecl *ND;
10299 if (QTy->isIncompleteType(&ND)) {
10300 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10301 return false;
10302 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010303 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010304 return false;
10305 }
10306 return true;
10307}
10308
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010309/// \brief Return true if it can be proven that the provided array expression
10310/// (array section or array subscript) does NOT specify the whole size of the
10311/// array whose base type is \a BaseQTy.
10312static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10313 const Expr *E,
10314 QualType BaseQTy) {
10315 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10316
10317 // If this is an array subscript, it refers to the whole size if the size of
10318 // the dimension is constant and equals 1. Also, an array section assumes the
10319 // format of an array subscript if no colon is used.
10320 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10321 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10322 return ATy->getSize().getSExtValue() != 1;
10323 // Size can't be evaluated statically.
10324 return false;
10325 }
10326
10327 assert(OASE && "Expecting array section if not an array subscript.");
10328 auto *LowerBound = OASE->getLowerBound();
10329 auto *Length = OASE->getLength();
10330
10331 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010332 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010333 if (LowerBound) {
10334 llvm::APSInt ConstLowerBound;
10335 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10336 return false; // Can't get the integer value as a constant.
10337 if (ConstLowerBound.getSExtValue())
10338 return true;
10339 }
10340
10341 // If we don't have a length we covering the whole dimension.
10342 if (!Length)
10343 return false;
10344
10345 // If the base is a pointer, we don't have a way to get the size of the
10346 // pointee.
10347 if (BaseQTy->isPointerType())
10348 return false;
10349
10350 // We can only check if the length is the same as the size of the dimension
10351 // if we have a constant array.
10352 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10353 if (!CATy)
10354 return false;
10355
10356 llvm::APSInt ConstLength;
10357 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10358 return false; // Can't get the integer value as a constant.
10359
10360 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10361}
10362
10363// Return true if it can be proven that the provided array expression (array
10364// section or array subscript) does NOT specify a single element of the array
10365// whose base type is \a BaseQTy.
10366static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010367 const Expr *E,
10368 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010369 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10370
10371 // An array subscript always refer to a single element. Also, an array section
10372 // assumes the format of an array subscript if no colon is used.
10373 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10374 return false;
10375
10376 assert(OASE && "Expecting array section if not an array subscript.");
10377 auto *Length = OASE->getLength();
10378
10379 // If we don't have a length we have to check if the array has unitary size
10380 // for this dimension. Also, we should always expect a length if the base type
10381 // is pointer.
10382 if (!Length) {
10383 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10384 return ATy->getSize().getSExtValue() != 1;
10385 // We cannot assume anything.
10386 return false;
10387 }
10388
10389 // Check if the length evaluates to 1.
10390 llvm::APSInt ConstLength;
10391 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10392 return false; // Can't get the integer value as a constant.
10393
10394 return ConstLength.getSExtValue() != 1;
10395}
10396
Samuel Antao661c0902016-05-26 17:39:58 +000010397// Return the expression of the base of the mappable expression or null if it
10398// cannot be determined and do all the necessary checks to see if the expression
10399// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010400// components of the expression.
10401static Expr *CheckMapClauseExpressionBase(
10402 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010403 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10404 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010405 SourceLocation ELoc = E->getExprLoc();
10406 SourceRange ERange = E->getSourceRange();
10407
10408 // The base of elements of list in a map clause have to be either:
10409 // - a reference to variable or field.
10410 // - a member expression.
10411 // - an array expression.
10412 //
10413 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10414 // reference to 'r'.
10415 //
10416 // If we have:
10417 //
10418 // struct SS {
10419 // Bla S;
10420 // foo() {
10421 // #pragma omp target map (S.Arr[:12]);
10422 // }
10423 // }
10424 //
10425 // We want to retrieve the member expression 'this->S';
10426
10427 Expr *RelevantExpr = nullptr;
10428
Samuel Antao5de996e2016-01-22 20:21:36 +000010429 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10430 // If a list item is an array section, it must specify contiguous storage.
10431 //
10432 // For this restriction it is sufficient that we make sure only references
10433 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010434 // exist except in the rightmost expression (unless they cover the whole
10435 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010436 //
10437 // r.ArrS[3:5].Arr[6:7]
10438 //
10439 // r.ArrS[3:5].x
10440 //
10441 // but these would be valid:
10442 // r.ArrS[3].Arr[6:7]
10443 //
10444 // r.ArrS[3].x
10445
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010446 bool AllowUnitySizeArraySection = true;
10447 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010448
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010449 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010450 E = E->IgnoreParenImpCasts();
10451
10452 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10453 if (!isa<VarDecl>(CurE->getDecl()))
10454 break;
10455
10456 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010457
10458 // If we got a reference to a declaration, we should not expect any array
10459 // section before that.
10460 AllowUnitySizeArraySection = false;
10461 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010462
10463 // Record the component.
10464 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10465 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010466 continue;
10467 }
10468
10469 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10470 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10471
10472 if (isa<CXXThisExpr>(BaseE))
10473 // We found a base expression: this->Val.
10474 RelevantExpr = CurE;
10475 else
10476 E = BaseE;
10477
10478 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10479 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10480 << CurE->getSourceRange();
10481 break;
10482 }
10483
10484 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10485
10486 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10487 // A bit-field cannot appear in a map clause.
10488 //
10489 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010490 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10491 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010492 break;
10493 }
10494
10495 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10496 // If the type of a list item is a reference to a type T then the type
10497 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010498 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010499
10500 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10501 // A list item cannot be a variable that is a member of a structure with
10502 // a union type.
10503 //
10504 if (auto *RT = CurType->getAs<RecordType>())
10505 if (RT->isUnionType()) {
10506 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10507 << CurE->getSourceRange();
10508 break;
10509 }
10510
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010511 // If we got a member expression, we should not expect any array section
10512 // before that:
10513 //
10514 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10515 // If a list item is an element of a structure, only the rightmost symbol
10516 // of the variable reference can be an array section.
10517 //
10518 AllowUnitySizeArraySection = false;
10519 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010520
10521 // Record the component.
10522 CurComponents.push_back(
10523 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010524 continue;
10525 }
10526
10527 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10528 E = CurE->getBase()->IgnoreParenImpCasts();
10529
10530 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10531 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10532 << 0 << CurE->getSourceRange();
10533 break;
10534 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010535
10536 // If we got an array subscript that express the whole dimension we
10537 // can have any array expressions before. If it only expressing part of
10538 // the dimension, we can only have unitary-size array expressions.
10539 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10540 E->getType()))
10541 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010542
10543 // Record the component - we don't have any declaration associated.
10544 CurComponents.push_back(
10545 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010546 continue;
10547 }
10548
10549 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010550 E = CurE->getBase()->IgnoreParenImpCasts();
10551
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010552 auto CurType =
10553 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10554
Samuel Antao5de996e2016-01-22 20:21:36 +000010555 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10556 // If the type of a list item is a reference to a type T then the type
10557 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010558 if (CurType->isReferenceType())
10559 CurType = CurType->getPointeeType();
10560
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010561 bool IsPointer = CurType->isAnyPointerType();
10562
10563 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010564 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10565 << 0 << CurE->getSourceRange();
10566 break;
10567 }
10568
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010569 bool NotWhole =
10570 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10571 bool NotUnity =
10572 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10573
Samuel Antaodab51bb2016-07-18 23:22:11 +000010574 if (AllowWholeSizeArraySection) {
10575 // Any array section is currently allowed. Allowing a whole size array
10576 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010577 //
10578 // If this array section refers to the whole dimension we can still
10579 // accept other array sections before this one, except if the base is a
10580 // pointer. Otherwise, only unitary sections are accepted.
10581 if (NotWhole || IsPointer)
10582 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010583 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010584 // A unity or whole array section is not allowed and that is not
10585 // compatible with the properties of the current array section.
10586 SemaRef.Diag(
10587 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10588 << CurE->getSourceRange();
10589 break;
10590 }
Samuel Antao90927002016-04-26 14:54:23 +000010591
10592 // Record the component - we don't have any declaration associated.
10593 CurComponents.push_back(
10594 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010595 continue;
10596 }
10597
10598 // If nothing else worked, this is not a valid map clause expression.
10599 SemaRef.Diag(ELoc,
10600 diag::err_omp_expected_named_var_member_or_array_expression)
10601 << ERange;
10602 break;
10603 }
10604
10605 return RelevantExpr;
10606}
10607
10608// Return true if expression E associated with value VD has conflicts with other
10609// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010610static bool CheckMapConflicts(
10611 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10612 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010613 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10614 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010615 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010616 SourceLocation ELoc = E->getExprLoc();
10617 SourceRange ERange = E->getSourceRange();
10618
10619 // In order to easily check the conflicts we need to match each component of
10620 // the expression under test with the components of the expressions that are
10621 // already in the stack.
10622
Samuel Antao5de996e2016-01-22 20:21:36 +000010623 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010624 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010625 "Map clause expression with unexpected base!");
10626
10627 // Variables to help detecting enclosing problems in data environment nests.
10628 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010629 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010630
Samuel Antao90927002016-04-26 14:54:23 +000010631 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10632 VD, CurrentRegionOnly,
10633 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010634 StackComponents,
10635 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010636
Samuel Antao5de996e2016-01-22 20:21:36 +000010637 assert(!StackComponents.empty() &&
10638 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010639 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010640 "Map clause expression with unexpected base!");
10641
Samuel Antao90927002016-04-26 14:54:23 +000010642 // The whole expression in the stack.
10643 auto *RE = StackComponents.front().getAssociatedExpression();
10644
Samuel Antao5de996e2016-01-22 20:21:36 +000010645 // Expressions must start from the same base. Here we detect at which
10646 // point both expressions diverge from each other and see if we can
10647 // detect if the memory referred to both expressions is contiguous and
10648 // do not overlap.
10649 auto CI = CurComponents.rbegin();
10650 auto CE = CurComponents.rend();
10651 auto SI = StackComponents.rbegin();
10652 auto SE = StackComponents.rend();
10653 for (; CI != CE && SI != SE; ++CI, ++SI) {
10654
10655 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10656 // At most one list item can be an array item derived from a given
10657 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010658 if (CurrentRegionOnly &&
10659 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10660 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10661 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10662 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10663 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010664 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010665 << CI->getAssociatedExpression()->getSourceRange();
10666 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10667 diag::note_used_here)
10668 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010669 return true;
10670 }
10671
10672 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010673 if (CI->getAssociatedExpression()->getStmtClass() !=
10674 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010675 break;
10676
10677 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010678 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010679 break;
10680 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010681 // Check if the extra components of the expressions in the enclosing
10682 // data environment are redundant for the current base declaration.
10683 // If they are, the maps completely overlap, which is legal.
10684 for (; SI != SE; ++SI) {
10685 QualType Type;
10686 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010687 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010688 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010689 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10690 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010691 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10692 Type =
10693 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10694 }
10695 if (Type.isNull() || Type->isAnyPointerType() ||
10696 CheckArrayExpressionDoesNotReferToWholeSize(
10697 SemaRef, SI->getAssociatedExpression(), Type))
10698 break;
10699 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010700
10701 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10702 // List items of map clauses in the same construct must not share
10703 // original storage.
10704 //
10705 // If the expressions are exactly the same or one is a subset of the
10706 // other, it means they are sharing storage.
10707 if (CI == CE && SI == SE) {
10708 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010709 if (CKind == OMPC_map)
10710 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10711 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010712 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010713 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10714 << ERange;
10715 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010716 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10717 << RE->getSourceRange();
10718 return true;
10719 } else {
10720 // If we find the same expression in the enclosing data environment,
10721 // that is legal.
10722 IsEnclosedByDataEnvironmentExpr = true;
10723 return false;
10724 }
10725 }
10726
Samuel Antao90927002016-04-26 14:54:23 +000010727 QualType DerivedType =
10728 std::prev(CI)->getAssociatedDeclaration()->getType();
10729 SourceLocation DerivedLoc =
10730 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010731
10732 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10733 // If the type of a list item is a reference to a type T then the type
10734 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010735 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010736
10737 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10738 // A variable for which the type is pointer and an array section
10739 // derived from that variable must not appear as list items of map
10740 // clauses of the same construct.
10741 //
10742 // Also, cover one of the cases in:
10743 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10744 // If any part of the original storage of a list item has corresponding
10745 // storage in the device data environment, all of the original storage
10746 // must have corresponding storage in the device data environment.
10747 //
10748 if (DerivedType->isAnyPointerType()) {
10749 if (CI == CE || SI == SE) {
10750 SemaRef.Diag(
10751 DerivedLoc,
10752 diag::err_omp_pointer_mapped_along_with_derived_section)
10753 << DerivedLoc;
10754 } else {
10755 assert(CI != CE && SI != SE);
10756 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10757 << DerivedLoc;
10758 }
10759 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10760 << RE->getSourceRange();
10761 return true;
10762 }
10763
10764 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10765 // List items of map clauses in the same construct must not share
10766 // original storage.
10767 //
10768 // An expression is a subset of the other.
10769 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010770 if (CKind == OMPC_map)
10771 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10772 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010773 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010774 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10775 << ERange;
10776 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010777 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10778 << RE->getSourceRange();
10779 return true;
10780 }
10781
10782 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010783 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010784 if (!CurrentRegionOnly && SI != SE)
10785 EnclosingExpr = RE;
10786
10787 // The current expression is a subset of the expression in the data
10788 // environment.
10789 IsEnclosedByDataEnvironmentExpr |=
10790 (!CurrentRegionOnly && CI != CE && SI == SE);
10791
10792 return false;
10793 });
10794
10795 if (CurrentRegionOnly)
10796 return FoundError;
10797
10798 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10799 // If any part of the original storage of a list item has corresponding
10800 // storage in the device data environment, all of the original storage must
10801 // have corresponding storage in the device data environment.
10802 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10803 // If a list item is an element of a structure, and a different element of
10804 // the structure has a corresponding list item in the device data environment
10805 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010806 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010807 // data environment prior to the task encountering the construct.
10808 //
10809 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10810 SemaRef.Diag(ELoc,
10811 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10812 << ERange;
10813 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10814 << EnclosingExpr->getSourceRange();
10815 return true;
10816 }
10817
10818 return FoundError;
10819}
10820
Samuel Antao661c0902016-05-26 17:39:58 +000010821namespace {
10822// Utility struct that gathers all the related lists associated with a mappable
10823// expression.
10824struct MappableVarListInfo final {
10825 // The list of expressions.
10826 ArrayRef<Expr *> VarList;
10827 // The list of processed expressions.
10828 SmallVector<Expr *, 16> ProcessedVarList;
10829 // The mappble components for each expression.
10830 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10831 // The base declaration of the variable.
10832 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10833
10834 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10835 // We have a list of components and base declarations for each entry in the
10836 // variable list.
10837 VarComponents.reserve(VarList.size());
10838 VarBaseDeclarations.reserve(VarList.size());
10839 }
10840};
10841}
10842
10843// Check the validity of the provided variable list for the provided clause kind
10844// \a CKind. In the check process the valid expressions, and mappable expression
10845// components and variables are extracted and used to fill \a Vars,
10846// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10847// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10848static void
10849checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10850 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10851 SourceLocation StartLoc,
10852 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10853 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010854 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10855 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010856 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010857
Samuel Antao90927002016-04-26 14:54:23 +000010858 // Keep track of the mappable components and base declarations in this clause.
10859 // Each entry in the list is going to have a list of components associated. We
10860 // record each set of the components so that we can build the clause later on.
10861 // In the end we should have the same amount of declarations and component
10862 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010863
Samuel Antao661c0902016-05-26 17:39:58 +000010864 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010865 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010866 SourceLocation ELoc = RE->getExprLoc();
10867
Kelvin Li0bff7af2015-11-23 05:32:03 +000010868 auto *VE = RE->IgnoreParenLValueCasts();
10869
10870 if (VE->isValueDependent() || VE->isTypeDependent() ||
10871 VE->isInstantiationDependent() ||
10872 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010873 // We can only analyze this information once the missing information is
10874 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010875 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010876 continue;
10877 }
10878
10879 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010880
Samuel Antao5de996e2016-01-22 20:21:36 +000010881 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010882 SemaRef.Diag(ELoc,
10883 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010884 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010885 continue;
10886 }
10887
Samuel Antao90927002016-04-26 14:54:23 +000010888 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10889 ValueDecl *CurDeclaration = nullptr;
10890
10891 // Obtain the array or member expression bases if required. Also, fill the
10892 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010893 auto *BE =
10894 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010895 if (!BE)
10896 continue;
10897
Samuel Antao90927002016-04-26 14:54:23 +000010898 assert(!CurComponents.empty() &&
10899 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010900
Samuel Antao90927002016-04-26 14:54:23 +000010901 // For the following checks, we rely on the base declaration which is
10902 // expected to be associated with the last component. The declaration is
10903 // expected to be a variable or a field (if 'this' is being mapped).
10904 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10905 assert(CurDeclaration && "Null decl on map clause.");
10906 assert(
10907 CurDeclaration->isCanonicalDecl() &&
10908 "Expecting components to have associated only canonical declarations.");
10909
10910 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10911 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010912
10913 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010914 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010915
10916 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010917 // threadprivate variables cannot appear in a map clause.
10918 // OpenMP 4.5 [2.10.5, target update Construct]
10919 // threadprivate variables cannot appear in a from clause.
10920 if (VD && DSAS->isThreadPrivate(VD)) {
10921 auto DVar = DSAS->getTopDSA(VD, false);
10922 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10923 << getOpenMPClauseName(CKind);
10924 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010925 continue;
10926 }
10927
Samuel Antao5de996e2016-01-22 20:21:36 +000010928 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10929 // A list item cannot appear in both a map clause and a data-sharing
10930 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010931
Samuel Antao5de996e2016-01-22 20:21:36 +000010932 // Check conflicts with other map clause expressions. We check the conflicts
10933 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010934 // environment, because the restrictions are different. We only have to
10935 // check conflicts across regions for the map clauses.
10936 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10937 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010938 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010939 if (CKind == OMPC_map &&
10940 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10941 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010942 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010943
Samuel Antao661c0902016-05-26 17:39:58 +000010944 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010945 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10946 // If the type of a list item is a reference to a type T then the type will
10947 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010948 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010949
Samuel Antao661c0902016-05-26 17:39:58 +000010950 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10951 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010952 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010953 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010954 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10955 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010956 continue;
10957
Samuel Antao661c0902016-05-26 17:39:58 +000010958 if (CKind == OMPC_map) {
10959 // target enter data
10960 // OpenMP [2.10.2, Restrictions, p. 99]
10961 // A map-type must be specified in all map clauses and must be either
10962 // to or alloc.
10963 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10964 if (DKind == OMPD_target_enter_data &&
10965 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10966 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10967 << (IsMapTypeImplicit ? 1 : 0)
10968 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10969 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010970 continue;
10971 }
Samuel Antao661c0902016-05-26 17:39:58 +000010972
10973 // target exit_data
10974 // OpenMP [2.10.3, Restrictions, p. 102]
10975 // A map-type must be specified in all map clauses and must be either
10976 // from, release, or delete.
10977 if (DKind == OMPD_target_exit_data &&
10978 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10979 MapType == OMPC_MAP_delete)) {
10980 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10981 << (IsMapTypeImplicit ? 1 : 0)
10982 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10983 << getOpenMPDirectiveName(DKind);
10984 continue;
10985 }
10986
10987 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10988 // A list item cannot appear in both a map clause and a data-sharing
10989 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010990 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010991 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010992 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010993 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10994 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010995 auto DVar = DSAS->getTopDSA(VD, false);
10996 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010997 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010998 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010999 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011000 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11001 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11002 continue;
11003 }
11004 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011005 }
11006
Samuel Antao90927002016-04-26 14:54:23 +000011007 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011008 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011009
11010 // Store the components in the stack so that they can be used to check
11011 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011012 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11013 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011014
11015 // Save the components and declaration to create the clause. For purposes of
11016 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011017 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011018 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11019 MVLI.VarComponents.back().append(CurComponents.begin(),
11020 CurComponents.end());
11021 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11022 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011023 }
Samuel Antao661c0902016-05-26 17:39:58 +000011024}
11025
11026OMPClause *
11027Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11028 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11029 SourceLocation MapLoc, SourceLocation ColonLoc,
11030 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11031 SourceLocation LParenLoc, SourceLocation EndLoc) {
11032 MappableVarListInfo MVLI(VarList);
11033 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11034 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011035
Samuel Antao5de996e2016-01-22 20:21:36 +000011036 // We need to produce a map clause even if we don't have variables so that
11037 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011038 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11039 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11040 MVLI.VarComponents, MapTypeModifier, MapType,
11041 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011042}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011043
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011044QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11045 TypeResult ParsedType) {
11046 assert(ParsedType.isUsable());
11047
11048 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11049 if (ReductionType.isNull())
11050 return QualType();
11051
11052 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11053 // A type name in a declare reduction directive cannot be a function type, an
11054 // array type, a reference type, or a type qualified with const, volatile or
11055 // restrict.
11056 if (ReductionType.hasQualifiers()) {
11057 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11058 return QualType();
11059 }
11060
11061 if (ReductionType->isFunctionType()) {
11062 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11063 return QualType();
11064 }
11065 if (ReductionType->isReferenceType()) {
11066 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11067 return QualType();
11068 }
11069 if (ReductionType->isArrayType()) {
11070 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11071 return QualType();
11072 }
11073 return ReductionType;
11074}
11075
11076Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11077 Scope *S, DeclContext *DC, DeclarationName Name,
11078 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11079 AccessSpecifier AS, Decl *PrevDeclInScope) {
11080 SmallVector<Decl *, 8> Decls;
11081 Decls.reserve(ReductionTypes.size());
11082
11083 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11084 ForRedeclaration);
11085 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11086 // A reduction-identifier may not be re-declared in the current scope for the
11087 // same type or for a type that is compatible according to the base language
11088 // rules.
11089 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11090 OMPDeclareReductionDecl *PrevDRD = nullptr;
11091 bool InCompoundScope = true;
11092 if (S != nullptr) {
11093 // Find previous declaration with the same name not referenced in other
11094 // declarations.
11095 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11096 InCompoundScope =
11097 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11098 LookupName(Lookup, S);
11099 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11100 /*AllowInlineNamespace=*/false);
11101 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11102 auto Filter = Lookup.makeFilter();
11103 while (Filter.hasNext()) {
11104 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11105 if (InCompoundScope) {
11106 auto I = UsedAsPrevious.find(PrevDecl);
11107 if (I == UsedAsPrevious.end())
11108 UsedAsPrevious[PrevDecl] = false;
11109 if (auto *D = PrevDecl->getPrevDeclInScope())
11110 UsedAsPrevious[D] = true;
11111 }
11112 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11113 PrevDecl->getLocation();
11114 }
11115 Filter.done();
11116 if (InCompoundScope) {
11117 for (auto &PrevData : UsedAsPrevious) {
11118 if (!PrevData.second) {
11119 PrevDRD = PrevData.first;
11120 break;
11121 }
11122 }
11123 }
11124 } else if (PrevDeclInScope != nullptr) {
11125 auto *PrevDRDInScope = PrevDRD =
11126 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11127 do {
11128 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11129 PrevDRDInScope->getLocation();
11130 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11131 } while (PrevDRDInScope != nullptr);
11132 }
11133 for (auto &TyData : ReductionTypes) {
11134 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11135 bool Invalid = false;
11136 if (I != PreviousRedeclTypes.end()) {
11137 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11138 << TyData.first;
11139 Diag(I->second, diag::note_previous_definition);
11140 Invalid = true;
11141 }
11142 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11143 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11144 Name, TyData.first, PrevDRD);
11145 DC->addDecl(DRD);
11146 DRD->setAccess(AS);
11147 Decls.push_back(DRD);
11148 if (Invalid)
11149 DRD->setInvalidDecl();
11150 else
11151 PrevDRD = DRD;
11152 }
11153
11154 return DeclGroupPtrTy::make(
11155 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11156}
11157
11158void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11159 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11160
11161 // Enter new function scope.
11162 PushFunctionScope();
11163 getCurFunction()->setHasBranchProtectedScope();
11164 getCurFunction()->setHasOMPDeclareReductionCombiner();
11165
11166 if (S != nullptr)
11167 PushDeclContext(S, DRD);
11168 else
11169 CurContext = DRD;
11170
Faisal Valid143a0c2017-04-01 21:30:49 +000011171 PushExpressionEvaluationContext(
11172 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011173
11174 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011175 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11176 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11177 // uses semantics of argument handles by value, but it should be passed by
11178 // reference. C lang does not support references, so pass all parameters as
11179 // pointers.
11180 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011181 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011182 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011183 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11184 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11185 // uses semantics of argument handles by value, but it should be passed by
11186 // reference. C lang does not support references, so pass all parameters as
11187 // pointers.
11188 // Create 'T omp_out;' variable.
11189 auto *OmpOutParm =
11190 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11191 if (S != nullptr) {
11192 PushOnScopeChains(OmpInParm, S);
11193 PushOnScopeChains(OmpOutParm, S);
11194 } else {
11195 DRD->addDecl(OmpInParm);
11196 DRD->addDecl(OmpOutParm);
11197 }
11198}
11199
11200void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11201 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11202 DiscardCleanupsInEvaluationContext();
11203 PopExpressionEvaluationContext();
11204
11205 PopDeclContext();
11206 PopFunctionScopeInfo();
11207
11208 if (Combiner != nullptr)
11209 DRD->setCombiner(Combiner);
11210 else
11211 DRD->setInvalidDecl();
11212}
11213
11214void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11215 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11216
11217 // Enter new function scope.
11218 PushFunctionScope();
11219 getCurFunction()->setHasBranchProtectedScope();
11220
11221 if (S != nullptr)
11222 PushDeclContext(S, DRD);
11223 else
11224 CurContext = DRD;
11225
Faisal Valid143a0c2017-04-01 21:30:49 +000011226 PushExpressionEvaluationContext(
11227 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011228
11229 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011230 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11231 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11232 // uses semantics of argument handles by value, but it should be passed by
11233 // reference. C lang does not support references, so pass all parameters as
11234 // pointers.
11235 // Create 'T omp_priv;' variable.
11236 auto *OmpPrivParm =
11237 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011238 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11239 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11240 // uses semantics of argument handles by value, but it should be passed by
11241 // reference. C lang does not support references, so pass all parameters as
11242 // pointers.
11243 // Create 'T omp_orig;' variable.
11244 auto *OmpOrigParm =
11245 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011246 if (S != nullptr) {
11247 PushOnScopeChains(OmpPrivParm, S);
11248 PushOnScopeChains(OmpOrigParm, S);
11249 } else {
11250 DRD->addDecl(OmpPrivParm);
11251 DRD->addDecl(OmpOrigParm);
11252 }
11253}
11254
11255void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11256 Expr *Initializer) {
11257 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11258 DiscardCleanupsInEvaluationContext();
11259 PopExpressionEvaluationContext();
11260
11261 PopDeclContext();
11262 PopFunctionScopeInfo();
11263
11264 if (Initializer != nullptr)
11265 DRD->setInitializer(Initializer);
11266 else
11267 DRD->setInvalidDecl();
11268}
11269
11270Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11271 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11272 for (auto *D : DeclReductions.get()) {
11273 if (IsValid) {
11274 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11275 if (S != nullptr)
11276 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11277 } else
11278 D->setInvalidDecl();
11279 }
11280 return DeclReductions;
11281}
11282
David Majnemer9d168222016-08-05 17:44:54 +000011283OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011284 SourceLocation StartLoc,
11285 SourceLocation LParenLoc,
11286 SourceLocation EndLoc) {
11287 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011288 Stmt *HelperValStmt = nullptr;
11289 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011290
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011291 // OpenMP [teams Constrcut, Restrictions]
11292 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011293 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11294 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011295 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011296
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011297 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11298 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11299 if (CaptureRegion != OMPD_unknown) {
11300 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11301 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11302 HelperValStmt = buildPreInits(Context, Captures);
11303 }
11304
11305 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11306 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011307}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011308
11309OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11310 SourceLocation StartLoc,
11311 SourceLocation LParenLoc,
11312 SourceLocation EndLoc) {
11313 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011314 Stmt *HelperValStmt = nullptr;
11315 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011316
11317 // OpenMP [teams Constrcut, Restrictions]
11318 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011319 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11320 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011321 return nullptr;
11322
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011323 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11324 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11325 if (CaptureRegion != OMPD_unknown) {
11326 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11327 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11328 HelperValStmt = buildPreInits(Context, Captures);
11329 }
11330
11331 return new (Context) OMPThreadLimitClause(
11332 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011333}
Alexey Bataeva0569352015-12-01 10:17:31 +000011334
11335OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11336 SourceLocation StartLoc,
11337 SourceLocation LParenLoc,
11338 SourceLocation EndLoc) {
11339 Expr *ValExpr = Priority;
11340
11341 // OpenMP [2.9.1, task Constrcut]
11342 // The priority-value is a non-negative numerical scalar expression.
11343 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11344 /*StrictlyPositive=*/false))
11345 return nullptr;
11346
11347 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11348}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011349
11350OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11351 SourceLocation StartLoc,
11352 SourceLocation LParenLoc,
11353 SourceLocation EndLoc) {
11354 Expr *ValExpr = Grainsize;
11355
11356 // OpenMP [2.9.2, taskloop Constrcut]
11357 // The parameter of the grainsize clause must be a positive integer
11358 // expression.
11359 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11360 /*StrictlyPositive=*/true))
11361 return nullptr;
11362
11363 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11364}
Alexey Bataev382967a2015-12-08 12:06:20 +000011365
11366OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11367 SourceLocation StartLoc,
11368 SourceLocation LParenLoc,
11369 SourceLocation EndLoc) {
11370 Expr *ValExpr = NumTasks;
11371
11372 // OpenMP [2.9.2, taskloop Constrcut]
11373 // The parameter of the num_tasks clause must be a positive integer
11374 // expression.
11375 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11376 /*StrictlyPositive=*/true))
11377 return nullptr;
11378
11379 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11380}
11381
Alexey Bataev28c75412015-12-15 08:19:24 +000011382OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11383 SourceLocation LParenLoc,
11384 SourceLocation EndLoc) {
11385 // OpenMP [2.13.2, critical construct, Description]
11386 // ... where hint-expression is an integer constant expression that evaluates
11387 // to a valid lock hint.
11388 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11389 if (HintExpr.isInvalid())
11390 return nullptr;
11391 return new (Context)
11392 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11393}
11394
Carlo Bertollib4adf552016-01-15 18:50:31 +000011395OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11396 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11397 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11398 SourceLocation EndLoc) {
11399 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11400 std::string Values;
11401 Values += "'";
11402 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11403 Values += "'";
11404 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11405 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11406 return nullptr;
11407 }
11408 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011409 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011410 if (ChunkSize) {
11411 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11412 !ChunkSize->isInstantiationDependent() &&
11413 !ChunkSize->containsUnexpandedParameterPack()) {
11414 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11415 ExprResult Val =
11416 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11417 if (Val.isInvalid())
11418 return nullptr;
11419
11420 ValExpr = Val.get();
11421
11422 // OpenMP [2.7.1, Restrictions]
11423 // chunk_size must be a loop invariant integer expression with a positive
11424 // value.
11425 llvm::APSInt Result;
11426 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11427 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11428 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11429 << "dist_schedule" << ChunkSize->getSourceRange();
11430 return nullptr;
11431 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011432 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11433 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011434 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11435 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11436 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011437 }
11438 }
11439 }
11440
11441 return new (Context)
11442 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011443 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011444}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011445
11446OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11447 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11448 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11449 SourceLocation KindLoc, SourceLocation EndLoc) {
11450 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011451 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011452 std::string Value;
11453 SourceLocation Loc;
11454 Value += "'";
11455 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11456 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011457 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011458 Loc = MLoc;
11459 } else {
11460 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011461 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011462 Loc = KindLoc;
11463 }
11464 Value += "'";
11465 Diag(Loc, diag::err_omp_unexpected_clause_value)
11466 << Value << getOpenMPClauseName(OMPC_defaultmap);
11467 return nullptr;
11468 }
11469
11470 return new (Context)
11471 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11472}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011473
11474bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11475 DeclContext *CurLexicalContext = getCurLexicalContext();
11476 if (!CurLexicalContext->isFileContext() &&
11477 !CurLexicalContext->isExternCContext() &&
11478 !CurLexicalContext->isExternCXXContext()) {
11479 Diag(Loc, diag::err_omp_region_not_file_context);
11480 return false;
11481 }
11482 if (IsInOpenMPDeclareTargetContext) {
11483 Diag(Loc, diag::err_omp_enclosed_declare_target);
11484 return false;
11485 }
11486
11487 IsInOpenMPDeclareTargetContext = true;
11488 return true;
11489}
11490
11491void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11492 assert(IsInOpenMPDeclareTargetContext &&
11493 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11494
11495 IsInOpenMPDeclareTargetContext = false;
11496}
11497
David Majnemer9d168222016-08-05 17:44:54 +000011498void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11499 CXXScopeSpec &ScopeSpec,
11500 const DeclarationNameInfo &Id,
11501 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11502 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011503 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11504 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11505
11506 if (Lookup.isAmbiguous())
11507 return;
11508 Lookup.suppressDiagnostics();
11509
11510 if (!Lookup.isSingleResult()) {
11511 if (TypoCorrection Corrected =
11512 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11513 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11514 CTK_ErrorRecovery)) {
11515 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11516 << Id.getName());
11517 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11518 return;
11519 }
11520
11521 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11522 return;
11523 }
11524
11525 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11526 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11527 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11528 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11529
11530 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11531 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11532 ND->addAttr(A);
11533 if (ASTMutationListener *ML = Context.getASTMutationListener())
11534 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11535 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11536 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11537 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11538 << Id.getName();
11539 }
11540 } else
11541 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11542}
11543
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011544static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11545 Sema &SemaRef, Decl *D) {
11546 if (!D)
11547 return;
11548 Decl *LD = nullptr;
11549 if (isa<TagDecl>(D)) {
11550 LD = cast<TagDecl>(D)->getDefinition();
11551 } else if (isa<VarDecl>(D)) {
11552 LD = cast<VarDecl>(D)->getDefinition();
11553
11554 // If this is an implicit variable that is legal and we do not need to do
11555 // anything.
11556 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011557 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11558 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11559 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011560 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011561 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011562 return;
11563 }
11564
11565 } else if (isa<FunctionDecl>(D)) {
11566 const FunctionDecl *FD = nullptr;
11567 if (cast<FunctionDecl>(D)->hasBody(FD))
11568 LD = const_cast<FunctionDecl *>(FD);
11569
11570 // If the definition is associated with the current declaration in the
11571 // target region (it can be e.g. a lambda) that is legal and we do not need
11572 // to do anything else.
11573 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011574 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11575 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11576 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011577 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011578 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011579 return;
11580 }
11581 }
11582 if (!LD)
11583 LD = D;
11584 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11585 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11586 // Outlined declaration is not declared target.
11587 if (LD->isOutOfLine()) {
11588 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11589 SemaRef.Diag(SL, diag::note_used_here) << SR;
11590 } else {
11591 DeclContext *DC = LD->getDeclContext();
11592 while (DC) {
11593 if (isa<FunctionDecl>(DC) &&
11594 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11595 break;
11596 DC = DC->getParent();
11597 }
11598 if (DC)
11599 return;
11600
11601 // Is not declared in target context.
11602 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11603 SemaRef.Diag(SL, diag::note_used_here) << SR;
11604 }
11605 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011606 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11607 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11608 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011609 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011610 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011611 }
11612}
11613
11614static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11615 Sema &SemaRef, DSAStackTy *Stack,
11616 ValueDecl *VD) {
11617 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11618 return true;
11619 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11620 return false;
11621 return true;
11622}
11623
11624void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11625 if (!D || D->isInvalidDecl())
11626 return;
11627 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11628 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11629 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11630 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11631 if (DSAStack->isThreadPrivate(VD)) {
11632 Diag(SL, diag::err_omp_threadprivate_in_target);
11633 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11634 return;
11635 }
11636 }
11637 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11638 // Problem if any with var declared with incomplete type will be reported
11639 // as normal, so no need to check it here.
11640 if ((E || !VD->getType()->isIncompleteType()) &&
11641 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11642 // Mark decl as declared target to prevent further diagnostic.
11643 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011644 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11645 Context, OMPDeclareTargetDeclAttr::MT_To);
11646 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011647 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011648 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011649 }
11650 return;
11651 }
11652 }
11653 if (!E) {
11654 // Checking declaration inside declare target region.
11655 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11656 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011657 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11658 Context, OMPDeclareTargetDeclAttr::MT_To);
11659 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011660 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011661 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011662 }
11663 return;
11664 }
11665 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11666}
Samuel Antao661c0902016-05-26 17:39:58 +000011667
11668OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11669 SourceLocation StartLoc,
11670 SourceLocation LParenLoc,
11671 SourceLocation EndLoc) {
11672 MappableVarListInfo MVLI(VarList);
11673 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11674 if (MVLI.ProcessedVarList.empty())
11675 return nullptr;
11676
11677 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11678 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11679 MVLI.VarComponents);
11680}
Samuel Antaoec172c62016-05-26 17:49:04 +000011681
11682OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11683 SourceLocation StartLoc,
11684 SourceLocation LParenLoc,
11685 SourceLocation EndLoc) {
11686 MappableVarListInfo MVLI(VarList);
11687 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11688 if (MVLI.ProcessedVarList.empty())
11689 return nullptr;
11690
11691 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11692 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11693 MVLI.VarComponents);
11694}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011695
11696OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11697 SourceLocation StartLoc,
11698 SourceLocation LParenLoc,
11699 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011700 MappableVarListInfo MVLI(VarList);
11701 SmallVector<Expr *, 8> PrivateCopies;
11702 SmallVector<Expr *, 8> Inits;
11703
Carlo Bertolli2404b172016-07-13 15:37:16 +000011704 for (auto &RefExpr : VarList) {
11705 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11706 SourceLocation ELoc;
11707 SourceRange ERange;
11708 Expr *SimpleRefExpr = RefExpr;
11709 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11710 if (Res.second) {
11711 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011712 MVLI.ProcessedVarList.push_back(RefExpr);
11713 PrivateCopies.push_back(nullptr);
11714 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011715 }
11716 ValueDecl *D = Res.first;
11717 if (!D)
11718 continue;
11719
11720 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011721 Type = Type.getNonReferenceType().getUnqualifiedType();
11722
11723 auto *VD = dyn_cast<VarDecl>(D);
11724
11725 // Item should be a pointer or reference to pointer.
11726 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011727 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11728 << 0 << RefExpr->getSourceRange();
11729 continue;
11730 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011731
11732 // Build the private variable and the expression that refers to it.
11733 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11734 D->hasAttrs() ? &D->getAttrs() : nullptr);
11735 if (VDPrivate->isInvalidDecl())
11736 continue;
11737
11738 CurContext->addDecl(VDPrivate);
11739 auto VDPrivateRefExpr = buildDeclRefExpr(
11740 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11741
11742 // Add temporary variable to initialize the private copy of the pointer.
11743 auto *VDInit =
11744 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11745 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11746 RefExpr->getExprLoc());
11747 AddInitializerToDecl(VDPrivate,
11748 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011749 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011750
11751 // If required, build a capture to implement the privatization initialized
11752 // with the current list item value.
11753 DeclRefExpr *Ref = nullptr;
11754 if (!VD)
11755 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11756 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11757 PrivateCopies.push_back(VDPrivateRefExpr);
11758 Inits.push_back(VDInitRefExpr);
11759
11760 // We need to add a data sharing attribute for this variable to make sure it
11761 // is correctly captured. A variable that shows up in a use_device_ptr has
11762 // similar properties of a first private variable.
11763 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11764
11765 // Create a mappable component for the list item. List items in this clause
11766 // only need a component.
11767 MVLI.VarBaseDeclarations.push_back(D);
11768 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11769 MVLI.VarComponents.back().push_back(
11770 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011771 }
11772
Samuel Antaocc10b852016-07-28 14:23:26 +000011773 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011774 return nullptr;
11775
Samuel Antaocc10b852016-07-28 14:23:26 +000011776 return OMPUseDevicePtrClause::Create(
11777 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11778 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011779}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011780
11781OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11782 SourceLocation StartLoc,
11783 SourceLocation LParenLoc,
11784 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011785 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011786 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011787 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011788 SourceLocation ELoc;
11789 SourceRange ERange;
11790 Expr *SimpleRefExpr = RefExpr;
11791 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11792 if (Res.second) {
11793 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011794 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011795 }
11796 ValueDecl *D = Res.first;
11797 if (!D)
11798 continue;
11799
11800 QualType Type = D->getType();
11801 // item should be a pointer or array or reference to pointer or array
11802 if (!Type.getNonReferenceType()->isPointerType() &&
11803 !Type.getNonReferenceType()->isArrayType()) {
11804 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11805 << 0 << RefExpr->getSourceRange();
11806 continue;
11807 }
Samuel Antao6890b092016-07-28 14:25:09 +000011808
11809 // Check if the declaration in the clause does not show up in any data
11810 // sharing attribute.
11811 auto DVar = DSAStack->getTopDSA(D, false);
11812 if (isOpenMPPrivate(DVar.CKind)) {
11813 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11814 << getOpenMPClauseName(DVar.CKind)
11815 << getOpenMPClauseName(OMPC_is_device_ptr)
11816 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11817 ReportOriginalDSA(*this, DSAStack, D, DVar);
11818 continue;
11819 }
11820
11821 Expr *ConflictExpr;
11822 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011823 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011824 [&ConflictExpr](
11825 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11826 OpenMPClauseKind) -> bool {
11827 ConflictExpr = R.front().getAssociatedExpression();
11828 return true;
11829 })) {
11830 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11831 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11832 << ConflictExpr->getSourceRange();
11833 continue;
11834 }
11835
11836 // Store the components in the stack so that they can be used to check
11837 // against other clauses later on.
11838 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11839 DSAStack->addMappableExpressionComponents(
11840 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11841
11842 // Record the expression we've just processed.
11843 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11844
11845 // Create a mappable component for the list item. List items in this clause
11846 // only need a component. We use a null declaration to signal fields in
11847 // 'this'.
11848 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11849 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11850 "Unexpected device pointer expression!");
11851 MVLI.VarBaseDeclarations.push_back(
11852 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11853 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11854 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011855 }
11856
Samuel Antao6890b092016-07-28 14:25:09 +000011857 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011858 return nullptr;
11859
Samuel Antao6890b092016-07-28 14:25:09 +000011860 return OMPIsDevicePtrClause::Create(
11861 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11862 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011863}