blob: b1c57628aa638fad768d803cb3fec8709909788b [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000121 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000122 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
123 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000124 /// \brief true, if check for DSA must be from parent directive, false, if
125 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000127 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000129 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130
131 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
132
David Majnemer9d168222016-08-05 17:44:54 +0000133 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000134
135 /// \brief Checks if the variable is a local for OpenMP region.
136 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000137
Alexey Bataev4b465392017-04-26 15:06:24 +0000138 bool isStackEmpty() const {
139 return Stack.empty() ||
140 Stack.back().second != CurrentNonCapturingFunctionScope ||
141 Stack.back().first.empty();
142 }
143
Alexey Bataev758e55e2013-09-06 18:03:48 +0000144public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000145 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000146
Alexey Bataevaac108a2015-06-23 04:51:00 +0000147 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
148 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000150 bool isForceVarCapturing() const { return ForceCapturing; }
151 void setForceVarCapturing(bool V) { ForceCapturing = V; }
152
Alexey Bataev758e55e2013-09-06 18:03:48 +0000153 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000154 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 if (Stack.empty() ||
156 Stack.back().second != CurrentNonCapturingFunctionScope)
157 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
158 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
159 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 }
161
162 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000163 assert(!Stack.back().first.empty() &&
164 "Data-sharing attributes stack is empty!");
165 Stack.back().first.pop_back();
166 }
167
168 /// Start new OpenMP region stack in new non-capturing function.
169 void pushFunction() {
170 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
171 assert(!isa<CapturingScopeInfo>(CurFnScope));
172 CurrentNonCapturingFunctionScope = CurFnScope;
173 }
174 /// Pop region stack for non-capturing function.
175 void popFunction(const FunctionScopeInfo *OldFSI) {
176 if (!Stack.empty() && Stack.back().second == OldFSI) {
177 assert(Stack.back().first.empty());
178 Stack.pop_back();
179 }
180 CurrentNonCapturingFunctionScope = nullptr;
181 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
182 if (!isa<CapturingScopeInfo>(FSI)) {
183 CurrentNonCapturingFunctionScope = FSI;
184 break;
185 }
186 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 }
188
Alexey Bataev28c75412015-12-15 08:19:24 +0000189 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
190 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
191 }
192 const std::pair<OMPCriticalDirective *, llvm::APSInt>
193 getCriticalWithHint(const DeclarationNameInfo &Name) const {
194 auto I = Criticals.find(Name.getAsString());
195 if (I != Criticals.end())
196 return I->second;
197 return std::make_pair(nullptr, llvm::APSInt());
198 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000199 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000200 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000201 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000202 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000203
Alexey Bataev9c821032015-04-30 04:23:23 +0000204 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000205 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000206 /// \brief Check if the specified variable is a loop control variable for
207 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000208 /// \return The index of the loop control variable in the list of associated
209 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000210 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000211 /// \brief Check if the specified variable is a loop control variable for
212 /// parent region.
213 /// \return The index of the loop control variable in the list of associated
214 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000215 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000216 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
217 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000218 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000219
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000221 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
222 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000223
Alexey Bataev758e55e2013-09-06 18:03:48 +0000224 /// \brief Returns data sharing attributes from top of the stack for the
225 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000226 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000227 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000228 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000229 /// \brief Checks if the specified variables has data-sharing attributes which
230 /// match specified \a CPred predicate in any directive which matches \a DPred
231 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000232 DSAVarData hasDSA(ValueDecl *D,
233 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
234 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
235 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000236 /// \brief Checks if the specified variables has data-sharing attributes which
237 /// match specified \a CPred predicate in any innermost directive which
238 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000239 DSAVarData
240 hasInnermostDSA(ValueDecl *D,
241 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
242 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
243 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000244 /// \brief Checks if the specified variables has explicit data-sharing
245 /// attributes which match specified \a CPred predicate at the specified
246 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000247 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000248 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000249 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000250
251 /// \brief Returns true if the directive at level \Level matches in the
252 /// specified \a DPred predicate.
253 bool hasExplicitDirective(
254 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
255 unsigned Level);
256
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000257 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000258 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
259 const DeclarationNameInfo &,
260 SourceLocation)> &DPred,
261 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000262
Alexey Bataev758e55e2013-09-06 18:03:48 +0000263 /// \brief Returns currently analyzed directive.
264 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000265 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000267 /// \brief Returns parent directive.
268 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000269 if (isStackEmpty() || Stack.back().first.size() == 1)
270 return OMPD_unknown;
271 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000272 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273
274 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000275 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000276 assert(!isStackEmpty());
277 Stack.back().first.back().DefaultAttr = DSA_none;
278 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000279 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000280 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000281 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000282 assert(!isStackEmpty());
283 Stack.back().first.back().DefaultAttr = DSA_shared;
284 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000285 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000286
287 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000288 return isStackEmpty() ? DSA_unspecified
289 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000291 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000292 return isStackEmpty() ? SourceLocation()
293 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000294 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000295
Alexey Bataevf29276e2014-06-18 04:14:57 +0000296 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000297 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000298 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000299 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000300 }
301
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000303 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000304 assert(!isStackEmpty());
305 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
306 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000307 }
308 /// \brief Returns true, if parent region is ordered (has associated
309 /// 'ordered' clause), false - otherwise.
310 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000311 if (isStackEmpty() || Stack.back().first.size() == 1)
312 return false;
313 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000314 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000315 /// \brief Returns optional parameter for the ordered region.
316 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000317 if (isStackEmpty() || Stack.back().first.size() == 1)
318 return nullptr;
319 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000320 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000321 /// \brief Marks current region as nowait (it has a 'nowait' clause).
322 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000323 assert(!isStackEmpty());
324 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000325 }
326 /// \brief Returns true, if parent region is nowait (has associated
327 /// 'nowait' clause), false - otherwise.
328 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000329 if (isStackEmpty() || Stack.back().first.size() == 1)
330 return false;
331 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000332 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000333 /// \brief Marks parent region as cancel region.
334 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 if (!isStackEmpty() && Stack.back().first.size() > 1) {
336 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
337 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
338 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000339 }
340 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000341 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000342 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000343 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000344
Alexey Bataev9c821032015-04-30 04:23:23 +0000345 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000346 void setAssociatedLoops(unsigned Val) {
347 assert(!isStackEmpty());
348 Stack.back().first.back().AssociatedLoops = Val;
349 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000350 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000351 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000352 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000353 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000354
Alexey Bataev13314bf2014-10-09 04:18:56 +0000355 /// \brief Marks current target region as one with closely nested teams
356 /// region.
357 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000358 if (!isStackEmpty() && Stack.back().first.size() > 1) {
359 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
360 TeamsRegionLoc;
361 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000362 }
363 /// \brief Returns true, if current region has closely nested teams region.
364 bool hasInnerTeamsRegion() const {
365 return getInnerTeamsRegionLoc().isValid();
366 }
367 /// \brief Returns location of the nested teams region (if any).
368 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000369 return isStackEmpty() ? SourceLocation()
370 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000371 }
372
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000373 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000374 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000375 }
376 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000377 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000378 }
379 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000380 return isStackEmpty() ? SourceLocation()
381 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000382 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000383
Samuel Antao4c8035b2016-12-12 18:00:20 +0000384 /// Do the check specified in \a Check to all component lists and return true
385 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000386 bool checkMappableExprComponentListsForDecl(
387 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000388 const llvm::function_ref<
389 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
390 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000391 if (isStackEmpty())
392 return false;
393 auto SI = Stack.back().first.rbegin();
394 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000395
396 if (SI == SE)
397 return false;
398
399 if (CurrentRegionOnly) {
400 SE = std::next(SI);
401 } else {
402 ++SI;
403 }
404
405 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000406 auto MI = SI->MappedExprComponents.find(VD);
407 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000408 for (auto &L : MI->second.Components)
409 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000410 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000411 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000412 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000413 }
414
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 Bataev48c0bfb2016-01-20 09:07:54 +0000482static ValueDecl *getCanonicalDecl(ValueDecl *D) {
483 auto *VD = dyn_cast<VarDecl>(D);
484 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000485 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000486 VD = VD->getCanonicalDecl();
487 D = VD;
488 } else {
489 assert(FD);
490 FD = FD->getCanonicalDecl();
491 D = FD;
492 }
493 return D;
494}
495
David Majnemer9d168222016-08-05 17:44:54 +0000496DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000497 ValueDecl *D) {
498 D = getCanonicalDecl(D);
499 auto *VD = dyn_cast<VarDecl>(D);
500 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000501 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000502 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000503 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
504 // in a region but not in construct]
505 // File-scope or namespace-scope variables referenced in called routines
506 // in the region are shared unless they appear in a threadprivate
507 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000508 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000509 DVar.CKind = OMPC_shared;
510
511 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
512 // in a region but not in construct]
513 // Variables with static storage duration that are declared in called
514 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000515 if (VD && VD->hasGlobalStorage())
516 DVar.CKind = OMPC_shared;
517
518 // Non-static data members are shared by default.
519 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000520 DVar.CKind = OMPC_shared;
521
Alexey Bataev758e55e2013-09-06 18:03:48 +0000522 return DVar;
523 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000524
Alexey Bataev758e55e2013-09-06 18:03:48 +0000525 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000526 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
527 // in a Construct, C/C++, predetermined, p.1]
528 // Variables with automatic storage duration that are declared in a scope
529 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000530 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
531 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000532 DVar.CKind = OMPC_private;
533 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000534 }
535
Alexey Bataev758e55e2013-09-06 18:03:48 +0000536 // Explicitly specified attributes and local variables with predetermined
537 // attributes.
538 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000539 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000540 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000541 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000542 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543 return DVar;
544 }
545
546 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
547 // in a Construct, C/C++, implicitly determined, p.1]
548 // In a parallel or task construct, the data-sharing attributes of these
549 // variables are determined by the default clause, if present.
550 switch (Iter->DefaultAttr) {
551 case DSA_shared:
552 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000553 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000554 return DVar;
555 case DSA_none:
556 return DVar;
557 case DSA_unspecified:
558 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
559 // in a Construct, implicitly determined, p.2]
560 // In a parallel construct, if no default clause is present, these
561 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000562 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000563 if (isOpenMPParallelDirective(DVar.DKind) ||
564 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000565 DVar.CKind = OMPC_shared;
566 return DVar;
567 }
568
569 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
570 // in a Construct, implicitly determined, p.4]
571 // In a task construct, if no default clause is present, a variable that in
572 // the enclosing context is determined to be shared by all implicit tasks
573 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000574 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000575 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000576 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000577 do {
578 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000579 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000580 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000581 // In a task construct, if no default clause is present, a variable
582 // whose data-sharing attribute is not determined by the rules above is
583 // firstprivate.
584 DVarTemp = getDSA(I, D);
585 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000586 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000587 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000588 return DVar;
589 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000590 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000591 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000592 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000593 return DVar;
594 }
595 }
596 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
597 // in a Construct, implicitly determined, p.3]
598 // For constructs other than task, if no default clause is present, these
599 // variables inherit their data-sharing attributes from the enclosing
600 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000601 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000602}
603
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000604Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000605 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000606 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000607 auto &StackElem = Stack.back().first.back();
608 auto It = StackElem.AlignedMap.find(D);
609 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000610 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000611 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000612 return nullptr;
613 } else {
614 assert(It->second && "Unexpected nullptr expr in the aligned map");
615 return It->second;
616 }
617 return nullptr;
618}
619
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000620void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000621 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000622 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000623 auto &StackElem = Stack.back().first.back();
624 StackElem.LCVMap.insert(
625 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000626}
627
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000628DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000629 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000630 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000631 auto &StackElem = Stack.back().first.back();
632 auto It = StackElem.LCVMap.find(D);
633 if (It != StackElem.LCVMap.end())
634 return It->second;
635 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000636}
637
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000638DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000639 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
640 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000641 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000642 auto &StackElem = *std::next(Stack.back().first.rbegin());
643 auto It = StackElem.LCVMap.find(D);
644 if (It != StackElem.LCVMap.end())
645 return It->second;
646 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000647}
648
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000649ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000650 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
651 "Data-sharing attributes stack is empty");
652 auto &StackElem = *std::next(Stack.back().first.rbegin());
653 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000654 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000655 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000656 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000657 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000658 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000659}
660
Alexey Bataev90c228f2016-02-08 09:29:13 +0000661void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
662 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000663 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000664 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000665 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000666 Data.Attributes = A;
667 Data.RefExpr.setPointer(E);
668 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000669 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000670 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
671 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000672 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
673 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
674 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
675 (isLoopControlVariable(D).first && A == OMPC_private));
676 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
677 Data.RefExpr.setInt(/*IntVal=*/true);
678 return;
679 }
680 const bool IsLastprivate =
681 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
682 Data.Attributes = A;
683 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
684 Data.PrivateCopy = PrivateCopy;
685 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000686 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000687 Data.Attributes = A;
688 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
689 Data.PrivateCopy = nullptr;
690 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691 }
692}
693
Alexey Bataeved09d242014-05-28 05:53:51 +0000694bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000695 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000696 if (!isStackEmpty() && Stack.back().first.size() > 1) {
697 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000698 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000699 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000700 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000701 if (I == E)
702 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000704 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000705 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000706 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000707 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000709 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000710}
711
Alexey Bataev39f915b82015-05-08 10:41:21 +0000712/// \brief Build a variable declaration for OpenMP loop iteration variable.
713static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000714 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000715 DeclContext *DC = SemaRef.CurContext;
716 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
717 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
718 VarDecl *Decl =
719 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000720 if (Attrs) {
721 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
722 I != E; ++I)
723 Decl->addAttr(*I);
724 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000725 Decl->setImplicit();
726 return Decl;
727}
728
729static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
730 SourceLocation Loc,
731 bool RefersToCapture = false) {
732 D->setReferenced();
733 D->markUsed(S.Context);
734 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
735 SourceLocation(), D, RefersToCapture, Loc, Ty,
736 VK_LValue);
737}
738
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000739DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
740 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000741 DSAVarData DVar;
742
743 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
744 // in a Construct, C/C++, predetermined, p.1]
745 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000746 auto *VD = dyn_cast<VarDecl>(D);
747 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
748 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000749 SemaRef.getLangOpts().OpenMPUseTLS &&
750 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000751 (VD && VD->getStorageClass() == SC_Register &&
752 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
753 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000754 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000755 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000756 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000757 auto TI = Threadprivates.find(D);
758 if (TI != Threadprivates.end()) {
759 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000760 DVar.CKind = OMPC_threadprivate;
761 return DVar;
762 }
763
Alexey Bataev4b465392017-04-26 15:06:24 +0000764 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000765 // Not in OpenMP execution region and top scope was already checked.
766 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000767
Alexey Bataev758e55e2013-09-06 18:03:48 +0000768 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000769 // in a Construct, C/C++, predetermined, p.4]
770 // Static data members are shared.
771 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
772 // in a Construct, C/C++, predetermined, p.7]
773 // Variables with static storage duration that are declared in a scope
774 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000775 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000776 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000777 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000778 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000779 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000780
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000781 DVar.CKind = OMPC_shared;
782 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000783 }
784
785 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000786 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
787 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000788 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
789 // in a Construct, C/C++, predetermined, p.6]
790 // Variables with const qualified type having no mutable member are
791 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000792 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000793 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000794 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
795 if (auto *CTD = CTSD->getSpecializedTemplate())
796 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000797 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000798 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
799 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000800 // Variables with const-qualified type having no mutable member may be
801 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000802 DSAVarData DVarTemp = hasDSA(
803 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
804 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000805 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
806 return DVar;
807
Alexey Bataev758e55e2013-09-06 18:03:48 +0000808 DVar.CKind = OMPC_shared;
809 return DVar;
810 }
811
Alexey Bataev758e55e2013-09-06 18:03:48 +0000812 // Explicitly specified attributes and local variables with predetermined
813 // attributes.
Alexey Bataev4b465392017-04-26 15:06:24 +0000814 auto StartI = std::next(Stack.back().first.rbegin());
815 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000816 if (FromParent && StartI != EndI)
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000817 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000818 auto I = std::prev(StartI);
819 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000820 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000821 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000822 DVar.CKind = I->SharingMap[D].Attributes;
823 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000824 }
825
826 return DVar;
827}
828
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000829DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
830 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000831 if (isStackEmpty()) {
832 StackTy::reverse_iterator I;
833 return getDSA(I, D);
834 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000835 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000836 auto StartI = Stack.back().first.rbegin();
837 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000838 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000839 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000840 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000841}
842
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000843DSAStackTy::DSAVarData
844DSAStackTy::hasDSA(ValueDecl *D,
845 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
846 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
847 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000848 if (isStackEmpty())
849 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000850 D = getCanonicalDecl(D);
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +0000851 auto I = (FromParent && Stack.back().first.size() > 1)
852 ? std::next(Stack.back().first.rbegin())
853 : Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000854 auto EndI = Stack.back().first.rend();
Alexey Bataev60859c02017-04-27 15:10:33 +0000855 while (std::distance(I, EndI) > 1) {
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +0000856 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000857 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000858 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000859 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000860 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000861 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +0000862 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000863 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000864}
865
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000866DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
867 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
868 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
869 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000870 if (isStackEmpty())
871 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000872 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000873 auto StartI = std::next(Stack.back().first.rbegin());
874 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000875 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000876 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000877 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +0000878 return {};
Alexey Bataeve3978122016-07-19 05:06:39 +0000879 DSAVarData DVar = getDSA(StartI, D);
880 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000881}
882
Alexey Bataevaac108a2015-06-23 04:51:00 +0000883bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000884 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000885 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000886 if (CPred(ClauseKindMode))
887 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000888 if (isStackEmpty())
889 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000890 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000891 auto StartI = Stack.back().first.begin();
892 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000893 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000894 return false;
895 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000896 return (StartI->SharingMap.count(D) > 0) &&
897 StartI->SharingMap[D].RefExpr.getPointer() &&
898 CPred(StartI->SharingMap[D].Attributes) &&
899 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000900}
901
Samuel Antao4be30e92015-10-02 17:14:03 +0000902bool DSAStackTy::hasExplicitDirective(
903 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
904 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000905 if (isStackEmpty())
906 return false;
907 auto StartI = Stack.back().first.begin();
908 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000909 if (std::distance(StartI, EndI) <= (int)Level)
910 return false;
911 std::advance(StartI, Level);
912 return DPred(StartI->Directive);
913}
914
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000915bool DSAStackTy::hasDirective(
916 const llvm::function_ref<bool(OpenMPDirectiveKind,
917 const DeclarationNameInfo &, SourceLocation)>
918 &DPred,
919 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000920 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000921 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +0000922 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +0000923 auto StartI = std::next(Stack.back().first.rbegin());
924 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000925 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000926 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000927 for (auto I = StartI, EE = EndI; I != EE; ++I) {
928 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
929 return true;
930 }
931 return false;
932}
933
Alexey Bataev758e55e2013-09-06 18:03:48 +0000934void Sema::InitDataSharingAttributesStack() {
935 VarDataSharingAttributesStack = new DSAStackTy(*this);
936}
937
938#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
939
Alexey Bataev4b465392017-04-26 15:06:24 +0000940void Sema::pushOpenMPFunctionRegion() {
941 DSAStack->pushFunction();
942}
943
944void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
945 DSAStack->popFunction(OldFSI);
946}
947
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000948bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000949 assert(LangOpts.OpenMP && "OpenMP is not allowed");
950
951 auto &Ctx = getASTContext();
952 bool IsByRef = true;
953
954 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000955 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000956
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000957 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 // This table summarizes how a given variable should be passed to the device
959 // given its type and the clauses where it appears. This table is based on
960 // the description in OpenMP 4.5 [2.10.4, target Construct] and
961 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
962 //
963 // =========================================================================
964 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
965 // | |(tofrom:scalar)| | pvt | | | |
966 // =========================================================================
967 // | scl | | | | - | | bycopy|
968 // | scl | | - | x | - | - | bycopy|
969 // | scl | | x | - | - | - | null |
970 // | scl | x | | | - | | byref |
971 // | scl | x | - | x | - | - | bycopy|
972 // | scl | x | x | - | - | - | null |
973 // | scl | | - | - | - | x | byref |
974 // | scl | x | - | - | - | x | byref |
975 //
976 // | agg | n.a. | | | - | | byref |
977 // | agg | n.a. | - | x | - | - | byref |
978 // | agg | n.a. | x | - | - | - | null |
979 // | agg | n.a. | - | - | - | x | byref |
980 // | agg | n.a. | - | - | - | x[] | byref |
981 //
982 // | ptr | n.a. | | | - | | bycopy|
983 // | ptr | n.a. | - | x | - | - | bycopy|
984 // | ptr | n.a. | x | - | - | - | null |
985 // | ptr | n.a. | - | - | - | x | byref |
986 // | ptr | n.a. | - | - | - | x[] | bycopy|
987 // | ptr | n.a. | - | - | x | | bycopy|
988 // | ptr | n.a. | - | - | x | x | bycopy|
989 // | ptr | n.a. | - | - | x | x[] | bycopy|
990 // =========================================================================
991 // Legend:
992 // scl - scalar
993 // ptr - pointer
994 // agg - aggregate
995 // x - applies
996 // - - invalid in this combination
997 // [] - mapped with an array section
998 // byref - should be mapped by reference
999 // byval - should be mapped by value
1000 // null - initialize a local variable to null on the device
1001 //
1002 // Observations:
1003 // - All scalar declarations that show up in a map clause have to be passed
1004 // by reference, because they may have been mapped in the enclosing data
1005 // environment.
1006 // - If the scalar value does not fit the size of uintptr, it has to be
1007 // passed by reference, regardless the result in the table above.
1008 // - For pointers mapped by value that have either an implicit map or an
1009 // array section, the runtime library may pass the NULL value to the
1010 // device instead of the value passed to it by the compiler.
1011
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001012 if (Ty->isReferenceType())
1013 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001014
1015 // Locate map clauses and see if the variable being captured is referred to
1016 // in any of those clauses. Here we only care about variables, not fields,
1017 // because fields are part of aggregates.
1018 bool IsVariableUsedInMapClause = false;
1019 bool IsVariableAssociatedWithSection = false;
1020
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001021 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1022 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001023 MapExprComponents,
1024 OpenMPClauseKind WhereFoundClauseKind) {
1025 // Only the map clause information influences how a variable is
1026 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001027 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001028 if (WhereFoundClauseKind != OMPC_map)
1029 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001030
1031 auto EI = MapExprComponents.rbegin();
1032 auto EE = MapExprComponents.rend();
1033
1034 assert(EI != EE && "Invalid map expression!");
1035
1036 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1037 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1038
1039 ++EI;
1040 if (EI == EE)
1041 return false;
1042
1043 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1044 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1045 isa<MemberExpr>(EI->getAssociatedExpression())) {
1046 IsVariableAssociatedWithSection = true;
1047 // There is nothing more we need to know about this variable.
1048 return true;
1049 }
1050
1051 // Keep looking for more map info.
1052 return false;
1053 });
1054
1055 if (IsVariableUsedInMapClause) {
1056 // If variable is identified in a map clause it is always captured by
1057 // reference except if it is a pointer that is dereferenced somehow.
1058 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1059 } else {
1060 // By default, all the data that has a scalar type is mapped by copy.
1061 IsByRef = !Ty->isScalarType();
1062 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001063 }
1064
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001065 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1066 IsByRef = !DSAStack->hasExplicitDSA(
1067 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1068 Level, /*NotLastprivate=*/true);
1069 }
1070
Samuel Antao86ace552016-04-27 22:40:57 +00001071 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001072 // and alignment, because the runtime library only deals with uintptr types.
1073 // If it does not fit the uintptr size, we need to pass the data by reference
1074 // instead.
1075 if (!IsByRef &&
1076 (Ctx.getTypeSizeInChars(Ty) >
1077 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001078 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001079 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001080 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001081
1082 return IsByRef;
1083}
1084
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001085unsigned Sema::getOpenMPNestingLevel() const {
1086 assert(getLangOpts().OpenMP);
1087 return DSAStack->getNestingLevel();
1088}
1089
Alexey Bataev90c228f2016-02-08 09:29:13 +00001090VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001091 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001092 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001093
1094 // If we are attempting to capture a global variable in a directive with
1095 // 'target' we return true so that this global is also mapped to the device.
1096 //
1097 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1098 // then it should not be captured. Therefore, an extra check has to be
1099 // inserted here once support for 'declare target' is added.
1100 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001101 auto *VD = dyn_cast<VarDecl>(D);
1102 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001103 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001104 !DSAStack->isClauseParsingMode())
1105 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001106 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001107 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1108 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001109 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001110 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001111 false))
1112 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001113 }
1114
Alexey Bataev48977c32015-08-04 08:10:48 +00001115 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1116 (!DSAStack->isClauseParsingMode() ||
1117 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001118 auto &&Info = DSAStack->isLoopControlVariable(D);
1119 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001120 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001121 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001122 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001123 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001124 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001125 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001126 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001127 DVarPrivate = DSAStack->hasDSA(
1128 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1129 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001130 if (DVarPrivate.CKind != OMPC_unknown)
1131 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001132 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001133 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001134}
1135
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001136bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001137 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1138 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001139 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001140}
1141
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001142bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001143 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1144 // Return true if the current level is no longer enclosed in a target region.
1145
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001146 auto *VD = dyn_cast<VarDecl>(D);
1147 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001148 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1149 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001150}
1151
Alexey Bataeved09d242014-05-28 05:53:51 +00001152void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001153
1154void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1155 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001156 Scope *CurScope, SourceLocation Loc) {
1157 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001158 PushExpressionEvaluationContext(
1159 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001160}
1161
Alexey Bataevaac108a2015-06-23 04:51:00 +00001162void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1163 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001164}
1165
Alexey Bataevaac108a2015-06-23 04:51:00 +00001166void Sema::EndOpenMPClause() {
1167 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001168}
1169
Alexey Bataev758e55e2013-09-06 18:03:48 +00001170void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001171 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1172 // A variable of class type (or array thereof) that appears in a lastprivate
1173 // clause requires an accessible, unambiguous default constructor for the
1174 // class type, unless the list item is also specified in a firstprivate
1175 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001176 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001177 for (auto *C : D->clauses()) {
1178 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1179 SmallVector<Expr *, 8> PrivateCopies;
1180 for (auto *DE : Clause->varlists()) {
1181 if (DE->isValueDependent() || DE->isTypeDependent()) {
1182 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001183 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001184 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001185 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001186 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1187 QualType Type = VD->getType().getNonReferenceType();
1188 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001189 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001190 // Generate helper private variable and initialize it with the
1191 // default value. The address of the original variable is replaced
1192 // by the address of the new private variable in CodeGen. This new
1193 // variable is not added to IdResolver, so the code in the OpenMP
1194 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001195 auto *VDPrivate = buildVarDecl(
1196 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001197 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001198 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001199 if (VDPrivate->isInvalidDecl())
1200 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001201 PrivateCopies.push_back(buildDeclRefExpr(
1202 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001203 } else {
1204 // The variable is also a firstprivate, so initialization sequence
1205 // for private copy is generated already.
1206 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001207 }
1208 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001209 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001210 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001211 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001212 }
1213 }
1214 }
1215
Alexey Bataev758e55e2013-09-06 18:03:48 +00001216 DSAStack->pop();
1217 DiscardCleanupsInEvaluationContext();
1218 PopExpressionEvaluationContext();
1219}
1220
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001221static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1222 Expr *NumIterations, Sema &SemaRef,
1223 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001224
Alexey Bataeva769e072013-03-22 06:34:35 +00001225namespace {
1226
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001227class VarDeclFilterCCC : public CorrectionCandidateCallback {
1228private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001229 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001230
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001231public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001232 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001233 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001234 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001235 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001236 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001237 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1238 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001239 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001240 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001241 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001242};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001243
1244class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1245private:
1246 Sema &SemaRef;
1247
1248public:
1249 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1250 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1251 NamedDecl *ND = Candidate.getCorrectionDecl();
1252 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1253 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1254 SemaRef.getCurScope());
1255 }
1256 return false;
1257 }
1258};
1259
Alexey Bataeved09d242014-05-28 05:53:51 +00001260} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001261
1262ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1263 CXXScopeSpec &ScopeSpec,
1264 const DeclarationNameInfo &Id) {
1265 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1266 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1267
1268 if (Lookup.isAmbiguous())
1269 return ExprError();
1270
1271 VarDecl *VD;
1272 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001273 if (TypoCorrection Corrected = CorrectTypo(
1274 Id, LookupOrdinaryName, CurScope, nullptr,
1275 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001276 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001277 PDiag(Lookup.empty()
1278 ? diag::err_undeclared_var_use_suggest
1279 : diag::err_omp_expected_var_arg_suggest)
1280 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001281 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001282 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001283 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1284 : diag::err_omp_expected_var_arg)
1285 << Id.getName();
1286 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001287 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001288 } else {
1289 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001290 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001291 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1292 return ExprError();
1293 }
1294 }
1295 Lookup.suppressDiagnostics();
1296
1297 // OpenMP [2.9.2, Syntax, C/C++]
1298 // Variables must be file-scope, namespace-scope, or static block-scope.
1299 if (!VD->hasGlobalStorage()) {
1300 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001301 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1302 bool IsDecl =
1303 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001304 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001305 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1306 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001307 return ExprError();
1308 }
1309
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001310 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1311 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001312 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1313 // A threadprivate directive for file-scope variables must appear outside
1314 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001315 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1316 !getCurLexicalContext()->isTranslationUnit()) {
1317 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001318 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1319 bool IsDecl =
1320 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1321 Diag(VD->getLocation(),
1322 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1323 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001324 return ExprError();
1325 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1327 // A threadprivate directive for static class member variables must appear
1328 // in the class definition, in the same scope in which the member
1329 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001330 if (CanonicalVD->isStaticDataMember() &&
1331 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1332 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001333 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1334 bool IsDecl =
1335 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1336 Diag(VD->getLocation(),
1337 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1338 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001339 return ExprError();
1340 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001341 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1342 // A threadprivate directive for namespace-scope variables must appear
1343 // outside any definition or declaration other than the namespace
1344 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001345 if (CanonicalVD->getDeclContext()->isNamespace() &&
1346 (!getCurLexicalContext()->isFileContext() ||
1347 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1348 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001349 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1350 bool IsDecl =
1351 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1352 Diag(VD->getLocation(),
1353 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1354 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001355 return ExprError();
1356 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001357 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1358 // A threadprivate directive for static block-scope variables must appear
1359 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001360 if (CanonicalVD->isStaticLocal() && CurScope &&
1361 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001362 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001363 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1364 bool IsDecl =
1365 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1366 Diag(VD->getLocation(),
1367 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1368 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001369 return ExprError();
1370 }
1371
1372 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1373 // A threadprivate directive must lexically precede all references to any
1374 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001375 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001376 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001377 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001378 return ExprError();
1379 }
1380
1381 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001382 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1383 SourceLocation(), VD,
1384 /*RefersToEnclosingVariableOrCapture=*/false,
1385 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001386}
1387
Alexey Bataeved09d242014-05-28 05:53:51 +00001388Sema::DeclGroupPtrTy
1389Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1390 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001391 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 CurContext->addDecl(D);
1393 return DeclGroupPtrTy::make(DeclGroupRef(D));
1394 }
David Blaikie0403cb12016-01-15 23:43:25 +00001395 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001396}
1397
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001398namespace {
1399class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1400 Sema &SemaRef;
1401
1402public:
1403 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001404 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001405 if (VD->hasLocalStorage()) {
1406 SemaRef.Diag(E->getLocStart(),
1407 diag::err_omp_local_var_in_threadprivate_init)
1408 << E->getSourceRange();
1409 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1410 << VD << VD->getSourceRange();
1411 return true;
1412 }
1413 }
1414 return false;
1415 }
1416 bool VisitStmt(const Stmt *S) {
1417 for (auto Child : S->children()) {
1418 if (Child && Visit(Child))
1419 return true;
1420 }
1421 return false;
1422 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001423 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001424};
1425} // namespace
1426
Alexey Bataeved09d242014-05-28 05:53:51 +00001427OMPThreadPrivateDecl *
1428Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001429 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001430 for (auto &RefExpr : VarList) {
1431 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001432 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1433 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001434
Alexey Bataev376b4a42016-02-09 09:41:09 +00001435 // Mark variable as used.
1436 VD->setReferenced();
1437 VD->markUsed(Context);
1438
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001439 QualType QType = VD->getType();
1440 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1441 // It will be analyzed later.
1442 Vars.push_back(DE);
1443 continue;
1444 }
1445
Alexey Bataeva769e072013-03-22 06:34:35 +00001446 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1447 // A threadprivate variable must not have an incomplete type.
1448 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001449 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001450 continue;
1451 }
1452
1453 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1454 // A threadprivate variable must not have a reference type.
1455 if (VD->getType()->isReferenceType()) {
1456 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001457 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1458 bool IsDecl =
1459 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1460 Diag(VD->getLocation(),
1461 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1462 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001463 continue;
1464 }
1465
Samuel Antaof8b50122015-07-13 22:54:53 +00001466 // Check if this is a TLS variable. If TLS is not being supported, produce
1467 // the corresponding diagnostic.
1468 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1469 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1470 getLangOpts().OpenMPUseTLS &&
1471 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001472 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1473 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001474 Diag(ILoc, diag::err_omp_var_thread_local)
1475 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001476 bool IsDecl =
1477 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1478 Diag(VD->getLocation(),
1479 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1480 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001481 continue;
1482 }
1483
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001484 // Check if initial value of threadprivate variable reference variable with
1485 // local storage (it is not supported by runtime).
1486 if (auto Init = VD->getAnyInitializer()) {
1487 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001488 if (Checker.Visit(Init))
1489 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001490 }
1491
Alexey Bataeved09d242014-05-28 05:53:51 +00001492 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001493 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001494 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1495 Context, SourceRange(Loc, Loc)));
1496 if (auto *ML = Context.getASTMutationListener())
1497 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001498 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001499 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001500 if (!Vars.empty()) {
1501 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1502 Vars);
1503 D->setAccess(AS_public);
1504 }
1505 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001506}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001507
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001509 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001510 bool IsLoopIterVar = false) {
1511 if (DVar.RefExpr) {
1512 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1513 << getOpenMPClauseName(DVar.CKind);
1514 return;
1515 }
1516 enum {
1517 PDSA_StaticMemberShared,
1518 PDSA_StaticLocalVarShared,
1519 PDSA_LoopIterVarPrivate,
1520 PDSA_LoopIterVarLinear,
1521 PDSA_LoopIterVarLastprivate,
1522 PDSA_ConstVarShared,
1523 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001524 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001525 PDSA_LocalVarPrivate,
1526 PDSA_Implicit
1527 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001528 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001529 auto ReportLoc = D->getLocation();
1530 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001531 if (IsLoopIterVar) {
1532 if (DVar.CKind == OMPC_private)
1533 Reason = PDSA_LoopIterVarPrivate;
1534 else if (DVar.CKind == OMPC_lastprivate)
1535 Reason = PDSA_LoopIterVarLastprivate;
1536 else
1537 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001538 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1539 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001540 Reason = PDSA_TaskVarFirstprivate;
1541 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001542 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001543 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001544 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001545 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001546 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001547 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001548 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001549 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001550 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001551 ReportHint = true;
1552 Reason = PDSA_LocalVarPrivate;
1553 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001554 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001555 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001556 << Reason << ReportHint
1557 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1558 } else if (DVar.ImplicitDSALoc.isValid()) {
1559 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1560 << getOpenMPClauseName(DVar.CKind);
1561 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001562}
1563
Alexey Bataev758e55e2013-09-06 18:03:48 +00001564namespace {
1565class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1566 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001567 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001568 bool ErrorFound;
1569 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001570 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001571 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001572
Alexey Bataev758e55e2013-09-06 18:03:48 +00001573public:
1574 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001575 if (E->isTypeDependent() || E->isValueDependent() ||
1576 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1577 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001578 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001580 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1581 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001582
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001583 auto DVar = Stack->getTopDSA(VD, false);
1584 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001585 if (DVar.RefExpr)
1586 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001587
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001588 auto ELoc = E->getExprLoc();
1589 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590 // The default(none) clause requires that each variable that is referenced
1591 // in the construct, and does not have a predetermined data-sharing
1592 // attribute, must have its data-sharing attribute explicitly determined
1593 // by being listed in a data-sharing attribute clause.
1594 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001595 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001596 VarsWithInheritedDSA.count(VD) == 0) {
1597 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001598 return;
1599 }
1600
1601 // OpenMP [2.9.3.6, Restrictions, p.2]
1602 // A list item that appears in a reduction clause of the innermost
1603 // enclosing worksharing or parallel construct may not be accessed in an
1604 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001605 DVar = Stack->hasInnermostDSA(
1606 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1607 [](OpenMPDirectiveKind K) -> bool {
1608 return isOpenMPParallelDirective(K) ||
1609 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1610 },
1611 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001612 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001613 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001614 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1615 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001616 return;
1617 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001618
1619 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001620 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001621 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1622 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001623 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001624 }
1625 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001626 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001627 if (E->isTypeDependent() || E->isValueDependent() ||
1628 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1629 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001630 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1631 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1632 auto DVar = Stack->getTopDSA(FD, false);
1633 // Check if the variable has explicit DSA set and stop analysis if it
1634 // so.
1635 if (DVar.RefExpr)
1636 return;
1637
1638 auto ELoc = E->getExprLoc();
1639 auto DKind = Stack->getCurrentDirective();
1640 // OpenMP [2.9.3.6, Restrictions, p.2]
1641 // A list item that appears in a reduction clause of the innermost
1642 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001643 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001644 DVar = Stack->hasInnermostDSA(
1645 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1646 [](OpenMPDirectiveKind K) -> bool {
1647 return isOpenMPParallelDirective(K) ||
1648 isOpenMPWorksharingDirective(K) ||
1649 isOpenMPTeamsDirective(K);
1650 },
1651 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001652 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001653 ErrorFound = true;
1654 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1655 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1656 return;
1657 }
1658
1659 // Define implicit data-sharing attributes for task.
1660 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001661 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1662 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001663 ImplicitFirstprivate.push_back(E);
1664 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001665 } else
1666 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001667 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001668 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001669 for (auto *C : S->clauses()) {
1670 // Skip analysis of arguments of implicitly defined firstprivate clause
1671 // for task directives.
1672 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1673 for (auto *CC : C->children()) {
1674 if (CC)
1675 Visit(CC);
1676 }
1677 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001678 }
1679 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001680 for (auto *C : S->children()) {
1681 if (C && !isa<OMPExecutableDirective>(C))
1682 Visit(C);
1683 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001684 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001685
1686 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001687 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001688 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001689 return VarsWithInheritedDSA;
1690 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001691
Alexey Bataev7ff55242014-06-19 09:13:45 +00001692 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1693 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001694};
Alexey Bataeved09d242014-05-28 05:53:51 +00001695} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001696
Alexey Bataevbae9a792014-06-27 10:37:06 +00001697void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001698 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001699 case OMPD_parallel:
1700 case OMPD_parallel_for:
1701 case OMPD_parallel_for_simd:
1702 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001703 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001704 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001705 QualType KmpInt32PtrTy =
1706 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001707 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001708 std::make_pair(".global_tid.", KmpInt32PtrTy),
1709 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1710 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001711 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1713 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001714 break;
1715 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001716 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001717 case OMPD_target_parallel: {
1718 Sema::CapturedParamNameType ParamsTarget[] = {
1719 std::make_pair(StringRef(), QualType()) // __context with shared vars
1720 };
1721 // Start a captured region for 'target' with no implicit parameters.
1722 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1723 ParamsTarget);
1724 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1725 QualType KmpInt32PtrTy =
1726 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001727 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001728 std::make_pair(".global_tid.", KmpInt32PtrTy),
1729 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1730 std::make_pair(StringRef(), QualType()) // __context with shared vars
1731 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001732 // Start a captured region for 'teams' or 'parallel'. Both regions have
1733 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001734 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001735 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001736 break;
1737 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001738 case OMPD_simd:
1739 case OMPD_for:
1740 case OMPD_for_simd:
1741 case OMPD_sections:
1742 case OMPD_section:
1743 case OMPD_single:
1744 case OMPD_master:
1745 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001746 case OMPD_taskgroup:
1747 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001748 case OMPD_ordered:
1749 case OMPD_atomic:
1750 case OMPD_target_data:
1751 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001752 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001753 case OMPD_target_parallel_for_simd:
1754 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001755 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001756 std::make_pair(StringRef(), QualType()) // __context with shared vars
1757 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001758 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1759 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001760 break;
1761 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001762 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001763 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001764 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1765 FunctionProtoType::ExtProtoInfo EPI;
1766 EPI.Variadic = true;
1767 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001768 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001769 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001770 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1771 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1772 std::make_pair(".copy_fn.",
1773 Context.getPointerType(CopyFnType).withConst()),
1774 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001775 std::make_pair(StringRef(), QualType()) // __context with shared vars
1776 };
1777 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1778 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001779 // Mark this captured region as inlined, because we don't use outlined
1780 // function directly.
1781 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1782 AlwaysInlineAttr::CreateImplicit(
1783 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001784 break;
1785 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001786 case OMPD_taskloop:
1787 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001788 QualType KmpInt32Ty =
1789 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1790 QualType KmpUInt64Ty =
1791 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1792 QualType KmpInt64Ty =
1793 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1794 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1795 FunctionProtoType::ExtProtoInfo EPI;
1796 EPI.Variadic = true;
1797 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001798 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001799 std::make_pair(".global_tid.", KmpInt32Ty),
1800 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1801 std::make_pair(".privates.",
1802 Context.VoidPtrTy.withConst().withRestrict()),
1803 std::make_pair(
1804 ".copy_fn.",
1805 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1806 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1807 std::make_pair(".lb.", KmpUInt64Ty),
1808 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1809 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001810 std::make_pair(".reductions.",
1811 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001812 std::make_pair(StringRef(), QualType()) // __context with shared vars
1813 };
1814 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1815 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001816 // Mark this captured region as inlined, because we don't use outlined
1817 // function directly.
1818 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1819 AlwaysInlineAttr::CreateImplicit(
1820 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001821 break;
1822 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001823 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001824 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001825 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001826 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001827 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001828 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001829 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001830 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001831 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001832 case OMPD_target_teams_distribute_parallel_for_simd:
1833 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001834 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1835 QualType KmpInt32PtrTy =
1836 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1837 Sema::CapturedParamNameType Params[] = {
1838 std::make_pair(".global_tid.", KmpInt32PtrTy),
1839 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1840 std::make_pair(".previous.lb.", Context.getSizeType()),
1841 std::make_pair(".previous.ub.", Context.getSizeType()),
1842 std::make_pair(StringRef(), QualType()) // __context with shared vars
1843 };
1844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1845 Params);
1846 break;
1847 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001848 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001849 case OMPD_taskyield:
1850 case OMPD_barrier:
1851 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001852 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001853 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001854 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001855 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001856 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001857 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001858 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001859 case OMPD_declare_target:
1860 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001861 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001862 llvm_unreachable("OpenMP Directive is not allowed");
1863 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001864 llvm_unreachable("Unknown OpenMP directive");
1865 }
1866}
1867
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001868int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1869 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1870 getOpenMPCaptureRegions(CaptureRegions, DKind);
1871 return CaptureRegions.size();
1872}
1873
Alexey Bataev3392d762016-02-16 11:18:12 +00001874static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001875 Expr *CaptureExpr, bool WithInit,
1876 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001877 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001878 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001879 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001880 QualType Ty = Init->getType();
1881 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1882 if (S.getLangOpts().CPlusPlus)
1883 Ty = C.getLValueReferenceType(Ty);
1884 else {
1885 Ty = C.getPointerType(Ty);
1886 ExprResult Res =
1887 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1888 if (!Res.isUsable())
1889 return nullptr;
1890 Init = Res.get();
1891 }
Alexey Bataev61205072016-03-02 04:57:40 +00001892 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001893 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001894 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1895 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001896 if (!WithInit)
1897 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001898 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001899 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001900 return CED;
1901}
1902
Alexey Bataev61205072016-03-02 04:57:40 +00001903static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1904 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001905 OMPCapturedExprDecl *CD;
1906 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1907 CD = cast<OMPCapturedExprDecl>(VD);
1908 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001909 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1910 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001911 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001912 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001913}
1914
Alexey Bataev5a3af132016-03-29 08:58:54 +00001915static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1916 if (!Ref) {
1917 auto *CD =
1918 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1919 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1920 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1921 CaptureExpr->getExprLoc());
1922 }
1923 ExprResult Res = Ref;
1924 if (!S.getLangOpts().CPlusPlus &&
1925 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1926 Ref->getType()->isPointerType())
1927 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1928 if (!Res.isUsable())
1929 return ExprError();
1930 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001931}
1932
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001933namespace {
1934// OpenMP directives parsed in this section are represented as a
1935// CapturedStatement with an associated statement. If a syntax error
1936// is detected during the parsing of the associated statement, the
1937// compiler must abort processing and close the CapturedStatement.
1938//
1939// Combined directives such as 'target parallel' have more than one
1940// nested CapturedStatements. This RAII ensures that we unwind out
1941// of all the nested CapturedStatements when an error is found.
1942class CaptureRegionUnwinderRAII {
1943private:
1944 Sema &S;
1945 bool &ErrorFound;
1946 OpenMPDirectiveKind DKind;
1947
1948public:
1949 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1950 OpenMPDirectiveKind DKind)
1951 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1952 ~CaptureRegionUnwinderRAII() {
1953 if (ErrorFound) {
1954 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1955 while (--ThisCaptureLevel >= 0)
1956 S.ActOnCapturedRegionError();
1957 }
1958 }
1959};
1960} // namespace
1961
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001962StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1963 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001964 bool ErrorFound = false;
1965 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1966 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001967 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001968 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001969 return StmtError();
1970 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001971
1972 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001973 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001974 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001975 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001976 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001977 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001978 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001979 Clause->getClauseKind() == OMPC_copyprivate ||
1980 (getLangOpts().OpenMPUseTLS &&
1981 getASTContext().getTargetInfo().isTLSSupported() &&
1982 Clause->getClauseKind() == OMPC_copyin)) {
1983 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001984 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001985 for (auto *VarRef : Clause->children()) {
1986 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001987 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001988 }
1989 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001990 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001991 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001992 if (auto *C = OMPClauseWithPreInit::get(Clause))
1993 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001994 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1995 if (auto *E = C->getPostUpdateExpr())
1996 MarkDeclarationsReferencedInExpr(E);
1997 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001998 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001999 if (Clause->getClauseKind() == OMPC_schedule)
2000 SC = cast<OMPScheduleClause>(Clause);
2001 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002002 OC = cast<OMPOrderedClause>(Clause);
2003 else if (Clause->getClauseKind() == OMPC_linear)
2004 LCs.push_back(cast<OMPLinearClause>(Clause));
2005 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002006 // OpenMP, 2.7.1 Loop Construct, Restrictions
2007 // The nonmonotonic modifier cannot be specified if an ordered clause is
2008 // specified.
2009 if (SC &&
2010 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2011 SC->getSecondScheduleModifier() ==
2012 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2013 OC) {
2014 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2015 ? SC->getFirstScheduleModifierLoc()
2016 : SC->getSecondScheduleModifierLoc(),
2017 diag::err_omp_schedule_nonmonotonic_ordered)
2018 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2019 ErrorFound = true;
2020 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002021 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2022 for (auto *C : LCs) {
2023 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2024 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2025 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002026 ErrorFound = true;
2027 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002028 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2029 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2030 OC->getNumForLoops()) {
2031 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2032 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2033 ErrorFound = true;
2034 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002035 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002036 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002037 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002038 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002039 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2040 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2041 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2042 // Mark all variables in private list clauses as used in inner region.
2043 // Required for proper codegen of combined directives.
2044 // TODO: add processing for other clauses.
2045 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2046 for (auto *C : PICs) {
2047 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2048 // Find the particular capture region for the clause if the
2049 // directive is a combined one with multiple capture regions.
2050 // If the directive is not a combined one, the capture region
2051 // associated with the clause is OMPD_unknown and is generated
2052 // only once.
2053 if (CaptureRegion == ThisCaptureRegion ||
2054 CaptureRegion == OMPD_unknown) {
2055 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2056 for (auto *D : DS->decls())
2057 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2058 }
2059 }
2060 }
2061 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002062 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002063 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002064 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002065}
2066
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002067static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2068 OpenMPDirectiveKind CancelRegion,
2069 SourceLocation StartLoc) {
2070 // CancelRegion is only needed for cancel and cancellation_point.
2071 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2072 return false;
2073
2074 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2075 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2076 return false;
2077
2078 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2079 << getOpenMPDirectiveName(CancelRegion);
2080 return true;
2081}
2082
2083static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002084 OpenMPDirectiveKind CurrentRegion,
2085 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002086 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002087 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002088 if (Stack->getCurScope()) {
2089 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002090 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002091 bool NestingProhibited = false;
2092 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002093 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002094 enum {
2095 NoRecommend,
2096 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002097 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002098 ShouldBeInTargetRegion,
2099 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002100 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002101 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002102 // OpenMP [2.16, Nesting of Regions]
2103 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002104 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002105 // An ordered construct with the simd clause is the only OpenMP
2106 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002107 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002108 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2109 // message.
2110 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2111 ? diag::err_omp_prohibited_region_simd
2112 : diag::warn_omp_nesting_simd);
2113 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002114 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002115 if (ParentRegion == OMPD_atomic) {
2116 // OpenMP [2.16, Nesting of Regions]
2117 // OpenMP constructs may not be nested inside an atomic region.
2118 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2119 return true;
2120 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002121 if (CurrentRegion == OMPD_section) {
2122 // OpenMP [2.7.2, sections Construct, Restrictions]
2123 // Orphaned section directives are prohibited. That is, the section
2124 // directives must appear within the sections construct and must not be
2125 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002126 if (ParentRegion != OMPD_sections &&
2127 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002128 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2129 << (ParentRegion != OMPD_unknown)
2130 << getOpenMPDirectiveName(ParentRegion);
2131 return true;
2132 }
2133 return false;
2134 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002135 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002136 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002137 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002138 if (ParentRegion == OMPD_unknown &&
2139 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002140 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002141 if (CurrentRegion == OMPD_cancellation_point ||
2142 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002143 // OpenMP [2.16, Nesting of Regions]
2144 // A cancellation point construct for which construct-type-clause is
2145 // taskgroup must be nested inside a task construct. A cancellation
2146 // point construct for which construct-type-clause is not taskgroup must
2147 // be closely nested inside an OpenMP construct that matches the type
2148 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002149 // A cancel construct for which construct-type-clause is taskgroup must be
2150 // nested inside a task construct. A cancel construct for which
2151 // construct-type-clause is not taskgroup must be closely nested inside an
2152 // OpenMP construct that matches the type specified in
2153 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002154 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002155 !((CancelRegion == OMPD_parallel &&
2156 (ParentRegion == OMPD_parallel ||
2157 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002158 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002159 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2160 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002161 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2162 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002163 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2164 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002165 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002166 // OpenMP [2.16, Nesting of Regions]
2167 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002168 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002169 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002170 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002171 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2172 // OpenMP [2.16, Nesting of Regions]
2173 // A critical region may not be nested (closely or otherwise) inside a
2174 // critical region with the same name. Note that this restriction is not
2175 // sufficient to prevent deadlock.
2176 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002177 bool DeadLock = Stack->hasDirective(
2178 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2179 const DeclarationNameInfo &DNI,
2180 SourceLocation Loc) -> bool {
2181 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2182 PreviousCriticalLoc = Loc;
2183 return true;
2184 } else
2185 return false;
2186 },
2187 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002188 if (DeadLock) {
2189 SemaRef.Diag(StartLoc,
2190 diag::err_omp_prohibited_region_critical_same_name)
2191 << CurrentName.getName();
2192 if (PreviousCriticalLoc.isValid())
2193 SemaRef.Diag(PreviousCriticalLoc,
2194 diag::note_omp_previous_critical_region);
2195 return true;
2196 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002197 } else if (CurrentRegion == OMPD_barrier) {
2198 // OpenMP [2.16, Nesting of Regions]
2199 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002200 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002201 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2202 isOpenMPTaskingDirective(ParentRegion) ||
2203 ParentRegion == OMPD_master ||
2204 ParentRegion == OMPD_critical ||
2205 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002206 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002207 !isOpenMPParallelDirective(CurrentRegion) &&
2208 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002209 // OpenMP [2.16, Nesting of Regions]
2210 // A worksharing region may not be closely nested inside a worksharing,
2211 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002212 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2213 isOpenMPTaskingDirective(ParentRegion) ||
2214 ParentRegion == OMPD_master ||
2215 ParentRegion == OMPD_critical ||
2216 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002217 Recommend = ShouldBeInParallelRegion;
2218 } else if (CurrentRegion == OMPD_ordered) {
2219 // OpenMP [2.16, Nesting of Regions]
2220 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002221 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002222 // An ordered region must be closely nested inside a loop region (or
2223 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002224 // OpenMP [2.8.1,simd Construct, Restrictions]
2225 // An ordered construct with the simd clause is the only OpenMP construct
2226 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002227 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002228 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002229 !(isOpenMPSimdDirective(ParentRegion) ||
2230 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002231 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002232 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002233 // OpenMP [2.16, Nesting of Regions]
2234 // If specified, a teams construct must be contained within a target
2235 // construct.
2236 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002237 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002238 Recommend = ShouldBeInTargetRegion;
2239 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2240 }
Kelvin Libf594a52016-12-17 05:48:59 +00002241 if (!NestingProhibited &&
2242 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2243 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2244 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002245 // OpenMP [2.16, Nesting of Regions]
2246 // distribute, parallel, parallel sections, parallel workshare, and the
2247 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2248 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002249 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2250 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002251 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002252 }
David Majnemer9d168222016-08-05 17:44:54 +00002253 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002254 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002255 // OpenMP 4.5 [2.17 Nesting of Regions]
2256 // The region associated with the distribute construct must be strictly
2257 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002258 NestingProhibited =
2259 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002260 Recommend = ShouldBeInTeamsRegion;
2261 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002262 if (!NestingProhibited &&
2263 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2264 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2265 // OpenMP 4.5 [2.17 Nesting of Regions]
2266 // If a target, target update, target data, target enter data, or
2267 // target exit data construct is encountered during execution of a
2268 // target region, the behavior is unspecified.
2269 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002270 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2271 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002272 if (isOpenMPTargetExecutionDirective(K)) {
2273 OffendingRegion = K;
2274 return true;
2275 } else
2276 return false;
2277 },
2278 false /* don't skip top directive */);
2279 CloseNesting = false;
2280 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002281 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002282 if (OrphanSeen) {
2283 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2284 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2285 } else {
2286 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2287 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2288 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2289 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002290 return true;
2291 }
2292 }
2293 return false;
2294}
2295
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002296static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2297 ArrayRef<OMPClause *> Clauses,
2298 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2299 bool ErrorFound = false;
2300 unsigned NamedModifiersNumber = 0;
2301 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2302 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002303 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002304 for (const auto *C : Clauses) {
2305 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2306 // At most one if clause without a directive-name-modifier can appear on
2307 // the directive.
2308 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2309 if (FoundNameModifiers[CurNM]) {
2310 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2311 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2312 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2313 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002314 } else if (CurNM != OMPD_unknown) {
2315 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002316 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002317 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002318 FoundNameModifiers[CurNM] = IC;
2319 if (CurNM == OMPD_unknown)
2320 continue;
2321 // Check if the specified name modifier is allowed for the current
2322 // directive.
2323 // At most one if clause with the particular directive-name-modifier can
2324 // appear on the directive.
2325 bool MatchFound = false;
2326 for (auto NM : AllowedNameModifiers) {
2327 if (CurNM == NM) {
2328 MatchFound = true;
2329 break;
2330 }
2331 }
2332 if (!MatchFound) {
2333 S.Diag(IC->getNameModifierLoc(),
2334 diag::err_omp_wrong_if_directive_name_modifier)
2335 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2336 ErrorFound = true;
2337 }
2338 }
2339 }
2340 // If any if clause on the directive includes a directive-name-modifier then
2341 // all if clauses on the directive must include a directive-name-modifier.
2342 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2343 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2344 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2345 diag::err_omp_no_more_if_clause);
2346 } else {
2347 std::string Values;
2348 std::string Sep(", ");
2349 unsigned AllowedCnt = 0;
2350 unsigned TotalAllowedNum =
2351 AllowedNameModifiers.size() - NamedModifiersNumber;
2352 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2353 ++Cnt) {
2354 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2355 if (!FoundNameModifiers[NM]) {
2356 Values += "'";
2357 Values += getOpenMPDirectiveName(NM);
2358 Values += "'";
2359 if (AllowedCnt + 2 == TotalAllowedNum)
2360 Values += " or ";
2361 else if (AllowedCnt + 1 != TotalAllowedNum)
2362 Values += Sep;
2363 ++AllowedCnt;
2364 }
2365 }
2366 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2367 diag::err_omp_unnamed_if_clause)
2368 << (TotalAllowedNum > 1) << Values;
2369 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002370 for (auto Loc : NameModifierLoc) {
2371 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2372 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002373 ErrorFound = true;
2374 }
2375 return ErrorFound;
2376}
2377
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002378StmtResult Sema::ActOnOpenMPExecutableDirective(
2379 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2380 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2381 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002382 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002383 // First check CancelRegion which is then used in checkNestingOfRegions.
2384 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2385 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002386 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002387 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002388
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002389 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002390 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002391 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002392 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002393 if (AStmt) {
2394 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2395
2396 // Check default data sharing attributes for referenced variables.
2397 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002398 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2399 Stmt *S = AStmt;
2400 while (--ThisCaptureLevel >= 0)
2401 S = cast<CapturedStmt>(S)->getCapturedStmt();
2402 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002403 if (DSAChecker.isErrorFound())
2404 return StmtError();
2405 // Generate list of implicitly defined firstprivate variables.
2406 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002407
2408 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2409 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2410 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2411 SourceLocation(), SourceLocation())) {
2412 ClausesWithImplicit.push_back(Implicit);
2413 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2414 DSAChecker.getImplicitFirstprivate().size();
2415 } else
2416 ErrorFound = true;
2417 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002418 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002419
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002420 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002421 switch (Kind) {
2422 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002423 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2424 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002425 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002426 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002427 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002428 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2429 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002430 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002431 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002432 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2433 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002434 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002435 case OMPD_for_simd:
2436 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2437 EndLoc, VarsWithInheritedDSA);
2438 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002439 case OMPD_sections:
2440 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2441 EndLoc);
2442 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002443 case OMPD_section:
2444 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002445 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002446 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2447 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002448 case OMPD_single:
2449 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2450 EndLoc);
2451 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002452 case OMPD_master:
2453 assert(ClausesWithImplicit.empty() &&
2454 "No clauses are allowed for 'omp master' directive");
2455 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2456 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002457 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002458 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2459 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002460 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002461 case OMPD_parallel_for:
2462 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2463 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002464 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002465 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002466 case OMPD_parallel_for_simd:
2467 Res = ActOnOpenMPParallelForSimdDirective(
2468 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002469 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002470 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002471 case OMPD_parallel_sections:
2472 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2473 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002474 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002475 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002476 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002477 Res =
2478 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002479 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002480 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002481 case OMPD_taskyield:
2482 assert(ClausesWithImplicit.empty() &&
2483 "No clauses are allowed for 'omp taskyield' directive");
2484 assert(AStmt == nullptr &&
2485 "No associated statement allowed for 'omp taskyield' directive");
2486 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2487 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002488 case OMPD_barrier:
2489 assert(ClausesWithImplicit.empty() &&
2490 "No clauses are allowed for 'omp barrier' directive");
2491 assert(AStmt == nullptr &&
2492 "No associated statement allowed for 'omp barrier' directive");
2493 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2494 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002495 case OMPD_taskwait:
2496 assert(ClausesWithImplicit.empty() &&
2497 "No clauses are allowed for 'omp taskwait' directive");
2498 assert(AStmt == nullptr &&
2499 "No associated statement allowed for 'omp taskwait' directive");
2500 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2501 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002502 case OMPD_taskgroup:
2503 assert(ClausesWithImplicit.empty() &&
2504 "No clauses are allowed for 'omp taskgroup' directive");
2505 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2506 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002507 case OMPD_flush:
2508 assert(AStmt == nullptr &&
2509 "No associated statement allowed for 'omp flush' directive");
2510 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2511 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002512 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002513 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2514 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002515 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002516 case OMPD_atomic:
2517 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2518 EndLoc);
2519 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002520 case OMPD_teams:
2521 Res =
2522 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2523 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002524 case OMPD_target:
2525 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2526 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002527 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002528 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002529 case OMPD_target_parallel:
2530 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2531 StartLoc, EndLoc);
2532 AllowedNameModifiers.push_back(OMPD_target);
2533 AllowedNameModifiers.push_back(OMPD_parallel);
2534 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002535 case OMPD_target_parallel_for:
2536 Res = ActOnOpenMPTargetParallelForDirective(
2537 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2538 AllowedNameModifiers.push_back(OMPD_target);
2539 AllowedNameModifiers.push_back(OMPD_parallel);
2540 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002541 case OMPD_cancellation_point:
2542 assert(ClausesWithImplicit.empty() &&
2543 "No clauses are allowed for 'omp cancellation point' directive");
2544 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2545 "cancellation point' directive");
2546 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2547 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002548 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002549 assert(AStmt == nullptr &&
2550 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002551 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2552 CancelRegion);
2553 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002554 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002555 case OMPD_target_data:
2556 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2557 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002558 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002559 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002560 case OMPD_target_enter_data:
2561 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2562 EndLoc);
2563 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2564 break;
Samuel Antao72590762016-01-19 20:04:50 +00002565 case OMPD_target_exit_data:
2566 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2567 EndLoc);
2568 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2569 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002570 case OMPD_taskloop:
2571 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2572 EndLoc, VarsWithInheritedDSA);
2573 AllowedNameModifiers.push_back(OMPD_taskloop);
2574 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002575 case OMPD_taskloop_simd:
2576 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2577 EndLoc, VarsWithInheritedDSA);
2578 AllowedNameModifiers.push_back(OMPD_taskloop);
2579 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002580 case OMPD_distribute:
2581 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2582 EndLoc, VarsWithInheritedDSA);
2583 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002584 case OMPD_target_update:
2585 assert(!AStmt && "Statement is not allowed for target update");
2586 Res =
2587 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2588 AllowedNameModifiers.push_back(OMPD_target_update);
2589 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002590 case OMPD_distribute_parallel_for:
2591 Res = ActOnOpenMPDistributeParallelForDirective(
2592 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2593 AllowedNameModifiers.push_back(OMPD_parallel);
2594 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002595 case OMPD_distribute_parallel_for_simd:
2596 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2597 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2598 AllowedNameModifiers.push_back(OMPD_parallel);
2599 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002600 case OMPD_distribute_simd:
2601 Res = ActOnOpenMPDistributeSimdDirective(
2602 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2603 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002604 case OMPD_target_parallel_for_simd:
2605 Res = ActOnOpenMPTargetParallelForSimdDirective(
2606 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2607 AllowedNameModifiers.push_back(OMPD_target);
2608 AllowedNameModifiers.push_back(OMPD_parallel);
2609 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002610 case OMPD_target_simd:
2611 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2612 EndLoc, VarsWithInheritedDSA);
2613 AllowedNameModifiers.push_back(OMPD_target);
2614 break;
Kelvin Li02532872016-08-05 14:37:37 +00002615 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002616 Res = ActOnOpenMPTeamsDistributeDirective(
2617 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002618 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002619 case OMPD_teams_distribute_simd:
2620 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2621 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2622 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002623 case OMPD_teams_distribute_parallel_for_simd:
2624 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2625 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2626 AllowedNameModifiers.push_back(OMPD_parallel);
2627 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002628 case OMPD_teams_distribute_parallel_for:
2629 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2630 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2631 AllowedNameModifiers.push_back(OMPD_parallel);
2632 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002633 case OMPD_target_teams:
2634 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2635 EndLoc);
2636 AllowedNameModifiers.push_back(OMPD_target);
2637 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002638 case OMPD_target_teams_distribute:
2639 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2640 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2641 AllowedNameModifiers.push_back(OMPD_target);
2642 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002643 case OMPD_target_teams_distribute_parallel_for:
2644 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2645 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2646 AllowedNameModifiers.push_back(OMPD_target);
2647 AllowedNameModifiers.push_back(OMPD_parallel);
2648 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002649 case OMPD_target_teams_distribute_parallel_for_simd:
2650 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2651 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2652 AllowedNameModifiers.push_back(OMPD_target);
2653 AllowedNameModifiers.push_back(OMPD_parallel);
2654 break;
Kelvin Lida681182017-01-10 18:08:18 +00002655 case OMPD_target_teams_distribute_simd:
2656 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2657 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2658 AllowedNameModifiers.push_back(OMPD_target);
2659 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002660 case OMPD_declare_target:
2661 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002662 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002663 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002664 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002665 llvm_unreachable("OpenMP Directive is not allowed");
2666 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002667 llvm_unreachable("Unknown OpenMP directive");
2668 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002669
Alexey Bataev4acb8592014-07-07 13:01:15 +00002670 for (auto P : VarsWithInheritedDSA) {
2671 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2672 << P.first << P.second->getSourceRange();
2673 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002674 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2675
2676 if (!AllowedNameModifiers.empty())
2677 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2678 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002679
Alexey Bataeved09d242014-05-28 05:53:51 +00002680 if (ErrorFound)
2681 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002682 return Res;
2683}
2684
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002685Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2686 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002687 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002688 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2689 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002690 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002691 assert(Linears.size() == LinModifiers.size());
2692 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002693 if (!DG || DG.get().isNull())
2694 return DeclGroupPtrTy();
2695
2696 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002697 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002698 return DG;
2699 }
2700 auto *ADecl = DG.get().getSingleDecl();
2701 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2702 ADecl = FTD->getTemplatedDecl();
2703
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002704 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2705 if (!FD) {
2706 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002707 return DeclGroupPtrTy();
2708 }
2709
Alexey Bataev2af33e32016-04-07 12:45:37 +00002710 // OpenMP [2.8.2, declare simd construct, Description]
2711 // The parameter of the simdlen clause must be a constant positive integer
2712 // expression.
2713 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002714 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002715 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002716 // OpenMP [2.8.2, declare simd construct, Description]
2717 // The special this pointer can be used as if was one of the arguments to the
2718 // function in any of the linear, aligned, or uniform clauses.
2719 // The uniform clause declares one or more arguments to have an invariant
2720 // value for all concurrent invocations of the function in the execution of a
2721 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002722 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2723 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002724 for (auto *E : Uniforms) {
2725 E = E->IgnoreParenImpCasts();
2726 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2727 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2728 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2729 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002730 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2731 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002732 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002733 }
2734 if (isa<CXXThisExpr>(E)) {
2735 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002736 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002737 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002738 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2739 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002740 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002741 // OpenMP [2.8.2, declare simd construct, Description]
2742 // The aligned clause declares that the object to which each list item points
2743 // is aligned to the number of bytes expressed in the optional parameter of
2744 // the aligned clause.
2745 // The special this pointer can be used as if was one of the arguments to the
2746 // function in any of the linear, aligned, or uniform clauses.
2747 // The type of list items appearing in the aligned clause must be array,
2748 // pointer, reference to array, or reference to pointer.
2749 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2750 Expr *AlignedThis = nullptr;
2751 for (auto *E : Aligneds) {
2752 E = E->IgnoreParenImpCasts();
2753 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2754 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2755 auto *CanonPVD = PVD->getCanonicalDecl();
2756 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2757 FD->getParamDecl(PVD->getFunctionScopeIndex())
2758 ->getCanonicalDecl() == CanonPVD) {
2759 // OpenMP [2.8.1, simd construct, Restrictions]
2760 // A list-item cannot appear in more than one aligned clause.
2761 if (AlignedArgs.count(CanonPVD) > 0) {
2762 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2763 << 1 << E->getSourceRange();
2764 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2765 diag::note_omp_explicit_dsa)
2766 << getOpenMPClauseName(OMPC_aligned);
2767 continue;
2768 }
2769 AlignedArgs[CanonPVD] = E;
2770 QualType QTy = PVD->getType()
2771 .getNonReferenceType()
2772 .getUnqualifiedType()
2773 .getCanonicalType();
2774 const Type *Ty = QTy.getTypePtrOrNull();
2775 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2776 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2777 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2778 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2779 }
2780 continue;
2781 }
2782 }
2783 if (isa<CXXThisExpr>(E)) {
2784 if (AlignedThis) {
2785 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2786 << 2 << E->getSourceRange();
2787 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2788 << getOpenMPClauseName(OMPC_aligned);
2789 }
2790 AlignedThis = E;
2791 continue;
2792 }
2793 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2794 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2795 }
2796 // The optional parameter of the aligned clause, alignment, must be a constant
2797 // positive integer expression. If no optional parameter is specified,
2798 // implementation-defined default alignments for SIMD instructions on the
2799 // target platforms are assumed.
2800 SmallVector<Expr *, 4> NewAligns;
2801 for (auto *E : Alignments) {
2802 ExprResult Align;
2803 if (E)
2804 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2805 NewAligns.push_back(Align.get());
2806 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002807 // OpenMP [2.8.2, declare simd construct, Description]
2808 // The linear clause declares one or more list items to be private to a SIMD
2809 // lane and to have a linear relationship with respect to the iteration space
2810 // of a loop.
2811 // The special this pointer can be used as if was one of the arguments to the
2812 // function in any of the linear, aligned, or uniform clauses.
2813 // When a linear-step expression is specified in a linear clause it must be
2814 // either a constant integer expression or an integer-typed parameter that is
2815 // specified in a uniform clause on the directive.
2816 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2817 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2818 auto MI = LinModifiers.begin();
2819 for (auto *E : Linears) {
2820 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2821 ++MI;
2822 E = E->IgnoreParenImpCasts();
2823 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2824 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2825 auto *CanonPVD = PVD->getCanonicalDecl();
2826 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2827 FD->getParamDecl(PVD->getFunctionScopeIndex())
2828 ->getCanonicalDecl() == CanonPVD) {
2829 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2830 // A list-item cannot appear in more than one linear clause.
2831 if (LinearArgs.count(CanonPVD) > 0) {
2832 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2833 << getOpenMPClauseName(OMPC_linear)
2834 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2835 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2836 diag::note_omp_explicit_dsa)
2837 << getOpenMPClauseName(OMPC_linear);
2838 continue;
2839 }
2840 // Each argument can appear in at most one uniform or linear clause.
2841 if (UniformedArgs.count(CanonPVD) > 0) {
2842 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2843 << getOpenMPClauseName(OMPC_linear)
2844 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2845 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2846 diag::note_omp_explicit_dsa)
2847 << getOpenMPClauseName(OMPC_uniform);
2848 continue;
2849 }
2850 LinearArgs[CanonPVD] = E;
2851 if (E->isValueDependent() || E->isTypeDependent() ||
2852 E->isInstantiationDependent() ||
2853 E->containsUnexpandedParameterPack())
2854 continue;
2855 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2856 PVD->getOriginalType());
2857 continue;
2858 }
2859 }
2860 if (isa<CXXThisExpr>(E)) {
2861 if (UniformedLinearThis) {
2862 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2863 << getOpenMPClauseName(OMPC_linear)
2864 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2865 << E->getSourceRange();
2866 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2867 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2868 : OMPC_linear);
2869 continue;
2870 }
2871 UniformedLinearThis = E;
2872 if (E->isValueDependent() || E->isTypeDependent() ||
2873 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2874 continue;
2875 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2876 E->getType());
2877 continue;
2878 }
2879 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2880 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2881 }
2882 Expr *Step = nullptr;
2883 Expr *NewStep = nullptr;
2884 SmallVector<Expr *, 4> NewSteps;
2885 for (auto *E : Steps) {
2886 // Skip the same step expression, it was checked already.
2887 if (Step == E || !E) {
2888 NewSteps.push_back(E ? NewStep : nullptr);
2889 continue;
2890 }
2891 Step = E;
2892 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2893 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2894 auto *CanonPVD = PVD->getCanonicalDecl();
2895 if (UniformedArgs.count(CanonPVD) == 0) {
2896 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2897 << Step->getSourceRange();
2898 } else if (E->isValueDependent() || E->isTypeDependent() ||
2899 E->isInstantiationDependent() ||
2900 E->containsUnexpandedParameterPack() ||
2901 CanonPVD->getType()->hasIntegerRepresentation())
2902 NewSteps.push_back(Step);
2903 else {
2904 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2905 << Step->getSourceRange();
2906 }
2907 continue;
2908 }
2909 NewStep = Step;
2910 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2911 !Step->isInstantiationDependent() &&
2912 !Step->containsUnexpandedParameterPack()) {
2913 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2914 .get();
2915 if (NewStep)
2916 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2917 }
2918 NewSteps.push_back(NewStep);
2919 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002920 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2921 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002922 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002923 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2924 const_cast<Expr **>(Linears.data()), Linears.size(),
2925 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2926 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002927 ADecl->addAttr(NewAttr);
2928 return ConvertDeclToDeclGroup(ADecl);
2929}
2930
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002931StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2932 Stmt *AStmt,
2933 SourceLocation StartLoc,
2934 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002935 if (!AStmt)
2936 return StmtError();
2937
Alexey Bataev9959db52014-05-06 10:08:46 +00002938 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2939 // 1.2.2 OpenMP Language Terminology
2940 // Structured block - An executable statement with a single entry at the
2941 // top and a single exit at the bottom.
2942 // The point of exit cannot be a branch out of the structured block.
2943 // longjmp() and throw() must not violate the entry/exit criteria.
2944 CS->getCapturedDecl()->setNothrow();
2945
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002946 getCurFunction()->setHasBranchProtectedScope();
2947
Alexey Bataev25e5b442015-09-15 12:52:43 +00002948 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2949 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002950}
2951
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002952namespace {
2953/// \brief Helper class for checking canonical form of the OpenMP loops and
2954/// extracting iteration space of each loop in the loop nest, that will be used
2955/// for IR generation.
2956class OpenMPIterationSpaceChecker {
2957 /// \brief Reference to Sema.
2958 Sema &SemaRef;
2959 /// \brief A location for diagnostics (when there is no some better location).
2960 SourceLocation DefaultLoc;
2961 /// \brief A location for diagnostics (when increment is not compatible).
2962 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002963 /// \brief A source location for referring to loop init later.
2964 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002965 /// \brief A source location for referring to condition later.
2966 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002967 /// \brief A source location for referring to increment later.
2968 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002969 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002970 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002971 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002972 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002973 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002974 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002975 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002976 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002977 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002978 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002979 /// \brief This flag is true when condition is one of:
2980 /// Var < UB
2981 /// Var <= UB
2982 /// UB > Var
2983 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002984 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002985 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002986 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002987 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002988 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002989
2990public:
2991 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002992 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002993 /// \brief Check init-expr for canonical loop form and save loop counter
2994 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002995 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002996 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2997 /// for less/greater and for strict/non-strict comparison.
2998 bool CheckCond(Expr *S);
2999 /// \brief Check incr-expr for canonical loop form and return true if it
3000 /// does not conform, otherwise save loop step (#Step).
3001 bool CheckInc(Expr *S);
3002 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003003 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003004 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003005 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003006 /// \brief Source range of the loop init.
3007 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3008 /// \brief Source range of the loop condition.
3009 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3010 /// \brief Source range of the loop increment.
3011 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3012 /// \brief True if the step should be subtracted.
3013 bool ShouldSubtractStep() const { return SubtractStep; }
3014 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003015 Expr *
3016 BuildNumIterations(Scope *S, const bool LimitedType,
3017 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003018 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003019 Expr *BuildPreCond(Scope *S, Expr *Cond,
3020 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003021 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003022 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3023 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003024 /// \brief Build reference expression to the private counter be used for
3025 /// codegen.
3026 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003027 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003028 Expr *BuildCounterInit() const;
3029 /// \brief Build step of the counter be used for codegen.
3030 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003031 /// \brief Return true if any expression is dependent.
3032 bool Dependent() const;
3033
3034private:
3035 /// \brief Check the right-hand side of an assignment in the increment
3036 /// expression.
3037 bool CheckIncRHS(Expr *RHS);
3038 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003039 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003040 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003041 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003042 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003043 /// \brief Helper to set loop increment.
3044 bool SetStep(Expr *NewStep, bool Subtract);
3045};
3046
3047bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003048 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003049 assert(!LB && !UB && !Step);
3050 return false;
3051 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003052 return LCDecl->getType()->isDependentType() ||
3053 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3054 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003055}
3056
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003057static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003058 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3059 E = ExprTemp->getSubExpr();
3060
3061 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3062 E = MTE->GetTemporaryExpr();
3063
3064 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3065 E = Binder->getSubExpr();
3066
3067 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3068 E = ICE->getSubExprAsWritten();
3069 return E->IgnoreParens();
3070}
3071
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003072bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3073 Expr *NewLCRefExpr,
3074 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003075 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003076 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003077 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003078 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003079 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003080 LCDecl = getCanonicalDecl(NewLCDecl);
3081 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003082 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3083 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003084 if ((Ctor->isCopyOrMoveConstructor() ||
3085 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3086 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003087 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003088 LB = NewLB;
3089 return false;
3090}
3091
3092bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003093 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003094 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003095 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3096 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003097 if (!NewUB)
3098 return true;
3099 UB = NewUB;
3100 TestIsLessOp = LessOp;
3101 TestIsStrictOp = StrictOp;
3102 ConditionSrcRange = SR;
3103 ConditionLoc = SL;
3104 return false;
3105}
3106
3107bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3108 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003109 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003110 if (!NewStep)
3111 return true;
3112 if (!NewStep->isValueDependent()) {
3113 // Check that the step is integer expression.
3114 SourceLocation StepLoc = NewStep->getLocStart();
3115 ExprResult Val =
3116 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3117 if (Val.isInvalid())
3118 return true;
3119 NewStep = Val.get();
3120
3121 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3122 // If test-expr is of form var relational-op b and relational-op is < or
3123 // <= then incr-expr must cause var to increase on each iteration of the
3124 // loop. If test-expr is of form var relational-op b and relational-op is
3125 // > or >= then incr-expr must cause var to decrease on each iteration of
3126 // the loop.
3127 // If test-expr is of form b relational-op var and relational-op is < or
3128 // <= then incr-expr must cause var to decrease on each iteration of the
3129 // loop. If test-expr is of form b relational-op var and relational-op is
3130 // > or >= then incr-expr must cause var to increase on each iteration of
3131 // the loop.
3132 llvm::APSInt Result;
3133 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3134 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3135 bool IsConstNeg =
3136 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003137 bool IsConstPos =
3138 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003139 bool IsConstZero = IsConstant && !Result.getBoolValue();
3140 if (UB && (IsConstZero ||
3141 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003142 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003143 SemaRef.Diag(NewStep->getExprLoc(),
3144 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003145 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003146 SemaRef.Diag(ConditionLoc,
3147 diag::note_omp_loop_cond_requres_compatible_incr)
3148 << TestIsLessOp << ConditionSrcRange;
3149 return true;
3150 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003151 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003152 NewStep =
3153 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3154 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003155 Subtract = !Subtract;
3156 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003157 }
3158
3159 Step = NewStep;
3160 SubtractStep = Subtract;
3161 return false;
3162}
3163
Alexey Bataev9c821032015-04-30 04:23:23 +00003164bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003165 // Check init-expr for canonical loop form and save loop counter
3166 // variable - #Var and its initialization value - #LB.
3167 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3168 // var = lb
3169 // integer-type var = lb
3170 // random-access-iterator-type var = lb
3171 // pointer-type var = lb
3172 //
3173 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003174 if (EmitDiags) {
3175 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3176 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003177 return true;
3178 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003179 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3180 if (!ExprTemp->cleanupsHaveSideEffects())
3181 S = ExprTemp->getSubExpr();
3182
Alexander Musmana5f070a2014-10-01 06:03:56 +00003183 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003184 if (Expr *E = dyn_cast<Expr>(S))
3185 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003186 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003187 if (BO->getOpcode() == BO_Assign) {
3188 auto *LHS = BO->getLHS()->IgnoreParens();
3189 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3190 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3191 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3192 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3193 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3194 }
3195 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3196 if (ME->isArrow() &&
3197 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3198 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3199 }
3200 }
David Majnemer9d168222016-08-05 17:44:54 +00003201 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003202 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003203 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003204 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003205 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003206 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003207 SemaRef.Diag(S->getLocStart(),
3208 diag::ext_omp_loop_not_canonical_init)
3209 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003210 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003211 }
3212 }
3213 }
David Majnemer9d168222016-08-05 17:44:54 +00003214 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003215 if (CE->getOperator() == OO_Equal) {
3216 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003217 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003218 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3219 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3220 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3221 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3222 }
3223 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3224 if (ME->isArrow() &&
3225 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3226 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3227 }
3228 }
3229 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003230
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003231 if (Dependent() || SemaRef.CurContext->isDependentContext())
3232 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003233 if (EmitDiags) {
3234 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3235 << S->getSourceRange();
3236 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003237 return true;
3238}
3239
Alexey Bataev23b69422014-06-18 07:08:49 +00003240/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003241/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003242static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003243 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003244 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003245 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003246 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3247 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003248 if ((Ctor->isCopyOrMoveConstructor() ||
3249 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3250 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003251 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003252 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3253 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3254 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3255 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3256 return getCanonicalDecl(ME->getMemberDecl());
3257 return getCanonicalDecl(VD);
3258 }
3259 }
3260 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3261 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3262 return getCanonicalDecl(ME->getMemberDecl());
3263 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003264}
3265
3266bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3267 // Check test-expr for canonical form, save upper-bound UB, flags for
3268 // less/greater and for strict/non-strict comparison.
3269 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3270 // var relational-op b
3271 // b relational-op var
3272 //
3273 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003274 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003275 return true;
3276 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003277 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003278 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003279 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003280 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003281 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003282 return SetUB(BO->getRHS(),
3283 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3284 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3285 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003286 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003287 return SetUB(BO->getLHS(),
3288 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3289 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3290 BO->getSourceRange(), BO->getOperatorLoc());
3291 }
David Majnemer9d168222016-08-05 17:44:54 +00003292 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003293 if (CE->getNumArgs() == 2) {
3294 auto Op = CE->getOperator();
3295 switch (Op) {
3296 case OO_Greater:
3297 case OO_GreaterEqual:
3298 case OO_Less:
3299 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003300 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003301 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3302 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3303 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003304 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003305 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3306 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3307 CE->getOperatorLoc());
3308 break;
3309 default:
3310 break;
3311 }
3312 }
3313 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003314 if (Dependent() || SemaRef.CurContext->isDependentContext())
3315 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003316 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003317 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003318 return true;
3319}
3320
3321bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3322 // RHS of canonical loop form increment can be:
3323 // var + incr
3324 // incr + var
3325 // var - incr
3326 //
3327 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003328 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003329 if (BO->isAdditiveOp()) {
3330 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003331 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003332 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003333 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003334 return SetStep(BO->getLHS(), false);
3335 }
David Majnemer9d168222016-08-05 17:44:54 +00003336 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003337 bool IsAdd = CE->getOperator() == OO_Plus;
3338 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003339 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003340 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003341 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003342 return SetStep(CE->getArg(0), false);
3343 }
3344 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003345 if (Dependent() || SemaRef.CurContext->isDependentContext())
3346 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003347 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003348 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003349 return true;
3350}
3351
3352bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3353 // Check incr-expr for canonical loop form and return true if it
3354 // does not conform.
3355 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3356 // ++var
3357 // var++
3358 // --var
3359 // var--
3360 // var += incr
3361 // var -= incr
3362 // var = var + incr
3363 // var = incr + var
3364 // var = var - incr
3365 //
3366 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003367 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003368 return true;
3369 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003370 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3371 if (!ExprTemp->cleanupsHaveSideEffects())
3372 S = ExprTemp->getSubExpr();
3373
Alexander Musmana5f070a2014-10-01 06:03:56 +00003374 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003375 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003376 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003377 if (UO->isIncrementDecrementOp() &&
3378 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003379 return SetStep(SemaRef
3380 .ActOnIntegerConstant(UO->getLocStart(),
3381 (UO->isDecrementOp() ? -1 : 1))
3382 .get(),
3383 false);
3384 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003385 switch (BO->getOpcode()) {
3386 case BO_AddAssign:
3387 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003388 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003389 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3390 break;
3391 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003392 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003393 return CheckIncRHS(BO->getRHS());
3394 break;
3395 default:
3396 break;
3397 }
David Majnemer9d168222016-08-05 17:44:54 +00003398 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003399 switch (CE->getOperator()) {
3400 case OO_PlusPlus:
3401 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003402 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003403 return SetStep(SemaRef
3404 .ActOnIntegerConstant(
3405 CE->getLocStart(),
3406 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3407 .get(),
3408 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003409 break;
3410 case OO_PlusEqual:
3411 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003412 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003413 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3414 break;
3415 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003416 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003417 return CheckIncRHS(CE->getArg(1));
3418 break;
3419 default:
3420 break;
3421 }
3422 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003423 if (Dependent() || SemaRef.CurContext->isDependentContext())
3424 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003425 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003426 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003427 return true;
3428}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003429
Alexey Bataev5a3af132016-03-29 08:58:54 +00003430static ExprResult
3431tryBuildCapture(Sema &SemaRef, Expr *Capture,
3432 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003433 if (SemaRef.CurContext->isDependentContext())
3434 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003435 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3436 return SemaRef.PerformImplicitConversion(
3437 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3438 /*AllowExplicit=*/true);
3439 auto I = Captures.find(Capture);
3440 if (I != Captures.end())
3441 return buildCapture(SemaRef, Capture, I->second);
3442 DeclRefExpr *Ref = nullptr;
3443 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3444 Captures[Capture] = Ref;
3445 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003446}
3447
Alexander Musmana5f070a2014-10-01 06:03:56 +00003448/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003449Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3450 Scope *S, const bool LimitedType,
3451 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003452 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003453 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003454 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003455 SemaRef.getLangOpts().CPlusPlus) {
3456 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003457 auto *UBExpr = TestIsLessOp ? UB : LB;
3458 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003459 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3460 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003461 if (!Upper || !Lower)
3462 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003463
3464 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3465
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003466 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003467 // BuildBinOp already emitted error, this one is to point user to upper
3468 // and lower bound, and to tell what is passed to 'operator-'.
3469 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3470 << Upper->getSourceRange() << Lower->getSourceRange();
3471 return nullptr;
3472 }
3473 }
3474
3475 if (!Diff.isUsable())
3476 return nullptr;
3477
3478 // Upper - Lower [- 1]
3479 if (TestIsStrictOp)
3480 Diff = SemaRef.BuildBinOp(
3481 S, DefaultLoc, BO_Sub, Diff.get(),
3482 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3483 if (!Diff.isUsable())
3484 return nullptr;
3485
3486 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003487 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3488 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003489 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003490 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003491 if (!Diff.isUsable())
3492 return nullptr;
3493
3494 // Parentheses (for dumping/debugging purposes only).
3495 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3496 if (!Diff.isUsable())
3497 return nullptr;
3498
3499 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003500 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003501 if (!Diff.isUsable())
3502 return nullptr;
3503
Alexander Musman174b3ca2014-10-06 11:16:29 +00003504 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003505 QualType Type = Diff.get()->getType();
3506 auto &C = SemaRef.Context;
3507 bool UseVarType = VarType->hasIntegerRepresentation() &&
3508 C.getTypeSize(Type) > C.getTypeSize(VarType);
3509 if (!Type->isIntegerType() || UseVarType) {
3510 unsigned NewSize =
3511 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3512 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3513 : Type->hasSignedIntegerRepresentation();
3514 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003515 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3516 Diff = SemaRef.PerformImplicitConversion(
3517 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3518 if (!Diff.isUsable())
3519 return nullptr;
3520 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003521 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003522 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003523 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3524 if (NewSize != C.getTypeSize(Type)) {
3525 if (NewSize < C.getTypeSize(Type)) {
3526 assert(NewSize == 64 && "incorrect loop var size");
3527 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3528 << InitSrcRange << ConditionSrcRange;
3529 }
3530 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003531 NewSize, Type->hasSignedIntegerRepresentation() ||
3532 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003533 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3534 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3535 Sema::AA_Converting, true);
3536 if (!Diff.isUsable())
3537 return nullptr;
3538 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003539 }
3540 }
3541
Alexander Musmana5f070a2014-10-01 06:03:56 +00003542 return Diff.get();
3543}
3544
Alexey Bataev5a3af132016-03-29 08:58:54 +00003545Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3546 Scope *S, Expr *Cond,
3547 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003548 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3549 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3550 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003551
Alexey Bataev5a3af132016-03-29 08:58:54 +00003552 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3553 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3554 if (!NewLB.isUsable() || !NewUB.isUsable())
3555 return nullptr;
3556
Alexey Bataev62dbb972015-04-22 11:59:37 +00003557 auto CondExpr = SemaRef.BuildBinOp(
3558 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3559 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003560 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003561 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003562 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3563 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003564 CondExpr = SemaRef.PerformImplicitConversion(
3565 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3566 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003567 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003568 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3569 // Otherwise use original loop conditon and evaluate it in runtime.
3570 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3571}
3572
Alexander Musmana5f070a2014-10-01 06:03:56 +00003573/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003574DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003575 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003576 auto *VD = dyn_cast<VarDecl>(LCDecl);
3577 if (!VD) {
3578 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3579 auto *Ref = buildDeclRefExpr(
3580 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003581 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3582 // If the loop control decl is explicitly marked as private, do not mark it
3583 // as captured again.
3584 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3585 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003586 return Ref;
3587 }
3588 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003589 DefaultLoc);
3590}
3591
3592Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003593 if (LCDecl && !LCDecl->isInvalidDecl()) {
3594 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003595 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003596 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3597 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003598 if (PrivateVar->isInvalidDecl())
3599 return nullptr;
3600 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3601 }
3602 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003603}
3604
Samuel Antao4c8035b2016-12-12 18:00:20 +00003605/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003606Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3607
3608/// \brief Build step of the counter be used for codegen.
3609Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3610
3611/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003612struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003613 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003614 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003615 /// \brief This expression calculates the number of iterations in the loop.
3616 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003617 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003618 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003619 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003620 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003621 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003622 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003623 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003624 /// \brief This is step for the #CounterVar used to generate its update:
3625 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003626 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003627 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003628 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003629 /// \brief Source range of the loop init.
3630 SourceRange InitSrcRange;
3631 /// \brief Source range of the loop condition.
3632 SourceRange CondSrcRange;
3633 /// \brief Source range of the loop increment.
3634 SourceRange IncSrcRange;
3635};
3636
Alexey Bataev23b69422014-06-18 07:08:49 +00003637} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003638
Alexey Bataev9c821032015-04-30 04:23:23 +00003639void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3640 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3641 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003642 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3643 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003644 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3645 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003646 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3647 if (auto *D = ISC.GetLoopDecl()) {
3648 auto *VD = dyn_cast<VarDecl>(D);
3649 if (!VD) {
3650 if (auto *Private = IsOpenMPCapturedDecl(D))
3651 VD = Private;
3652 else {
3653 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3654 /*WithInit=*/false);
3655 VD = cast<VarDecl>(Ref->getDecl());
3656 }
3657 }
3658 DSAStack->addLoopControlVariable(D, VD);
3659 }
3660 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003661 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003662 }
3663}
3664
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003665/// \brief Called on a for stmt to check and extract its iteration space
3666/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003667static bool CheckOpenMPIterationSpace(
3668 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3669 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003670 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003671 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003672 LoopIterationSpace &ResultIterSpace,
3673 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003674 // OpenMP [2.6, Canonical Loop Form]
3675 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003676 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003677 if (!For) {
3678 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003679 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3680 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3681 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3682 if (NestedLoopCount > 1) {
3683 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3684 SemaRef.Diag(DSA.getConstructLoc(),
3685 diag::note_omp_collapse_ordered_expr)
3686 << 2 << CollapseLoopCountExpr->getSourceRange()
3687 << OrderedLoopCountExpr->getSourceRange();
3688 else if (CollapseLoopCountExpr)
3689 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3690 diag::note_omp_collapse_ordered_expr)
3691 << 0 << CollapseLoopCountExpr->getSourceRange();
3692 else
3693 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3694 diag::note_omp_collapse_ordered_expr)
3695 << 1 << OrderedLoopCountExpr->getSourceRange();
3696 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003697 return true;
3698 }
3699 assert(For->getBody());
3700
3701 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3702
3703 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003704 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003705 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003707
3708 bool HasErrors = false;
3709
3710 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003711 if (auto *LCDecl = ISC.GetLoopDecl()) {
3712 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003713
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003714 // OpenMP [2.6, Canonical Loop Form]
3715 // Var is one of the following:
3716 // A variable of signed or unsigned integer type.
3717 // For C++, a variable of a random access iterator type.
3718 // For C, a variable of a pointer type.
3719 auto VarType = LCDecl->getType().getNonReferenceType();
3720 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3721 !VarType->isPointerType() &&
3722 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3723 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3724 << SemaRef.getLangOpts().CPlusPlus;
3725 HasErrors = true;
3726 }
3727
3728 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3729 // a Construct
3730 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3731 // parallel for construct is (are) private.
3732 // The loop iteration variable in the associated for-loop of a simd
3733 // construct with just one associated for-loop is linear with a
3734 // constant-linear-step that is the increment of the associated for-loop.
3735 // Exclude loop var from the list of variables with implicitly defined data
3736 // sharing attributes.
3737 VarsWithImplicitDSA.erase(LCDecl);
3738
3739 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3740 // in a Construct, C/C++].
3741 // The loop iteration variable in the associated for-loop of a simd
3742 // construct with just one associated for-loop may be listed in a linear
3743 // clause with a constant-linear-step that is the increment of the
3744 // associated for-loop.
3745 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3746 // parallel for construct may be listed in a private or lastprivate clause.
3747 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3748 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3749 // declared in the loop and it is predetermined as a private.
3750 auto PredeterminedCKind =
3751 isOpenMPSimdDirective(DKind)
3752 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3753 : OMPC_private;
3754 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3755 DVar.CKind != PredeterminedCKind) ||
3756 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3757 isOpenMPDistributeDirective(DKind)) &&
3758 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3759 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3760 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3761 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3762 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3763 << getOpenMPClauseName(PredeterminedCKind);
3764 if (DVar.RefExpr == nullptr)
3765 DVar.CKind = PredeterminedCKind;
3766 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3767 HasErrors = true;
3768 } else if (LoopDeclRefExpr != nullptr) {
3769 // Make the loop iteration variable private (for worksharing constructs),
3770 // linear (for simd directives with the only one associated loop) or
3771 // lastprivate (for simd directives with several collapsed or ordered
3772 // loops).
3773 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003774 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3775 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003776 /*FromParent=*/false);
3777 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3778 }
3779
3780 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3781
3782 // Check test-expr.
3783 HasErrors |= ISC.CheckCond(For->getCond());
3784
3785 // Check incr-expr.
3786 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003787 }
3788
Alexander Musmana5f070a2014-10-01 06:03:56 +00003789 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790 return HasErrors;
3791
Alexander Musmana5f070a2014-10-01 06:03:56 +00003792 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003793 ResultIterSpace.PreCond =
3794 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003795 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003796 DSA.getCurScope(),
3797 (isOpenMPWorksharingDirective(DKind) ||
3798 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3799 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003800 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003801 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003802 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3803 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3804 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3805 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3806 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3807 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3808
Alexey Bataev62dbb972015-04-22 11:59:37 +00003809 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3810 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003811 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003812 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003813 ResultIterSpace.CounterInit == nullptr ||
3814 ResultIterSpace.CounterStep == nullptr);
3815
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003816 return HasErrors;
3817}
3818
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003819/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003820static ExprResult
3821BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3822 ExprResult Start,
3823 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003824 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003825 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3826 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003827 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003828 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003829 VarRef.get()->getType())) {
3830 NewStart = SemaRef.PerformImplicitConversion(
3831 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3832 /*AllowExplicit=*/true);
3833 if (!NewStart.isUsable())
3834 return ExprError();
3835 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003836
3837 auto Init =
3838 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3839 return Init;
3840}
3841
Alexander Musmana5f070a2014-10-01 06:03:56 +00003842/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003843static ExprResult
3844BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3845 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3846 ExprResult Step, bool Subtract,
3847 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003848 // Add parentheses (for debugging purposes only).
3849 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3850 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3851 !Step.isUsable())
3852 return ExprError();
3853
Alexey Bataev5a3af132016-03-29 08:58:54 +00003854 ExprResult NewStep = Step;
3855 if (Captures)
3856 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003857 if (NewStep.isInvalid())
3858 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003859 ExprResult Update =
3860 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003861 if (!Update.isUsable())
3862 return ExprError();
3863
Alexey Bataevc0214e02016-02-16 12:13:49 +00003864 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3865 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003866 ExprResult NewStart = Start;
3867 if (Captures)
3868 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003869 if (NewStart.isInvalid())
3870 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003871
Alexey Bataevc0214e02016-02-16 12:13:49 +00003872 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3873 ExprResult SavedUpdate = Update;
3874 ExprResult UpdateVal;
3875 if (VarRef.get()->getType()->isOverloadableType() ||
3876 NewStart.get()->getType()->isOverloadableType() ||
3877 Update.get()->getType()->isOverloadableType()) {
3878 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3879 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3880 Update =
3881 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3882 if (Update.isUsable()) {
3883 UpdateVal =
3884 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3885 VarRef.get(), SavedUpdate.get());
3886 if (UpdateVal.isUsable()) {
3887 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3888 UpdateVal.get());
3889 }
3890 }
3891 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3892 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003893
Alexey Bataevc0214e02016-02-16 12:13:49 +00003894 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3895 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3896 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3897 NewStart.get(), SavedUpdate.get());
3898 if (!Update.isUsable())
3899 return ExprError();
3900
Alexey Bataev11481f52016-02-17 10:29:05 +00003901 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3902 VarRef.get()->getType())) {
3903 Update = SemaRef.PerformImplicitConversion(
3904 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3905 if (!Update.isUsable())
3906 return ExprError();
3907 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003908
3909 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3910 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003911 return Update;
3912}
3913
3914/// \brief Convert integer expression \a E to make it have at least \a Bits
3915/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003916static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003917 if (E == nullptr)
3918 return ExprError();
3919 auto &C = SemaRef.Context;
3920 QualType OldType = E->getType();
3921 unsigned HasBits = C.getTypeSize(OldType);
3922 if (HasBits >= Bits)
3923 return ExprResult(E);
3924 // OK to convert to signed, because new type has more bits than old.
3925 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3926 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3927 true);
3928}
3929
3930/// \brief Check if the given expression \a E is a constant integer that fits
3931/// into \a Bits bits.
3932static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3933 if (E == nullptr)
3934 return false;
3935 llvm::APSInt Result;
3936 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3937 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3938 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003939}
3940
Alexey Bataev5a3af132016-03-29 08:58:54 +00003941/// Build preinits statement for the given declarations.
3942static Stmt *buildPreInits(ASTContext &Context,
3943 SmallVectorImpl<Decl *> &PreInits) {
3944 if (!PreInits.empty()) {
3945 return new (Context) DeclStmt(
3946 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3947 SourceLocation(), SourceLocation());
3948 }
3949 return nullptr;
3950}
3951
3952/// Build preinits statement for the given declarations.
3953static Stmt *buildPreInits(ASTContext &Context,
3954 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3955 if (!Captures.empty()) {
3956 SmallVector<Decl *, 16> PreInits;
3957 for (auto &Pair : Captures)
3958 PreInits.push_back(Pair.second->getDecl());
3959 return buildPreInits(Context, PreInits);
3960 }
3961 return nullptr;
3962}
3963
3964/// Build postupdate expression for the given list of postupdates expressions.
3965static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3966 Expr *PostUpdate = nullptr;
3967 if (!PostUpdates.empty()) {
3968 for (auto *E : PostUpdates) {
3969 Expr *ConvE = S.BuildCStyleCastExpr(
3970 E->getExprLoc(),
3971 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3972 E->getExprLoc(), E)
3973 .get();
3974 PostUpdate = PostUpdate
3975 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3976 PostUpdate, ConvE)
3977 .get()
3978 : ConvE;
3979 }
3980 }
3981 return PostUpdate;
3982}
3983
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003984/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003985/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3986/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003987static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003988CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3989 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3990 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003991 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003992 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003993 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003994 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003995 // Found 'collapse' clause - calculate collapse number.
3996 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003997 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003998 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003999 }
4000 if (OrderedLoopCountExpr) {
4001 // Found 'ordered' clause - calculate collapse number.
4002 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004003 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4004 if (Result.getLimitedValue() < NestedLoopCount) {
4005 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4006 diag::err_omp_wrong_ordered_loop_count)
4007 << OrderedLoopCountExpr->getSourceRange();
4008 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4009 diag::note_collapse_loop_count)
4010 << CollapseLoopCountExpr->getSourceRange();
4011 }
4012 NestedLoopCount = Result.getLimitedValue();
4013 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004014 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004015 // This is helper routine for loop directives (e.g., 'for', 'simd',
4016 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004017 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004018 SmallVector<LoopIterationSpace, 4> IterSpaces;
4019 IterSpaces.resize(NestedLoopCount);
4020 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004021 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004022 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004023 NestedLoopCount, CollapseLoopCountExpr,
4024 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004025 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004026 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004027 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004028 // OpenMP [2.8.1, simd construct, Restrictions]
4029 // All loops associated with the construct must be perfectly nested; that
4030 // is, there must be no intervening code nor any OpenMP directive between
4031 // any two loops.
4032 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004033 }
4034
Alexander Musmana5f070a2014-10-01 06:03:56 +00004035 Built.clear(/* size */ NestedLoopCount);
4036
4037 if (SemaRef.CurContext->isDependentContext())
4038 return NestedLoopCount;
4039
4040 // An example of what is generated for the following code:
4041 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004042 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004043 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004044 // for (k = 0; k < NK; ++k)
4045 // for (j = J0; j < NJ; j+=2) {
4046 // <loop body>
4047 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004048 //
4049 // We generate the code below.
4050 // Note: the loop body may be outlined in CodeGen.
4051 // Note: some counters may be C++ classes, operator- is used to find number of
4052 // iterations and operator+= to calculate counter value.
4053 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4054 // or i64 is currently supported).
4055 //
4056 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4057 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4058 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4059 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4060 // // similar updates for vars in clauses (e.g. 'linear')
4061 // <loop body (using local i and j)>
4062 // }
4063 // i = NI; // assign final values of counters
4064 // j = NJ;
4065 //
4066
4067 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4068 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004069 // Precondition tests if there is at least one iteration (all conditions are
4070 // true).
4071 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004072 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004073 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004074 32 /* Bits */, SemaRef
4075 .PerformImplicitConversion(
4076 N0->IgnoreImpCasts(), N0->getType(),
4077 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004078 .get(),
4079 SemaRef);
4080 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004081 64 /* Bits */, SemaRef
4082 .PerformImplicitConversion(
4083 N0->IgnoreImpCasts(), N0->getType(),
4084 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004085 .get(),
4086 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004087
4088 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4089 return NestedLoopCount;
4090
4091 auto &C = SemaRef.Context;
4092 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4093
4094 Scope *CurScope = DSA.getCurScope();
4095 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004096 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004097 PreCond =
4098 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4099 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004100 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004101 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004102 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004103 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4104 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004105 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004106 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004107 SemaRef
4108 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4109 Sema::AA_Converting,
4110 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004111 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004112 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004113 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004114 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004115 SemaRef
4116 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4117 Sema::AA_Converting,
4118 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004119 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004120 }
4121
4122 // Choose either the 32-bit or 64-bit version.
4123 ExprResult LastIteration = LastIteration64;
4124 if (LastIteration32.isUsable() &&
4125 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4126 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4127 FitsInto(
4128 32 /* Bits */,
4129 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4130 LastIteration64.get(), SemaRef)))
4131 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004132 QualType VType = LastIteration.get()->getType();
4133 QualType RealVType = VType;
4134 QualType StrideVType = VType;
4135 if (isOpenMPTaskLoopDirective(DKind)) {
4136 VType =
4137 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4138 StrideVType =
4139 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4140 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004141
4142 if (!LastIteration.isUsable())
4143 return 0;
4144
4145 // Save the number of iterations.
4146 ExprResult NumIterations = LastIteration;
4147 {
4148 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004149 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4150 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004151 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4152 if (!LastIteration.isUsable())
4153 return 0;
4154 }
4155
4156 // Calculate the last iteration number beforehand instead of doing this on
4157 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4158 llvm::APSInt Result;
4159 bool IsConstant =
4160 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4161 ExprResult CalcLastIteration;
4162 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004163 ExprResult SaveRef =
4164 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004165 LastIteration = SaveRef;
4166
4167 // Prepare SaveRef + 1.
4168 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004169 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004170 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4171 if (!NumIterations.isUsable())
4172 return 0;
4173 }
4174
4175 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4176
David Majnemer9d168222016-08-05 17:44:54 +00004177 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004178 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004179 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4180 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004181 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004182 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4183 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004184 SemaRef.AddInitializerToDecl(LBDecl,
4185 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4186 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004187
4188 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004189 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4190 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004191 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004192 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004193
4194 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4195 // This will be used to implement clause 'lastprivate'.
4196 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004197 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4198 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004199 SemaRef.AddInitializerToDecl(ILDecl,
4200 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4201 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004202
4203 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004204 VarDecl *STDecl =
4205 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4206 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004207 SemaRef.AddInitializerToDecl(STDecl,
4208 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4209 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004210
4211 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004212 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004213 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4214 UB.get(), LastIteration.get());
4215 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4216 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4217 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4218 CondOp.get());
4219 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004220
4221 // If we have a combined directive that combines 'distribute', 'for' or
4222 // 'simd' we need to be able to access the bounds of the schedule of the
4223 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4224 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4225 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004226
Carlo Bertolliffafe102017-04-20 00:39:39 +00004227 // Lower bound variable, initialized with zero.
4228 VarDecl *CombLBDecl =
4229 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4230 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4231 SemaRef.AddInitializerToDecl(
4232 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4233 /*DirectInit*/ false);
4234
4235 // Upper bound variable, initialized with last iteration number.
4236 VarDecl *CombUBDecl =
4237 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4238 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4239 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4240 /*DirectInit*/ false);
4241
4242 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4243 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4244 ExprResult CombCondOp =
4245 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4246 LastIteration.get(), CombUB.get());
4247 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4248 CombCondOp.get());
4249 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4250
4251 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004252 // We expect to have at least 2 more parameters than the 'parallel'
4253 // directive does - the lower and upper bounds of the previous schedule.
4254 assert(CD->getNumParams() >= 4 &&
4255 "Unexpected number of parameters in loop combined directive");
4256
4257 // Set the proper type for the bounds given what we learned from the
4258 // enclosed loops.
4259 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4260 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4261
4262 // Previous lower and upper bounds are obtained from the region
4263 // parameters.
4264 PrevLB =
4265 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4266 PrevUB =
4267 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4268 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004269 }
4270
4271 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004272 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004273 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004274 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004275 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4276 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004277 Expr *RHS =
4278 (isOpenMPWorksharingDirective(DKind) ||
4279 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4280 ? LB.get()
4281 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004282 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4283 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004284
4285 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4286 Expr *CombRHS =
4287 (isOpenMPWorksharingDirective(DKind) ||
4288 isOpenMPTaskLoopDirective(DKind) ||
4289 isOpenMPDistributeDirective(DKind))
4290 ? CombLB.get()
4291 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4292 CombInit =
4293 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4294 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4295 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004296 }
4297
Alexander Musmanc6388682014-12-15 07:07:06 +00004298 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004299 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004300 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004301 (isOpenMPWorksharingDirective(DKind) ||
4302 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004303 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4304 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4305 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004306 ExprResult CombCond;
4307 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4308 CombCond =
4309 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4310 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004311 // Loop increment (IV = IV + 1)
4312 SourceLocation IncLoc;
4313 ExprResult Inc =
4314 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4315 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4316 if (!Inc.isUsable())
4317 return 0;
4318 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004319 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4320 if (!Inc.isUsable())
4321 return 0;
4322
4323 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4324 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004325 // In combined construct, add combined version that use CombLB and CombUB
4326 // base variables for the update
4327 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004328 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4329 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004330 // LB + ST
4331 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4332 if (!NextLB.isUsable())
4333 return 0;
4334 // LB = LB + ST
4335 NextLB =
4336 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4337 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4338 if (!NextLB.isUsable())
4339 return 0;
4340 // UB + ST
4341 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4342 if (!NextUB.isUsable())
4343 return 0;
4344 // UB = UB + ST
4345 NextUB =
4346 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4347 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4348 if (!NextUB.isUsable())
4349 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004350 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4351 CombNextLB =
4352 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4353 if (!NextLB.isUsable())
4354 return 0;
4355 // LB = LB + ST
4356 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4357 CombNextLB.get());
4358 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4359 if (!CombNextLB.isUsable())
4360 return 0;
4361 // UB + ST
4362 CombNextUB =
4363 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4364 if (!CombNextUB.isUsable())
4365 return 0;
4366 // UB = UB + ST
4367 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4368 CombNextUB.get());
4369 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4370 if (!CombNextUB.isUsable())
4371 return 0;
4372 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004373 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004374
Carlo Bertolliffafe102017-04-20 00:39:39 +00004375 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004376 // directive with for as IV = IV + ST; ensure upper bound expression based
4377 // on PrevUB instead of NumIterations - used to implement 'for' when found
4378 // in combination with 'distribute', like in 'distribute parallel for'
4379 SourceLocation DistIncLoc;
4380 ExprResult DistCond, DistInc, PrevEUB;
4381 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4382 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4383 assert(DistCond.isUsable() && "distribute cond expr was not built");
4384
4385 DistInc =
4386 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4387 assert(DistInc.isUsable() && "distribute inc expr was not built");
4388 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4389 DistInc.get());
4390 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4391 assert(DistInc.isUsable() && "distribute inc expr was not built");
4392
4393 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4394 // construct
4395 SourceLocation DistEUBLoc;
4396 ExprResult IsUBGreater =
4397 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4398 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4399 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4400 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4401 CondOp.get());
4402 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4403 }
4404
Alexander Musmana5f070a2014-10-01 06:03:56 +00004405 // Build updates and final values of the loop counters.
4406 bool HasErrors = false;
4407 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004408 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004409 Built.Updates.resize(NestedLoopCount);
4410 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004411 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004412 {
4413 ExprResult Div;
4414 // Go from inner nested loop to outer.
4415 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4416 LoopIterationSpace &IS = IterSpaces[Cnt];
4417 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4418 // Build: Iter = (IV / Div) % IS.NumIters
4419 // where Div is product of previous iterations' IS.NumIters.
4420 ExprResult Iter;
4421 if (Div.isUsable()) {
4422 Iter =
4423 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4424 } else {
4425 Iter = IV;
4426 assert((Cnt == (int)NestedLoopCount - 1) &&
4427 "unusable div expected on first iteration only");
4428 }
4429
4430 if (Cnt != 0 && Iter.isUsable())
4431 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4432 IS.NumIterations);
4433 if (!Iter.isUsable()) {
4434 HasErrors = true;
4435 break;
4436 }
4437
Alexey Bataev39f915b82015-05-08 10:41:21 +00004438 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004439 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4440 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4441 IS.CounterVar->getExprLoc(),
4442 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004443 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004444 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004445 if (!Init.isUsable()) {
4446 HasErrors = true;
4447 break;
4448 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004449 ExprResult Update = BuildCounterUpdate(
4450 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4451 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004452 if (!Update.isUsable()) {
4453 HasErrors = true;
4454 break;
4455 }
4456
4457 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4458 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004459 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004460 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004461 if (!Final.isUsable()) {
4462 HasErrors = true;
4463 break;
4464 }
4465
4466 // Build Div for the next iteration: Div <- Div * IS.NumIters
4467 if (Cnt != 0) {
4468 if (Div.isUnset())
4469 Div = IS.NumIterations;
4470 else
4471 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4472 IS.NumIterations);
4473
4474 // Add parentheses (for debugging purposes only).
4475 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004476 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004477 if (!Div.isUsable()) {
4478 HasErrors = true;
4479 break;
4480 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004481 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004482 }
4483 if (!Update.isUsable() || !Final.isUsable()) {
4484 HasErrors = true;
4485 break;
4486 }
4487 // Save results
4488 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004489 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004490 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004491 Built.Updates[Cnt] = Update.get();
4492 Built.Finals[Cnt] = Final.get();
4493 }
4494 }
4495
4496 if (HasErrors)
4497 return 0;
4498
4499 // Save results
4500 Built.IterationVarRef = IV.get();
4501 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004502 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004503 Built.CalcLastIteration =
4504 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004505 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004506 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004507 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004508 Built.Init = Init.get();
4509 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004510 Built.LB = LB.get();
4511 Built.UB = UB.get();
4512 Built.IL = IL.get();
4513 Built.ST = ST.get();
4514 Built.EUB = EUB.get();
4515 Built.NLB = NextLB.get();
4516 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004517 Built.PrevLB = PrevLB.get();
4518 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004519 Built.DistInc = DistInc.get();
4520 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004521 Built.DistCombinedFields.LB = CombLB.get();
4522 Built.DistCombinedFields.UB = CombUB.get();
4523 Built.DistCombinedFields.EUB = CombEUB.get();
4524 Built.DistCombinedFields.Init = CombInit.get();
4525 Built.DistCombinedFields.Cond = CombCond.get();
4526 Built.DistCombinedFields.NLB = CombNextLB.get();
4527 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004528
Alexey Bataev8b427062016-05-25 12:36:08 +00004529 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4530 // Fill data for doacross depend clauses.
4531 for (auto Pair : DSA.getDoacrossDependClauses()) {
4532 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4533 Pair.first->setCounterValue(CounterVal);
4534 else {
4535 if (NestedLoopCount != Pair.second.size() ||
4536 NestedLoopCount != LoopMultipliers.size() + 1) {
4537 // Erroneous case - clause has some problems.
4538 Pair.first->setCounterValue(CounterVal);
4539 continue;
4540 }
4541 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4542 auto I = Pair.second.rbegin();
4543 auto IS = IterSpaces.rbegin();
4544 auto ILM = LoopMultipliers.rbegin();
4545 Expr *UpCounterVal = CounterVal;
4546 Expr *Multiplier = nullptr;
4547 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4548 if (I->first) {
4549 assert(IS->CounterStep);
4550 Expr *NormalizedOffset =
4551 SemaRef
4552 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4553 I->first, IS->CounterStep)
4554 .get();
4555 if (Multiplier) {
4556 NormalizedOffset =
4557 SemaRef
4558 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4559 NormalizedOffset, Multiplier)
4560 .get();
4561 }
4562 assert(I->second == OO_Plus || I->second == OO_Minus);
4563 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004564 UpCounterVal = SemaRef
4565 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4566 UpCounterVal, NormalizedOffset)
4567 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004568 }
4569 Multiplier = *ILM;
4570 ++I;
4571 ++IS;
4572 ++ILM;
4573 }
4574 Pair.first->setCounterValue(UpCounterVal);
4575 }
4576 }
4577
Alexey Bataevabfc0692014-06-25 06:52:00 +00004578 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004579}
4580
Alexey Bataev10e775f2015-07-30 11:36:16 +00004581static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004582 auto CollapseClauses =
4583 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4584 if (CollapseClauses.begin() != CollapseClauses.end())
4585 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004586 return nullptr;
4587}
4588
Alexey Bataev10e775f2015-07-30 11:36:16 +00004589static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004590 auto OrderedClauses =
4591 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4592 if (OrderedClauses.begin() != OrderedClauses.end())
4593 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004594 return nullptr;
4595}
4596
Kelvin Lic5609492016-07-15 04:39:07 +00004597static bool checkSimdlenSafelenSpecified(Sema &S,
4598 const ArrayRef<OMPClause *> Clauses) {
4599 OMPSafelenClause *Safelen = nullptr;
4600 OMPSimdlenClause *Simdlen = nullptr;
4601
4602 for (auto *Clause : Clauses) {
4603 if (Clause->getClauseKind() == OMPC_safelen)
4604 Safelen = cast<OMPSafelenClause>(Clause);
4605 else if (Clause->getClauseKind() == OMPC_simdlen)
4606 Simdlen = cast<OMPSimdlenClause>(Clause);
4607 if (Safelen && Simdlen)
4608 break;
4609 }
4610
4611 if (Simdlen && Safelen) {
4612 llvm::APSInt SimdlenRes, SafelenRes;
4613 auto SimdlenLength = Simdlen->getSimdlen();
4614 auto SafelenLength = Safelen->getSafelen();
4615 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4616 SimdlenLength->isInstantiationDependent() ||
4617 SimdlenLength->containsUnexpandedParameterPack())
4618 return false;
4619 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4620 SafelenLength->isInstantiationDependent() ||
4621 SafelenLength->containsUnexpandedParameterPack())
4622 return false;
4623 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4624 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4625 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4626 // If both simdlen and safelen clauses are specified, the value of the
4627 // simdlen parameter must be less than or equal to the value of the safelen
4628 // parameter.
4629 if (SimdlenRes > SafelenRes) {
4630 S.Diag(SimdlenLength->getExprLoc(),
4631 diag::err_omp_wrong_simdlen_safelen_values)
4632 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4633 return true;
4634 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004635 }
4636 return false;
4637}
4638
Alexey Bataev4acb8592014-07-07 13:01:15 +00004639StmtResult Sema::ActOnOpenMPSimdDirective(
4640 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4641 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004642 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004643 if (!AStmt)
4644 return StmtError();
4645
4646 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004647 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004648 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4649 // define the nested loops number.
4650 unsigned NestedLoopCount = CheckOpenMPLoop(
4651 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4652 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004653 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004654 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004655
Alexander Musmana5f070a2014-10-01 06:03:56 +00004656 assert((CurContext->isDependentContext() || B.builtAll()) &&
4657 "omp simd loop exprs were not built");
4658
Alexander Musman3276a272015-03-21 10:12:56 +00004659 if (!CurContext->isDependentContext()) {
4660 // Finalize the clauses that need pre-built expressions for CodeGen.
4661 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004662 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004663 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004664 B.NumIterations, *this, CurScope,
4665 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004666 return StmtError();
4667 }
4668 }
4669
Kelvin Lic5609492016-07-15 04:39:07 +00004670 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004671 return StmtError();
4672
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004673 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004674 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4675 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004676}
4677
Alexey Bataev4acb8592014-07-07 13:01:15 +00004678StmtResult Sema::ActOnOpenMPForDirective(
4679 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4680 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004681 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004682 if (!AStmt)
4683 return StmtError();
4684
4685 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004686 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004687 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4688 // define the nested loops number.
4689 unsigned NestedLoopCount = CheckOpenMPLoop(
4690 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4691 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004692 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004693 return StmtError();
4694
Alexander Musmana5f070a2014-10-01 06:03:56 +00004695 assert((CurContext->isDependentContext() || B.builtAll()) &&
4696 "omp for loop exprs were not built");
4697
Alexey Bataev54acd402015-08-04 11:18:19 +00004698 if (!CurContext->isDependentContext()) {
4699 // Finalize the clauses that need pre-built expressions for CodeGen.
4700 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004701 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004702 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004703 B.NumIterations, *this, CurScope,
4704 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004705 return StmtError();
4706 }
4707 }
4708
Alexey Bataevf29276e2014-06-18 04:14:57 +00004709 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004710 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004711 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004712}
4713
Alexander Musmanf82886e2014-09-18 05:12:34 +00004714StmtResult Sema::ActOnOpenMPForSimdDirective(
4715 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4716 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004717 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004718 if (!AStmt)
4719 return StmtError();
4720
4721 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004722 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004723 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4724 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004725 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004726 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4727 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4728 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004729 if (NestedLoopCount == 0)
4730 return StmtError();
4731
Alexander Musmanc6388682014-12-15 07:07:06 +00004732 assert((CurContext->isDependentContext() || B.builtAll()) &&
4733 "omp for simd loop exprs were not built");
4734
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004735 if (!CurContext->isDependentContext()) {
4736 // Finalize the clauses that need pre-built expressions for CodeGen.
4737 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004738 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004739 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004740 B.NumIterations, *this, CurScope,
4741 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004742 return StmtError();
4743 }
4744 }
4745
Kelvin Lic5609492016-07-15 04:39:07 +00004746 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004747 return StmtError();
4748
Alexander Musmanf82886e2014-09-18 05:12:34 +00004749 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004750 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4751 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004752}
4753
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004754StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4755 Stmt *AStmt,
4756 SourceLocation StartLoc,
4757 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004758 if (!AStmt)
4759 return StmtError();
4760
4761 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004762 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004763 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004764 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004765 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004766 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004767 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004768 return StmtError();
4769 // All associated statements must be '#pragma omp section' except for
4770 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004771 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004772 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4773 if (SectionStmt)
4774 Diag(SectionStmt->getLocStart(),
4775 diag::err_omp_sections_substmt_not_section);
4776 return StmtError();
4777 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004778 cast<OMPSectionDirective>(SectionStmt)
4779 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004780 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004781 } else {
4782 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4783 return StmtError();
4784 }
4785
4786 getCurFunction()->setHasBranchProtectedScope();
4787
Alexey Bataev25e5b442015-09-15 12:52:43 +00004788 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4789 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004790}
4791
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004792StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4793 SourceLocation StartLoc,
4794 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004795 if (!AStmt)
4796 return StmtError();
4797
4798 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004799
4800 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004801 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004802
Alexey Bataev25e5b442015-09-15 12:52:43 +00004803 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4804 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004805}
4806
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004807StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4808 Stmt *AStmt,
4809 SourceLocation StartLoc,
4810 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004811 if (!AStmt)
4812 return StmtError();
4813
4814 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004815
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004816 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004817
Alexey Bataev3255bf32015-01-19 05:20:46 +00004818 // OpenMP [2.7.3, single Construct, Restrictions]
4819 // The copyprivate clause must not be used with the nowait clause.
4820 OMPClause *Nowait = nullptr;
4821 OMPClause *Copyprivate = nullptr;
4822 for (auto *Clause : Clauses) {
4823 if (Clause->getClauseKind() == OMPC_nowait)
4824 Nowait = Clause;
4825 else if (Clause->getClauseKind() == OMPC_copyprivate)
4826 Copyprivate = Clause;
4827 if (Copyprivate && Nowait) {
4828 Diag(Copyprivate->getLocStart(),
4829 diag::err_omp_single_copyprivate_with_nowait);
4830 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4831 return StmtError();
4832 }
4833 }
4834
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004835 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4836}
4837
Alexander Musman80c22892014-07-17 08:54:58 +00004838StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4839 SourceLocation StartLoc,
4840 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004841 if (!AStmt)
4842 return StmtError();
4843
4844 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004845
4846 getCurFunction()->setHasBranchProtectedScope();
4847
4848 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4849}
4850
Alexey Bataev28c75412015-12-15 08:19:24 +00004851StmtResult Sema::ActOnOpenMPCriticalDirective(
4852 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4853 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004854 if (!AStmt)
4855 return StmtError();
4856
4857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004858
Alexey Bataev28c75412015-12-15 08:19:24 +00004859 bool ErrorFound = false;
4860 llvm::APSInt Hint;
4861 SourceLocation HintLoc;
4862 bool DependentHint = false;
4863 for (auto *C : Clauses) {
4864 if (C->getClauseKind() == OMPC_hint) {
4865 if (!DirName.getName()) {
4866 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4867 ErrorFound = true;
4868 }
4869 Expr *E = cast<OMPHintClause>(C)->getHint();
4870 if (E->isTypeDependent() || E->isValueDependent() ||
4871 E->isInstantiationDependent())
4872 DependentHint = true;
4873 else {
4874 Hint = E->EvaluateKnownConstInt(Context);
4875 HintLoc = C->getLocStart();
4876 }
4877 }
4878 }
4879 if (ErrorFound)
4880 return StmtError();
4881 auto Pair = DSAStack->getCriticalWithHint(DirName);
4882 if (Pair.first && DirName.getName() && !DependentHint) {
4883 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4884 Diag(StartLoc, diag::err_omp_critical_with_hint);
4885 if (HintLoc.isValid()) {
4886 Diag(HintLoc, diag::note_omp_critical_hint_here)
4887 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4888 } else
4889 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4890 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4891 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4892 << 1
4893 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4894 /*Radix=*/10, /*Signed=*/false);
4895 } else
4896 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4897 }
4898 }
4899
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004900 getCurFunction()->setHasBranchProtectedScope();
4901
Alexey Bataev28c75412015-12-15 08:19:24 +00004902 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4903 Clauses, AStmt);
4904 if (!Pair.first && DirName.getName() && !DependentHint)
4905 DSAStack->addCriticalWithHint(Dir, Hint);
4906 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004907}
4908
Alexey Bataev4acb8592014-07-07 13:01:15 +00004909StmtResult Sema::ActOnOpenMPParallelForDirective(
4910 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4911 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004912 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004913 if (!AStmt)
4914 return StmtError();
4915
Alexey Bataev4acb8592014-07-07 13:01:15 +00004916 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4917 // 1.2.2 OpenMP Language Terminology
4918 // Structured block - An executable statement with a single entry at the
4919 // top and a single exit at the bottom.
4920 // The point of exit cannot be a branch out of the structured block.
4921 // longjmp() and throw() must not violate the entry/exit criteria.
4922 CS->getCapturedDecl()->setNothrow();
4923
Alexander Musmanc6388682014-12-15 07:07:06 +00004924 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004925 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4926 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004927 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004928 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4929 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4930 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004931 if (NestedLoopCount == 0)
4932 return StmtError();
4933
Alexander Musmana5f070a2014-10-01 06:03:56 +00004934 assert((CurContext->isDependentContext() || B.builtAll()) &&
4935 "omp parallel for loop exprs were not built");
4936
Alexey Bataev54acd402015-08-04 11:18:19 +00004937 if (!CurContext->isDependentContext()) {
4938 // Finalize the clauses that need pre-built expressions for CodeGen.
4939 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004940 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004941 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004942 B.NumIterations, *this, CurScope,
4943 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004944 return StmtError();
4945 }
4946 }
4947
Alexey Bataev4acb8592014-07-07 13:01:15 +00004948 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004949 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004950 NestedLoopCount, Clauses, AStmt, B,
4951 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004952}
4953
Alexander Musmane4e893b2014-09-23 09:33:00 +00004954StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4955 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4956 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004957 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004958 if (!AStmt)
4959 return StmtError();
4960
Alexander Musmane4e893b2014-09-23 09:33:00 +00004961 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4962 // 1.2.2 OpenMP Language Terminology
4963 // Structured block - An executable statement with a single entry at the
4964 // top and a single exit at the bottom.
4965 // The point of exit cannot be a branch out of the structured block.
4966 // longjmp() and throw() must not violate the entry/exit criteria.
4967 CS->getCapturedDecl()->setNothrow();
4968
Alexander Musmanc6388682014-12-15 07:07:06 +00004969 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004970 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4971 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004972 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004973 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4974 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4975 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004976 if (NestedLoopCount == 0)
4977 return StmtError();
4978
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004979 if (!CurContext->isDependentContext()) {
4980 // Finalize the clauses that need pre-built expressions for CodeGen.
4981 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004982 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004983 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004984 B.NumIterations, *this, CurScope,
4985 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004986 return StmtError();
4987 }
4988 }
4989
Kelvin Lic5609492016-07-15 04:39:07 +00004990 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004991 return StmtError();
4992
Alexander Musmane4e893b2014-09-23 09:33:00 +00004993 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004994 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004995 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004996}
4997
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004998StmtResult
4999Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5000 Stmt *AStmt, SourceLocation StartLoc,
5001 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005002 if (!AStmt)
5003 return StmtError();
5004
5005 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005006 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005007 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005008 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005009 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005010 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005011 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005012 return StmtError();
5013 // All associated statements must be '#pragma omp section' except for
5014 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005015 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005016 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5017 if (SectionStmt)
5018 Diag(SectionStmt->getLocStart(),
5019 diag::err_omp_parallel_sections_substmt_not_section);
5020 return StmtError();
5021 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005022 cast<OMPSectionDirective>(SectionStmt)
5023 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005024 }
5025 } else {
5026 Diag(AStmt->getLocStart(),
5027 diag::err_omp_parallel_sections_not_compound_stmt);
5028 return StmtError();
5029 }
5030
5031 getCurFunction()->setHasBranchProtectedScope();
5032
Alexey Bataev25e5b442015-09-15 12:52:43 +00005033 return OMPParallelSectionsDirective::Create(
5034 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005035}
5036
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005037StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5038 Stmt *AStmt, SourceLocation StartLoc,
5039 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005040 if (!AStmt)
5041 return StmtError();
5042
David Majnemer9d168222016-08-05 17:44:54 +00005043 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005044 // 1.2.2 OpenMP Language Terminology
5045 // Structured block - An executable statement with a single entry at the
5046 // top and a single exit at the bottom.
5047 // The point of exit cannot be a branch out of the structured block.
5048 // longjmp() and throw() must not violate the entry/exit criteria.
5049 CS->getCapturedDecl()->setNothrow();
5050
5051 getCurFunction()->setHasBranchProtectedScope();
5052
Alexey Bataev25e5b442015-09-15 12:52:43 +00005053 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5054 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005055}
5056
Alexey Bataev68446b72014-07-18 07:47:19 +00005057StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5058 SourceLocation EndLoc) {
5059 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5060}
5061
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005062StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5063 SourceLocation EndLoc) {
5064 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5065}
5066
Alexey Bataev2df347a2014-07-18 10:17:07 +00005067StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5068 SourceLocation EndLoc) {
5069 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5070}
5071
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005072StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5073 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
5082 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5083}
5084
Alexey Bataev6125da92014-07-21 11:26:11 +00005085StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5086 SourceLocation StartLoc,
5087 SourceLocation EndLoc) {
5088 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5089 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5090}
5091
Alexey Bataev346265e2015-09-25 10:37:12 +00005092StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5093 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005094 SourceLocation StartLoc,
5095 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005096 OMPClause *DependFound = nullptr;
5097 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005098 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005099 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005100 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005101 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005102 for (auto *C : Clauses) {
5103 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5104 DependFound = C;
5105 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5106 if (DependSourceClause) {
5107 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5108 << getOpenMPDirectiveName(OMPD_ordered)
5109 << getOpenMPClauseName(OMPC_depend) << 2;
5110 ErrorFound = true;
5111 } else
5112 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005113 if (DependSinkClause) {
5114 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5115 << 0;
5116 ErrorFound = true;
5117 }
5118 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5119 if (DependSourceClause) {
5120 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5121 << 1;
5122 ErrorFound = true;
5123 }
5124 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005125 }
5126 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005127 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005128 else if (C->getClauseKind() == OMPC_simd)
5129 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005130 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005131 if (!ErrorFound && !SC &&
5132 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005133 // OpenMP [2.8.1,simd Construct, Restrictions]
5134 // An ordered construct with the simd clause is the only OpenMP construct
5135 // that can appear in the simd region.
5136 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005137 ErrorFound = true;
5138 } else if (DependFound && (TC || SC)) {
5139 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5140 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5141 ErrorFound = true;
5142 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5143 Diag(DependFound->getLocStart(),
5144 diag::err_omp_ordered_directive_without_param);
5145 ErrorFound = true;
5146 } else if (TC || Clauses.empty()) {
5147 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5148 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5149 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5150 << (TC != nullptr);
5151 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5152 ErrorFound = true;
5153 }
5154 }
5155 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005156 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005157
5158 if (AStmt) {
5159 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5160
5161 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005162 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005163
5164 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005165}
5166
Alexey Bataev1d160b12015-03-13 12:27:31 +00005167namespace {
5168/// \brief Helper class for checking expression in 'omp atomic [update]'
5169/// construct.
5170class OpenMPAtomicUpdateChecker {
5171 /// \brief Error results for atomic update expressions.
5172 enum ExprAnalysisErrorCode {
5173 /// \brief A statement is not an expression statement.
5174 NotAnExpression,
5175 /// \brief Expression is not builtin binary or unary operation.
5176 NotABinaryOrUnaryExpression,
5177 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5178 NotAnUnaryIncDecExpression,
5179 /// \brief An expression is not of scalar type.
5180 NotAScalarType,
5181 /// \brief A binary operation is not an assignment operation.
5182 NotAnAssignmentOp,
5183 /// \brief RHS part of the binary operation is not a binary expression.
5184 NotABinaryExpression,
5185 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5186 /// expression.
5187 NotABinaryOperator,
5188 /// \brief RHS binary operation does not have reference to the updated LHS
5189 /// part.
5190 NotAnUpdateExpression,
5191 /// \brief No errors is found.
5192 NoError
5193 };
5194 /// \brief Reference to Sema.
5195 Sema &SemaRef;
5196 /// \brief A location for note diagnostics (when error is found).
5197 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005198 /// \brief 'x' lvalue part of the source atomic expression.
5199 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005200 /// \brief 'expr' rvalue part of the source atomic expression.
5201 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005202 /// \brief Helper expression of the form
5203 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5204 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5205 Expr *UpdateExpr;
5206 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5207 /// important for non-associative operations.
5208 bool IsXLHSInRHSPart;
5209 BinaryOperatorKind Op;
5210 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005211 /// \brief true if the source expression is a postfix unary operation, false
5212 /// if it is a prefix unary operation.
5213 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005214
5215public:
5216 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005217 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005218 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005219 /// \brief Check specified statement that it is suitable for 'atomic update'
5220 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005221 /// expression. If DiagId and NoteId == 0, then only check is performed
5222 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005223 /// \param DiagId Diagnostic which should be emitted if error is found.
5224 /// \param NoteId Diagnostic note for the main error message.
5225 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005226 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005227 /// \brief Return the 'x' lvalue part of the source atomic expression.
5228 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005229 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5230 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005231 /// \brief Return the update expression used in calculation of the updated
5232 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5233 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5234 Expr *getUpdateExpr() const { return UpdateExpr; }
5235 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5236 /// false otherwise.
5237 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5238
Alexey Bataevb78ca832015-04-01 03:33:17 +00005239 /// \brief true if the source expression is a postfix unary operation, false
5240 /// if it is a prefix unary operation.
5241 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5242
Alexey Bataev1d160b12015-03-13 12:27:31 +00005243private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005244 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5245 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005246};
5247} // namespace
5248
5249bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5250 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5251 ExprAnalysisErrorCode ErrorFound = NoError;
5252 SourceLocation ErrorLoc, NoteLoc;
5253 SourceRange ErrorRange, NoteRange;
5254 // Allowed constructs are:
5255 // x = x binop expr;
5256 // x = expr binop x;
5257 if (AtomicBinOp->getOpcode() == BO_Assign) {
5258 X = AtomicBinOp->getLHS();
5259 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5260 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5261 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5262 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5263 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005264 Op = AtomicInnerBinOp->getOpcode();
5265 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005266 auto *LHS = AtomicInnerBinOp->getLHS();
5267 auto *RHS = AtomicInnerBinOp->getRHS();
5268 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5269 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5270 /*Canonical=*/true);
5271 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5272 /*Canonical=*/true);
5273 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5274 /*Canonical=*/true);
5275 if (XId == LHSId) {
5276 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005277 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005278 } else if (XId == RHSId) {
5279 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005280 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005281 } else {
5282 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5283 ErrorRange = AtomicInnerBinOp->getSourceRange();
5284 NoteLoc = X->getExprLoc();
5285 NoteRange = X->getSourceRange();
5286 ErrorFound = NotAnUpdateExpression;
5287 }
5288 } else {
5289 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5290 ErrorRange = AtomicInnerBinOp->getSourceRange();
5291 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5292 NoteRange = SourceRange(NoteLoc, NoteLoc);
5293 ErrorFound = NotABinaryOperator;
5294 }
5295 } else {
5296 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5297 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5298 ErrorFound = NotABinaryExpression;
5299 }
5300 } else {
5301 ErrorLoc = AtomicBinOp->getExprLoc();
5302 ErrorRange = AtomicBinOp->getSourceRange();
5303 NoteLoc = AtomicBinOp->getOperatorLoc();
5304 NoteRange = SourceRange(NoteLoc, NoteLoc);
5305 ErrorFound = NotAnAssignmentOp;
5306 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005307 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005308 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5309 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5310 return true;
5311 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005312 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005313 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005314}
5315
5316bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5317 unsigned NoteId) {
5318 ExprAnalysisErrorCode ErrorFound = NoError;
5319 SourceLocation ErrorLoc, NoteLoc;
5320 SourceRange ErrorRange, NoteRange;
5321 // Allowed constructs are:
5322 // x++;
5323 // x--;
5324 // ++x;
5325 // --x;
5326 // x binop= expr;
5327 // x = x binop expr;
5328 // x = expr binop x;
5329 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5330 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5331 if (AtomicBody->getType()->isScalarType() ||
5332 AtomicBody->isInstantiationDependent()) {
5333 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5334 AtomicBody->IgnoreParenImpCasts())) {
5335 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005336 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005337 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005338 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005339 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005340 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005341 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005342 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5343 AtomicBody->IgnoreParenImpCasts())) {
5344 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005345 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005346 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005347 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5348 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005349 // Check for Unary Operation
5350 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005351 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005352 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5353 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005354 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005355 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5356 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005357 } else {
5358 ErrorFound = NotAnUnaryIncDecExpression;
5359 ErrorLoc = AtomicUnaryOp->getExprLoc();
5360 ErrorRange = AtomicUnaryOp->getSourceRange();
5361 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5362 NoteRange = SourceRange(NoteLoc, NoteLoc);
5363 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005364 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005365 ErrorFound = NotABinaryOrUnaryExpression;
5366 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5367 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5368 }
5369 } else {
5370 ErrorFound = NotAScalarType;
5371 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5372 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5373 }
5374 } else {
5375 ErrorFound = NotAnExpression;
5376 NoteLoc = ErrorLoc = S->getLocStart();
5377 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5378 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005379 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005380 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5381 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5382 return true;
5383 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005384 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005385 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005386 // Build an update expression of form 'OpaqueValueExpr(x) binop
5387 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5388 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5389 auto *OVEX = new (SemaRef.getASTContext())
5390 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5391 auto *OVEExpr = new (SemaRef.getASTContext())
5392 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5393 auto Update =
5394 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5395 IsXLHSInRHSPart ? OVEExpr : OVEX);
5396 if (Update.isInvalid())
5397 return true;
5398 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5399 Sema::AA_Casting);
5400 if (Update.isInvalid())
5401 return true;
5402 UpdateExpr = Update.get();
5403 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005404 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005405}
5406
Alexey Bataev0162e452014-07-22 10:10:35 +00005407StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5408 Stmt *AStmt,
5409 SourceLocation StartLoc,
5410 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005411 if (!AStmt)
5412 return StmtError();
5413
David Majnemer9d168222016-08-05 17:44:54 +00005414 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005415 // 1.2.2 OpenMP Language Terminology
5416 // Structured block - An executable statement with a single entry at the
5417 // top and a single exit at the bottom.
5418 // The point of exit cannot be a branch out of the structured block.
5419 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005420 OpenMPClauseKind AtomicKind = OMPC_unknown;
5421 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005422 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005423 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005424 C->getClauseKind() == OMPC_update ||
5425 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005426 if (AtomicKind != OMPC_unknown) {
5427 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5428 << SourceRange(C->getLocStart(), C->getLocEnd());
5429 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5430 << getOpenMPClauseName(AtomicKind);
5431 } else {
5432 AtomicKind = C->getClauseKind();
5433 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005434 }
5435 }
5436 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005437
Alexey Bataev459dec02014-07-24 06:46:57 +00005438 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005439 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5440 Body = EWC->getSubExpr();
5441
Alexey Bataev62cec442014-11-18 10:14:22 +00005442 Expr *X = nullptr;
5443 Expr *V = nullptr;
5444 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005445 Expr *UE = nullptr;
5446 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005447 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005448 // OpenMP [2.12.6, atomic Construct]
5449 // In the next expressions:
5450 // * x and v (as applicable) are both l-value expressions with scalar type.
5451 // * During the execution of an atomic region, multiple syntactic
5452 // occurrences of x must designate the same storage location.
5453 // * Neither of v and expr (as applicable) may access the storage location
5454 // designated by x.
5455 // * Neither of x and expr (as applicable) may access the storage location
5456 // designated by v.
5457 // * expr is an expression with scalar type.
5458 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5459 // * binop, binop=, ++, and -- are not overloaded operators.
5460 // * The expression x binop expr must be numerically equivalent to x binop
5461 // (expr). This requirement is satisfied if the operators in expr have
5462 // precedence greater than binop, or by using parentheses around expr or
5463 // subexpressions of expr.
5464 // * The expression expr binop x must be numerically equivalent to (expr)
5465 // binop x. This requirement is satisfied if the operators in expr have
5466 // precedence equal to or greater than binop, or by using parentheses around
5467 // expr or subexpressions of expr.
5468 // * For forms that allow multiple occurrences of x, the number of times
5469 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005470 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005471 enum {
5472 NotAnExpression,
5473 NotAnAssignmentOp,
5474 NotAScalarType,
5475 NotAnLValue,
5476 NoError
5477 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005478 SourceLocation ErrorLoc, NoteLoc;
5479 SourceRange ErrorRange, NoteRange;
5480 // If clause is read:
5481 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005482 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5483 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005484 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5485 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5486 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5487 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5488 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5489 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5490 if (!X->isLValue() || !V->isLValue()) {
5491 auto NotLValueExpr = X->isLValue() ? V : X;
5492 ErrorFound = NotAnLValue;
5493 ErrorLoc = AtomicBinOp->getExprLoc();
5494 ErrorRange = AtomicBinOp->getSourceRange();
5495 NoteLoc = NotLValueExpr->getExprLoc();
5496 NoteRange = NotLValueExpr->getSourceRange();
5497 }
5498 } else if (!X->isInstantiationDependent() ||
5499 !V->isInstantiationDependent()) {
5500 auto NotScalarExpr =
5501 (X->isInstantiationDependent() || X->getType()->isScalarType())
5502 ? V
5503 : X;
5504 ErrorFound = NotAScalarType;
5505 ErrorLoc = AtomicBinOp->getExprLoc();
5506 ErrorRange = AtomicBinOp->getSourceRange();
5507 NoteLoc = NotScalarExpr->getExprLoc();
5508 NoteRange = NotScalarExpr->getSourceRange();
5509 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005510 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005511 ErrorFound = NotAnAssignmentOp;
5512 ErrorLoc = AtomicBody->getExprLoc();
5513 ErrorRange = AtomicBody->getSourceRange();
5514 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5515 : AtomicBody->getExprLoc();
5516 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5517 : AtomicBody->getSourceRange();
5518 }
5519 } else {
5520 ErrorFound = NotAnExpression;
5521 NoteLoc = ErrorLoc = Body->getLocStart();
5522 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005523 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005524 if (ErrorFound != NoError) {
5525 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5526 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005527 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5528 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005529 return StmtError();
5530 } else if (CurContext->isDependentContext())
5531 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005532 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005533 enum {
5534 NotAnExpression,
5535 NotAnAssignmentOp,
5536 NotAScalarType,
5537 NotAnLValue,
5538 NoError
5539 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005540 SourceLocation ErrorLoc, NoteLoc;
5541 SourceRange ErrorRange, NoteRange;
5542 // If clause is write:
5543 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005544 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5545 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005546 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5547 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005548 X = AtomicBinOp->getLHS();
5549 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005550 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5551 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5552 if (!X->isLValue()) {
5553 ErrorFound = NotAnLValue;
5554 ErrorLoc = AtomicBinOp->getExprLoc();
5555 ErrorRange = AtomicBinOp->getSourceRange();
5556 NoteLoc = X->getExprLoc();
5557 NoteRange = X->getSourceRange();
5558 }
5559 } else if (!X->isInstantiationDependent() ||
5560 !E->isInstantiationDependent()) {
5561 auto NotScalarExpr =
5562 (X->isInstantiationDependent() || X->getType()->isScalarType())
5563 ? E
5564 : X;
5565 ErrorFound = NotAScalarType;
5566 ErrorLoc = AtomicBinOp->getExprLoc();
5567 ErrorRange = AtomicBinOp->getSourceRange();
5568 NoteLoc = NotScalarExpr->getExprLoc();
5569 NoteRange = NotScalarExpr->getSourceRange();
5570 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005571 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005572 ErrorFound = NotAnAssignmentOp;
5573 ErrorLoc = AtomicBody->getExprLoc();
5574 ErrorRange = AtomicBody->getSourceRange();
5575 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5576 : AtomicBody->getExprLoc();
5577 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5578 : AtomicBody->getSourceRange();
5579 }
5580 } else {
5581 ErrorFound = NotAnExpression;
5582 NoteLoc = ErrorLoc = Body->getLocStart();
5583 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005584 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005585 if (ErrorFound != NoError) {
5586 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5587 << ErrorRange;
5588 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5589 << NoteRange;
5590 return StmtError();
5591 } else if (CurContext->isDependentContext())
5592 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005593 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005594 // If clause is update:
5595 // x++;
5596 // x--;
5597 // ++x;
5598 // --x;
5599 // x binop= expr;
5600 // x = x binop expr;
5601 // x = expr binop x;
5602 OpenMPAtomicUpdateChecker Checker(*this);
5603 if (Checker.checkStatement(
5604 Body, (AtomicKind == OMPC_update)
5605 ? diag::err_omp_atomic_update_not_expression_statement
5606 : diag::err_omp_atomic_not_expression_statement,
5607 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005608 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005609 if (!CurContext->isDependentContext()) {
5610 E = Checker.getExpr();
5611 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005612 UE = Checker.getUpdateExpr();
5613 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005614 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005615 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005616 enum {
5617 NotAnAssignmentOp,
5618 NotACompoundStatement,
5619 NotTwoSubstatements,
5620 NotASpecificExpression,
5621 NoError
5622 } ErrorFound = NoError;
5623 SourceLocation ErrorLoc, NoteLoc;
5624 SourceRange ErrorRange, NoteRange;
5625 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5626 // If clause is a capture:
5627 // v = x++;
5628 // v = x--;
5629 // v = ++x;
5630 // v = --x;
5631 // v = x binop= expr;
5632 // v = x = x binop expr;
5633 // v = x = expr binop x;
5634 auto *AtomicBinOp =
5635 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5636 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5637 V = AtomicBinOp->getLHS();
5638 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5639 OpenMPAtomicUpdateChecker Checker(*this);
5640 if (Checker.checkStatement(
5641 Body, diag::err_omp_atomic_capture_not_expression_statement,
5642 diag::note_omp_atomic_update))
5643 return StmtError();
5644 E = Checker.getExpr();
5645 X = Checker.getX();
5646 UE = Checker.getUpdateExpr();
5647 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5648 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005649 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005650 ErrorLoc = AtomicBody->getExprLoc();
5651 ErrorRange = AtomicBody->getSourceRange();
5652 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5653 : AtomicBody->getExprLoc();
5654 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5655 : AtomicBody->getSourceRange();
5656 ErrorFound = NotAnAssignmentOp;
5657 }
5658 if (ErrorFound != NoError) {
5659 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5660 << ErrorRange;
5661 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5662 return StmtError();
5663 } else if (CurContext->isDependentContext()) {
5664 UE = V = E = X = nullptr;
5665 }
5666 } else {
5667 // If clause is a capture:
5668 // { v = x; x = expr; }
5669 // { v = x; x++; }
5670 // { v = x; x--; }
5671 // { v = x; ++x; }
5672 // { v = x; --x; }
5673 // { v = x; x binop= expr; }
5674 // { v = x; x = x binop expr; }
5675 // { v = x; x = expr binop x; }
5676 // { x++; v = x; }
5677 // { x--; v = x; }
5678 // { ++x; v = x; }
5679 // { --x; v = x; }
5680 // { x binop= expr; v = x; }
5681 // { x = x binop expr; v = x; }
5682 // { x = expr binop x; v = x; }
5683 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5684 // Check that this is { expr1; expr2; }
5685 if (CS->size() == 2) {
5686 auto *First = CS->body_front();
5687 auto *Second = CS->body_back();
5688 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5689 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5690 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5691 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5692 // Need to find what subexpression is 'v' and what is 'x'.
5693 OpenMPAtomicUpdateChecker Checker(*this);
5694 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5695 BinaryOperator *BinOp = nullptr;
5696 if (IsUpdateExprFound) {
5697 BinOp = dyn_cast<BinaryOperator>(First);
5698 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5699 }
5700 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5701 // { v = x; x++; }
5702 // { v = x; x--; }
5703 // { v = x; ++x; }
5704 // { v = x; --x; }
5705 // { v = x; x binop= expr; }
5706 // { v = x; x = x binop expr; }
5707 // { v = x; x = expr binop x; }
5708 // Check that the first expression has form v = x.
5709 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5710 llvm::FoldingSetNodeID XId, PossibleXId;
5711 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5712 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5713 IsUpdateExprFound = XId == PossibleXId;
5714 if (IsUpdateExprFound) {
5715 V = BinOp->getLHS();
5716 X = Checker.getX();
5717 E = Checker.getExpr();
5718 UE = Checker.getUpdateExpr();
5719 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005720 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005721 }
5722 }
5723 if (!IsUpdateExprFound) {
5724 IsUpdateExprFound = !Checker.checkStatement(First);
5725 BinOp = nullptr;
5726 if (IsUpdateExprFound) {
5727 BinOp = dyn_cast<BinaryOperator>(Second);
5728 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5729 }
5730 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5731 // { x++; v = x; }
5732 // { x--; v = x; }
5733 // { ++x; v = x; }
5734 // { --x; v = x; }
5735 // { x binop= expr; v = x; }
5736 // { x = x binop expr; v = x; }
5737 // { x = expr binop x; v = x; }
5738 // Check that the second expression has form v = x.
5739 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5740 llvm::FoldingSetNodeID XId, PossibleXId;
5741 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5742 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5743 IsUpdateExprFound = XId == PossibleXId;
5744 if (IsUpdateExprFound) {
5745 V = BinOp->getLHS();
5746 X = Checker.getX();
5747 E = Checker.getExpr();
5748 UE = Checker.getUpdateExpr();
5749 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005750 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005751 }
5752 }
5753 }
5754 if (!IsUpdateExprFound) {
5755 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005756 auto *FirstExpr = dyn_cast<Expr>(First);
5757 auto *SecondExpr = dyn_cast<Expr>(Second);
5758 if (!FirstExpr || !SecondExpr ||
5759 !(FirstExpr->isInstantiationDependent() ||
5760 SecondExpr->isInstantiationDependent())) {
5761 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5762 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005763 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005764 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5765 : First->getLocStart();
5766 NoteRange = ErrorRange = FirstBinOp
5767 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005768 : SourceRange(ErrorLoc, ErrorLoc);
5769 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005770 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5771 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5772 ErrorFound = NotAnAssignmentOp;
5773 NoteLoc = ErrorLoc = SecondBinOp
5774 ? SecondBinOp->getOperatorLoc()
5775 : Second->getLocStart();
5776 NoteRange = ErrorRange =
5777 SecondBinOp ? SecondBinOp->getSourceRange()
5778 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005779 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005780 auto *PossibleXRHSInFirst =
5781 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5782 auto *PossibleXLHSInSecond =
5783 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5784 llvm::FoldingSetNodeID X1Id, X2Id;
5785 PossibleXRHSInFirst->Profile(X1Id, Context,
5786 /*Canonical=*/true);
5787 PossibleXLHSInSecond->Profile(X2Id, Context,
5788 /*Canonical=*/true);
5789 IsUpdateExprFound = X1Id == X2Id;
5790 if (IsUpdateExprFound) {
5791 V = FirstBinOp->getLHS();
5792 X = SecondBinOp->getLHS();
5793 E = SecondBinOp->getRHS();
5794 UE = nullptr;
5795 IsXLHSInRHSPart = false;
5796 IsPostfixUpdate = true;
5797 } else {
5798 ErrorFound = NotASpecificExpression;
5799 ErrorLoc = FirstBinOp->getExprLoc();
5800 ErrorRange = FirstBinOp->getSourceRange();
5801 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5802 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5803 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005804 }
5805 }
5806 }
5807 }
5808 } else {
5809 NoteLoc = ErrorLoc = Body->getLocStart();
5810 NoteRange = ErrorRange =
5811 SourceRange(Body->getLocStart(), Body->getLocStart());
5812 ErrorFound = NotTwoSubstatements;
5813 }
5814 } else {
5815 NoteLoc = ErrorLoc = Body->getLocStart();
5816 NoteRange = ErrorRange =
5817 SourceRange(Body->getLocStart(), Body->getLocStart());
5818 ErrorFound = NotACompoundStatement;
5819 }
5820 if (ErrorFound != NoError) {
5821 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5822 << ErrorRange;
5823 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5824 return StmtError();
5825 } else if (CurContext->isDependentContext()) {
5826 UE = V = E = X = nullptr;
5827 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005828 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005829 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005830
5831 getCurFunction()->setHasBranchProtectedScope();
5832
Alexey Bataev62cec442014-11-18 10:14:22 +00005833 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005834 X, V, E, UE, IsXLHSInRHSPart,
5835 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005836}
5837
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005838StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5839 Stmt *AStmt,
5840 SourceLocation StartLoc,
5841 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005842 if (!AStmt)
5843 return StmtError();
5844
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005845 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5846 // 1.2.2 OpenMP Language Terminology
5847 // Structured block - An executable statement with a single entry at the
5848 // top and a single exit at the bottom.
5849 // The point of exit cannot be a branch out of the structured block.
5850 // longjmp() and throw() must not violate the entry/exit criteria.
5851 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005852
Alexey Bataev13314bf2014-10-09 04:18:56 +00005853 // OpenMP [2.16, Nesting of Regions]
5854 // If specified, a teams construct must be contained within a target
5855 // construct. That target construct must contain no statements or directives
5856 // outside of the teams construct.
5857 if (DSAStack->hasInnerTeamsRegion()) {
5858 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5859 bool OMPTeamsFound = true;
5860 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5861 auto I = CS->body_begin();
5862 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005863 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005864 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5865 OMPTeamsFound = false;
5866 break;
5867 }
5868 ++I;
5869 }
5870 assert(I != CS->body_end() && "Not found statement");
5871 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005872 } else {
5873 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5874 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005875 }
5876 if (!OMPTeamsFound) {
5877 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5878 Diag(DSAStack->getInnerTeamsRegionLoc(),
5879 diag::note_omp_nested_teams_construct_here);
5880 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5881 << isa<OMPExecutableDirective>(S);
5882 return StmtError();
5883 }
5884 }
5885
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005886 getCurFunction()->setHasBranchProtectedScope();
5887
5888 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5889}
5890
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005891StmtResult
5892Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5893 Stmt *AStmt, SourceLocation StartLoc,
5894 SourceLocation EndLoc) {
5895 if (!AStmt)
5896 return StmtError();
5897
5898 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5899 // 1.2.2 OpenMP Language Terminology
5900 // Structured block - An executable statement with a single entry at the
5901 // top and a single exit at the bottom.
5902 // The point of exit cannot be a branch out of the structured block.
5903 // longjmp() and throw() must not violate the entry/exit criteria.
5904 CS->getCapturedDecl()->setNothrow();
5905
5906 getCurFunction()->setHasBranchProtectedScope();
5907
5908 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5909 AStmt);
5910}
5911
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005912StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5913 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5914 SourceLocation EndLoc,
5915 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5916 if (!AStmt)
5917 return StmtError();
5918
5919 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5920 // 1.2.2 OpenMP Language Terminology
5921 // Structured block - An executable statement with a single entry at the
5922 // top and a single exit at the bottom.
5923 // The point of exit cannot be a branch out of the structured block.
5924 // longjmp() and throw() must not violate the entry/exit criteria.
5925 CS->getCapturedDecl()->setNothrow();
5926
5927 OMPLoopDirective::HelperExprs B;
5928 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5929 // define the nested loops number.
5930 unsigned NestedLoopCount =
5931 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5932 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5933 VarsWithImplicitDSA, B);
5934 if (NestedLoopCount == 0)
5935 return StmtError();
5936
5937 assert((CurContext->isDependentContext() || B.builtAll()) &&
5938 "omp target parallel for loop exprs were not built");
5939
5940 if (!CurContext->isDependentContext()) {
5941 // Finalize the clauses that need pre-built expressions for CodeGen.
5942 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005943 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005944 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005945 B.NumIterations, *this, CurScope,
5946 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005947 return StmtError();
5948 }
5949 }
5950
5951 getCurFunction()->setHasBranchProtectedScope();
5952 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5953 NestedLoopCount, Clauses, AStmt,
5954 B, DSAStack->isCancelRegion());
5955}
5956
Alexey Bataev95b64a92017-05-30 16:00:04 +00005957/// Check for existence of a map clause in the list of clauses.
5958static bool hasClauses(ArrayRef<OMPClause *> Clauses,
5959 const OpenMPClauseKind K) {
5960 return llvm::any_of(
5961 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
5962}
Samuel Antaodf67fc42016-01-19 19:15:56 +00005963
Alexey Bataev95b64a92017-05-30 16:00:04 +00005964template <typename... Params>
5965static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
5966 const Params... ClauseTypes) {
5967 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00005968}
5969
Michael Wong65f367f2015-07-21 13:44:28 +00005970StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5971 Stmt *AStmt,
5972 SourceLocation StartLoc,
5973 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005974 if (!AStmt)
5975 return StmtError();
5976
5977 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5978
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005979 // OpenMP [2.10.1, Restrictions, p. 97]
5980 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00005981 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
5982 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
5983 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00005984 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005985 return StmtError();
5986 }
5987
Michael Wong65f367f2015-07-21 13:44:28 +00005988 getCurFunction()->setHasBranchProtectedScope();
5989
5990 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5991 AStmt);
5992}
5993
Samuel Antaodf67fc42016-01-19 19:15:56 +00005994StmtResult
5995Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5996 SourceLocation StartLoc,
5997 SourceLocation EndLoc) {
5998 // OpenMP [2.10.2, Restrictions, p. 99]
5999 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006000 if (!hasClauses(Clauses, OMPC_map)) {
6001 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6002 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006003 return StmtError();
6004 }
6005
6006 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6007 Clauses);
6008}
6009
Samuel Antao72590762016-01-19 20:04:50 +00006010StmtResult
6011Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6012 SourceLocation StartLoc,
6013 SourceLocation EndLoc) {
6014 // OpenMP [2.10.3, Restrictions, p. 102]
6015 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006016 if (!hasClauses(Clauses, OMPC_map)) {
6017 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6018 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006019 return StmtError();
6020 }
6021
6022 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6023}
6024
Samuel Antao686c70c2016-05-26 17:30:50 +00006025StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6026 SourceLocation StartLoc,
6027 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006028 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006029 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6030 return StmtError();
6031 }
6032 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6033}
6034
Alexey Bataev13314bf2014-10-09 04:18:56 +00006035StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6036 Stmt *AStmt, SourceLocation StartLoc,
6037 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006038 if (!AStmt)
6039 return StmtError();
6040
Alexey Bataev13314bf2014-10-09 04:18:56 +00006041 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6042 // 1.2.2 OpenMP Language Terminology
6043 // Structured block - An executable statement with a single entry at the
6044 // top and a single exit at the bottom.
6045 // The point of exit cannot be a branch out of the structured block.
6046 // longjmp() and throw() must not violate the entry/exit criteria.
6047 CS->getCapturedDecl()->setNothrow();
6048
6049 getCurFunction()->setHasBranchProtectedScope();
6050
6051 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6052}
6053
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006054StmtResult
6055Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6056 SourceLocation EndLoc,
6057 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006058 if (DSAStack->isParentNowaitRegion()) {
6059 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6060 return StmtError();
6061 }
6062 if (DSAStack->isParentOrderedRegion()) {
6063 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6064 return StmtError();
6065 }
6066 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6067 CancelRegion);
6068}
6069
Alexey Bataev87933c72015-09-18 08:07:34 +00006070StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6071 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006072 SourceLocation EndLoc,
6073 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006074 if (DSAStack->isParentNowaitRegion()) {
6075 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6076 return StmtError();
6077 }
6078 if (DSAStack->isParentOrderedRegion()) {
6079 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6080 return StmtError();
6081 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006082 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006083 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6084 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006085}
6086
Alexey Bataev382967a2015-12-08 12:06:20 +00006087static bool checkGrainsizeNumTasksClauses(Sema &S,
6088 ArrayRef<OMPClause *> Clauses) {
6089 OMPClause *PrevClause = nullptr;
6090 bool ErrorFound = false;
6091 for (auto *C : Clauses) {
6092 if (C->getClauseKind() == OMPC_grainsize ||
6093 C->getClauseKind() == OMPC_num_tasks) {
6094 if (!PrevClause)
6095 PrevClause = C;
6096 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6097 S.Diag(C->getLocStart(),
6098 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6099 << getOpenMPClauseName(C->getClauseKind())
6100 << getOpenMPClauseName(PrevClause->getClauseKind());
6101 S.Diag(PrevClause->getLocStart(),
6102 diag::note_omp_previous_grainsize_num_tasks)
6103 << getOpenMPClauseName(PrevClause->getClauseKind());
6104 ErrorFound = true;
6105 }
6106 }
6107 }
6108 return ErrorFound;
6109}
6110
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006111static bool checkReductionClauseWithNogroup(Sema &S,
6112 ArrayRef<OMPClause *> Clauses) {
6113 OMPClause *ReductionClause = nullptr;
6114 OMPClause *NogroupClause = nullptr;
6115 for (auto *C : Clauses) {
6116 if (C->getClauseKind() == OMPC_reduction) {
6117 ReductionClause = C;
6118 if (NogroupClause)
6119 break;
6120 continue;
6121 }
6122 if (C->getClauseKind() == OMPC_nogroup) {
6123 NogroupClause = C;
6124 if (ReductionClause)
6125 break;
6126 continue;
6127 }
6128 }
6129 if (ReductionClause && NogroupClause) {
6130 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6131 << SourceRange(NogroupClause->getLocStart(),
6132 NogroupClause->getLocEnd());
6133 return true;
6134 }
6135 return false;
6136}
6137
Alexey Bataev49f6e782015-12-01 04:18:41 +00006138StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6139 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6140 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006141 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006142 if (!AStmt)
6143 return StmtError();
6144
6145 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6146 OMPLoopDirective::HelperExprs B;
6147 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6148 // define the nested loops number.
6149 unsigned NestedLoopCount =
6150 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006151 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006152 VarsWithImplicitDSA, B);
6153 if (NestedLoopCount == 0)
6154 return StmtError();
6155
6156 assert((CurContext->isDependentContext() || B.builtAll()) &&
6157 "omp for loop exprs were not built");
6158
Alexey Bataev382967a2015-12-08 12:06:20 +00006159 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6160 // The grainsize clause and num_tasks clause are mutually exclusive and may
6161 // not appear on the same taskloop directive.
6162 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6163 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006164 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6165 // If a reduction clause is present on the taskloop directive, the nogroup
6166 // clause must not be specified.
6167 if (checkReductionClauseWithNogroup(*this, Clauses))
6168 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006169
Alexey Bataev49f6e782015-12-01 04:18:41 +00006170 getCurFunction()->setHasBranchProtectedScope();
6171 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6172 NestedLoopCount, Clauses, AStmt, B);
6173}
6174
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006175StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6176 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6177 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006178 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006179 if (!AStmt)
6180 return StmtError();
6181
6182 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6183 OMPLoopDirective::HelperExprs B;
6184 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6185 // define the nested loops number.
6186 unsigned NestedLoopCount =
6187 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6188 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6189 VarsWithImplicitDSA, B);
6190 if (NestedLoopCount == 0)
6191 return StmtError();
6192
6193 assert((CurContext->isDependentContext() || B.builtAll()) &&
6194 "omp for loop exprs were not built");
6195
Alexey Bataev5a3af132016-03-29 08:58:54 +00006196 if (!CurContext->isDependentContext()) {
6197 // Finalize the clauses that need pre-built expressions for CodeGen.
6198 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006199 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006200 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006201 B.NumIterations, *this, CurScope,
6202 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006203 return StmtError();
6204 }
6205 }
6206
Alexey Bataev382967a2015-12-08 12:06:20 +00006207 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6208 // The grainsize clause and num_tasks clause are mutually exclusive and may
6209 // not appear on the same taskloop directive.
6210 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6211 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006212 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6213 // If a reduction clause is present on the taskloop directive, the nogroup
6214 // clause must not be specified.
6215 if (checkReductionClauseWithNogroup(*this, Clauses))
6216 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006217
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006218 getCurFunction()->setHasBranchProtectedScope();
6219 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6220 NestedLoopCount, Clauses, AStmt, B);
6221}
6222
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006223StmtResult Sema::ActOnOpenMPDistributeDirective(
6224 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6225 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006226 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006227 if (!AStmt)
6228 return StmtError();
6229
6230 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6231 OMPLoopDirective::HelperExprs B;
6232 // In presence of clause 'collapse' with number of loops, it will
6233 // define the nested loops number.
6234 unsigned NestedLoopCount =
6235 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6236 nullptr /*ordered not a clause on distribute*/, AStmt,
6237 *this, *DSAStack, VarsWithImplicitDSA, B);
6238 if (NestedLoopCount == 0)
6239 return StmtError();
6240
6241 assert((CurContext->isDependentContext() || B.builtAll()) &&
6242 "omp for loop exprs were not built");
6243
6244 getCurFunction()->setHasBranchProtectedScope();
6245 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6246 NestedLoopCount, Clauses, AStmt, B);
6247}
6248
Carlo Bertolli9925f152016-06-27 14:55:37 +00006249StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6250 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6251 SourceLocation EndLoc,
6252 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6253 if (!AStmt)
6254 return StmtError();
6255
6256 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6257 // 1.2.2 OpenMP Language Terminology
6258 // Structured block - An executable statement with a single entry at the
6259 // top and a single exit at the bottom.
6260 // The point of exit cannot be a branch out of the structured block.
6261 // longjmp() and throw() must not violate the entry/exit criteria.
6262 CS->getCapturedDecl()->setNothrow();
6263
6264 OMPLoopDirective::HelperExprs B;
6265 // In presence of clause 'collapse' with number of loops, it will
6266 // define the nested loops number.
6267 unsigned NestedLoopCount = CheckOpenMPLoop(
6268 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6269 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6270 VarsWithImplicitDSA, B);
6271 if (NestedLoopCount == 0)
6272 return StmtError();
6273
6274 assert((CurContext->isDependentContext() || B.builtAll()) &&
6275 "omp for loop exprs were not built");
6276
6277 getCurFunction()->setHasBranchProtectedScope();
6278 return OMPDistributeParallelForDirective::Create(
6279 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6280}
6281
Kelvin Li4a39add2016-07-05 05:00:15 +00006282StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6283 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6284 SourceLocation EndLoc,
6285 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6286 if (!AStmt)
6287 return StmtError();
6288
6289 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6290 // 1.2.2 OpenMP Language Terminology
6291 // Structured block - An executable statement with a single entry at the
6292 // top and a single exit at the bottom.
6293 // The point of exit cannot be a branch out of the structured block.
6294 // longjmp() and throw() must not violate the entry/exit criteria.
6295 CS->getCapturedDecl()->setNothrow();
6296
6297 OMPLoopDirective::HelperExprs B;
6298 // In presence of clause 'collapse' with number of loops, it will
6299 // define the nested loops number.
6300 unsigned NestedLoopCount = CheckOpenMPLoop(
6301 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6302 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6303 VarsWithImplicitDSA, B);
6304 if (NestedLoopCount == 0)
6305 return StmtError();
6306
6307 assert((CurContext->isDependentContext() || B.builtAll()) &&
6308 "omp for loop exprs were not built");
6309
Kelvin Lic5609492016-07-15 04:39:07 +00006310 if (checkSimdlenSafelenSpecified(*this, Clauses))
6311 return StmtError();
6312
Kelvin Li4a39add2016-07-05 05:00:15 +00006313 getCurFunction()->setHasBranchProtectedScope();
6314 return OMPDistributeParallelForSimdDirective::Create(
6315 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6316}
6317
Kelvin Li787f3fc2016-07-06 04:45:38 +00006318StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6319 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6320 SourceLocation EndLoc,
6321 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6322 if (!AStmt)
6323 return StmtError();
6324
6325 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6326 // 1.2.2 OpenMP Language Terminology
6327 // Structured block - An executable statement with a single entry at the
6328 // top and a single exit at the bottom.
6329 // The point of exit cannot be a branch out of the structured block.
6330 // longjmp() and throw() must not violate the entry/exit criteria.
6331 CS->getCapturedDecl()->setNothrow();
6332
6333 OMPLoopDirective::HelperExprs B;
6334 // In presence of clause 'collapse' with number of loops, it will
6335 // define the nested loops number.
6336 unsigned NestedLoopCount =
6337 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6338 nullptr /*ordered not a clause on distribute*/, AStmt,
6339 *this, *DSAStack, VarsWithImplicitDSA, B);
6340 if (NestedLoopCount == 0)
6341 return StmtError();
6342
6343 assert((CurContext->isDependentContext() || B.builtAll()) &&
6344 "omp for loop exprs were not built");
6345
Kelvin Lic5609492016-07-15 04:39:07 +00006346 if (checkSimdlenSafelenSpecified(*this, Clauses))
6347 return StmtError();
6348
Kelvin Li787f3fc2016-07-06 04:45:38 +00006349 getCurFunction()->setHasBranchProtectedScope();
6350 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6351 NestedLoopCount, Clauses, AStmt, B);
6352}
6353
Kelvin Lia579b912016-07-14 02:54:56 +00006354StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6355 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6356 SourceLocation EndLoc,
6357 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6358 if (!AStmt)
6359 return StmtError();
6360
6361 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6362 // 1.2.2 OpenMP Language Terminology
6363 // Structured block - An executable statement with a single entry at the
6364 // top and a single exit at the bottom.
6365 // The point of exit cannot be a branch out of the structured block.
6366 // longjmp() and throw() must not violate the entry/exit criteria.
6367 CS->getCapturedDecl()->setNothrow();
6368
6369 OMPLoopDirective::HelperExprs B;
6370 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6371 // define the nested loops number.
6372 unsigned NestedLoopCount = CheckOpenMPLoop(
6373 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6374 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6375 VarsWithImplicitDSA, B);
6376 if (NestedLoopCount == 0)
6377 return StmtError();
6378
6379 assert((CurContext->isDependentContext() || B.builtAll()) &&
6380 "omp target parallel for simd loop exprs were not built");
6381
6382 if (!CurContext->isDependentContext()) {
6383 // Finalize the clauses that need pre-built expressions for CodeGen.
6384 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006385 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006386 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6387 B.NumIterations, *this, CurScope,
6388 DSAStack))
6389 return StmtError();
6390 }
6391 }
Kelvin Lic5609492016-07-15 04:39:07 +00006392 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006393 return StmtError();
6394
6395 getCurFunction()->setHasBranchProtectedScope();
6396 return OMPTargetParallelForSimdDirective::Create(
6397 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6398}
6399
Kelvin Li986330c2016-07-20 22:57:10 +00006400StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6401 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6402 SourceLocation EndLoc,
6403 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6404 if (!AStmt)
6405 return StmtError();
6406
6407 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6408 // 1.2.2 OpenMP Language Terminology
6409 // Structured block - An executable statement with a single entry at the
6410 // top and a single exit at the bottom.
6411 // The point of exit cannot be a branch out of the structured block.
6412 // longjmp() and throw() must not violate the entry/exit criteria.
6413 CS->getCapturedDecl()->setNothrow();
6414
6415 OMPLoopDirective::HelperExprs B;
6416 // In presence of clause 'collapse' with number of loops, it will define the
6417 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006418 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006419 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6420 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6421 VarsWithImplicitDSA, B);
6422 if (NestedLoopCount == 0)
6423 return StmtError();
6424
6425 assert((CurContext->isDependentContext() || B.builtAll()) &&
6426 "omp target simd loop exprs were not built");
6427
6428 if (!CurContext->isDependentContext()) {
6429 // Finalize the clauses that need pre-built expressions for CodeGen.
6430 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006431 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006432 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6433 B.NumIterations, *this, CurScope,
6434 DSAStack))
6435 return StmtError();
6436 }
6437 }
6438
6439 if (checkSimdlenSafelenSpecified(*this, Clauses))
6440 return StmtError();
6441
6442 getCurFunction()->setHasBranchProtectedScope();
6443 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6444 NestedLoopCount, Clauses, AStmt, B);
6445}
6446
Kelvin Li02532872016-08-05 14:37:37 +00006447StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6448 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6449 SourceLocation EndLoc,
6450 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6451 if (!AStmt)
6452 return StmtError();
6453
6454 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6455 // 1.2.2 OpenMP Language Terminology
6456 // Structured block - An executable statement with a single entry at the
6457 // top and a single exit at the bottom.
6458 // The point of exit cannot be a branch out of the structured block.
6459 // longjmp() and throw() must not violate the entry/exit criteria.
6460 CS->getCapturedDecl()->setNothrow();
6461
6462 OMPLoopDirective::HelperExprs B;
6463 // In presence of clause 'collapse' with number of loops, it will
6464 // define the nested loops number.
6465 unsigned NestedLoopCount =
6466 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6467 nullptr /*ordered not a clause on distribute*/, AStmt,
6468 *this, *DSAStack, VarsWithImplicitDSA, B);
6469 if (NestedLoopCount == 0)
6470 return StmtError();
6471
6472 assert((CurContext->isDependentContext() || B.builtAll()) &&
6473 "omp teams distribute loop exprs were not built");
6474
6475 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006476 return OMPTeamsDistributeDirective::Create(
6477 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006478}
6479
Kelvin Li4e325f72016-10-25 12:50:55 +00006480StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6481 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6482 SourceLocation EndLoc,
6483 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6484 if (!AStmt)
6485 return StmtError();
6486
6487 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6488 // 1.2.2 OpenMP Language Terminology
6489 // Structured block - An executable statement with a single entry at the
6490 // top and a single exit at the bottom.
6491 // The point of exit cannot be a branch out of the structured block.
6492 // longjmp() and throw() must not violate the entry/exit criteria.
6493 CS->getCapturedDecl()->setNothrow();
6494
6495 OMPLoopDirective::HelperExprs B;
6496 // In presence of clause 'collapse' with number of loops, it will
6497 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006498 unsigned NestedLoopCount = CheckOpenMPLoop(
6499 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6500 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6501 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006502
6503 if (NestedLoopCount == 0)
6504 return StmtError();
6505
6506 assert((CurContext->isDependentContext() || B.builtAll()) &&
6507 "omp teams distribute simd loop exprs were not built");
6508
6509 if (!CurContext->isDependentContext()) {
6510 // Finalize the clauses that need pre-built expressions for CodeGen.
6511 for (auto C : Clauses) {
6512 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6513 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6514 B.NumIterations, *this, CurScope,
6515 DSAStack))
6516 return StmtError();
6517 }
6518 }
6519
6520 if (checkSimdlenSafelenSpecified(*this, Clauses))
6521 return StmtError();
6522
6523 getCurFunction()->setHasBranchProtectedScope();
6524 return OMPTeamsDistributeSimdDirective::Create(
6525 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6526}
6527
Kelvin Li579e41c2016-11-30 23:51:03 +00006528StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6529 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6530 SourceLocation EndLoc,
6531 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6532 if (!AStmt)
6533 return StmtError();
6534
6535 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6536 // 1.2.2 OpenMP Language Terminology
6537 // Structured block - An executable statement with a single entry at the
6538 // top and a single exit at the bottom.
6539 // The point of exit cannot be a branch out of the structured block.
6540 // longjmp() and throw() must not violate the entry/exit criteria.
6541 CS->getCapturedDecl()->setNothrow();
6542
6543 OMPLoopDirective::HelperExprs B;
6544 // In presence of clause 'collapse' with number of loops, it will
6545 // define the nested loops number.
6546 auto NestedLoopCount = CheckOpenMPLoop(
6547 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6548 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6549 VarsWithImplicitDSA, B);
6550
6551 if (NestedLoopCount == 0)
6552 return StmtError();
6553
6554 assert((CurContext->isDependentContext() || B.builtAll()) &&
6555 "omp for loop exprs were not built");
6556
6557 if (!CurContext->isDependentContext()) {
6558 // Finalize the clauses that need pre-built expressions for CodeGen.
6559 for (auto C : Clauses) {
6560 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6561 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6562 B.NumIterations, *this, CurScope,
6563 DSAStack))
6564 return StmtError();
6565 }
6566 }
6567
6568 if (checkSimdlenSafelenSpecified(*this, Clauses))
6569 return StmtError();
6570
6571 getCurFunction()->setHasBranchProtectedScope();
6572 return OMPTeamsDistributeParallelForSimdDirective::Create(
6573 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6574}
6575
Kelvin Li7ade93f2016-12-09 03:24:30 +00006576StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6577 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6578 SourceLocation EndLoc,
6579 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6580 if (!AStmt)
6581 return StmtError();
6582
6583 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6584 // 1.2.2 OpenMP Language Terminology
6585 // Structured block - An executable statement with a single entry at the
6586 // top and a single exit at the bottom.
6587 // The point of exit cannot be a branch out of the structured block.
6588 // longjmp() and throw() must not violate the entry/exit criteria.
6589 CS->getCapturedDecl()->setNothrow();
6590
6591 OMPLoopDirective::HelperExprs B;
6592 // In presence of clause 'collapse' with number of loops, it will
6593 // define the nested loops number.
6594 unsigned NestedLoopCount = CheckOpenMPLoop(
6595 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6596 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6597 VarsWithImplicitDSA, B);
6598
6599 if (NestedLoopCount == 0)
6600 return StmtError();
6601
6602 assert((CurContext->isDependentContext() || B.builtAll()) &&
6603 "omp for loop exprs were not built");
6604
6605 if (!CurContext->isDependentContext()) {
6606 // Finalize the clauses that need pre-built expressions for CodeGen.
6607 for (auto C : Clauses) {
6608 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6609 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6610 B.NumIterations, *this, CurScope,
6611 DSAStack))
6612 return StmtError();
6613 }
6614 }
6615
6616 getCurFunction()->setHasBranchProtectedScope();
6617 return OMPTeamsDistributeParallelForDirective::Create(
6618 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6619}
6620
Kelvin Libf594a52016-12-17 05:48:59 +00006621StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6622 Stmt *AStmt,
6623 SourceLocation StartLoc,
6624 SourceLocation EndLoc) {
6625 if (!AStmt)
6626 return StmtError();
6627
6628 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6629 // 1.2.2 OpenMP Language Terminology
6630 // Structured block - An executable statement with a single entry at the
6631 // top and a single exit at the bottom.
6632 // The point of exit cannot be a branch out of the structured block.
6633 // longjmp() and throw() must not violate the entry/exit criteria.
6634 CS->getCapturedDecl()->setNothrow();
6635
6636 getCurFunction()->setHasBranchProtectedScope();
6637
6638 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6639 AStmt);
6640}
6641
Kelvin Li83c451e2016-12-25 04:52:54 +00006642StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6643 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6644 SourceLocation EndLoc,
6645 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6646 if (!AStmt)
6647 return StmtError();
6648
6649 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6650 // 1.2.2 OpenMP Language Terminology
6651 // Structured block - An executable statement with a single entry at the
6652 // top and a single exit at the bottom.
6653 // The point of exit cannot be a branch out of the structured block.
6654 // longjmp() and throw() must not violate the entry/exit criteria.
6655 CS->getCapturedDecl()->setNothrow();
6656
6657 OMPLoopDirective::HelperExprs B;
6658 // In presence of clause 'collapse' with number of loops, it will
6659 // define the nested loops number.
6660 auto NestedLoopCount = CheckOpenMPLoop(
6661 OMPD_target_teams_distribute,
6662 getCollapseNumberExpr(Clauses),
6663 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6664 VarsWithImplicitDSA, B);
6665 if (NestedLoopCount == 0)
6666 return StmtError();
6667
6668 assert((CurContext->isDependentContext() || B.builtAll()) &&
6669 "omp target teams distribute loop exprs were not built");
6670
6671 getCurFunction()->setHasBranchProtectedScope();
6672 return OMPTargetTeamsDistributeDirective::Create(
6673 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6674}
6675
Kelvin Li80e8f562016-12-29 22:16:30 +00006676StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6677 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6678 SourceLocation EndLoc,
6679 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6680 if (!AStmt)
6681 return StmtError();
6682
6683 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6684 // 1.2.2 OpenMP Language Terminology
6685 // Structured block - An executable statement with a single entry at the
6686 // top and a single exit at the bottom.
6687 // The point of exit cannot be a branch out of the structured block.
6688 // longjmp() and throw() must not violate the entry/exit criteria.
6689 CS->getCapturedDecl()->setNothrow();
6690
6691 OMPLoopDirective::HelperExprs B;
6692 // In presence of clause 'collapse' with number of loops, it will
6693 // define the nested loops number.
6694 auto NestedLoopCount = CheckOpenMPLoop(
6695 OMPD_target_teams_distribute_parallel_for,
6696 getCollapseNumberExpr(Clauses),
6697 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6698 VarsWithImplicitDSA, B);
6699 if (NestedLoopCount == 0)
6700 return StmtError();
6701
6702 assert((CurContext->isDependentContext() || B.builtAll()) &&
6703 "omp target teams distribute parallel for loop exprs were not built");
6704
6705 if (!CurContext->isDependentContext()) {
6706 // Finalize the clauses that need pre-built expressions for CodeGen.
6707 for (auto C : Clauses) {
6708 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6709 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6710 B.NumIterations, *this, CurScope,
6711 DSAStack))
6712 return StmtError();
6713 }
6714 }
6715
6716 getCurFunction()->setHasBranchProtectedScope();
6717 return OMPTargetTeamsDistributeParallelForDirective::Create(
6718 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6719}
6720
Kelvin Li1851df52017-01-03 05:23:48 +00006721StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6722 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6723 SourceLocation EndLoc,
6724 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6725 if (!AStmt)
6726 return StmtError();
6727
6728 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6729 // 1.2.2 OpenMP Language Terminology
6730 // Structured block - An executable statement with a single entry at the
6731 // top and a single exit at the bottom.
6732 // The point of exit cannot be a branch out of the structured block.
6733 // longjmp() and throw() must not violate the entry/exit criteria.
6734 CS->getCapturedDecl()->setNothrow();
6735
6736 OMPLoopDirective::HelperExprs B;
6737 // In presence of clause 'collapse' with number of loops, it will
6738 // define the nested loops number.
6739 auto NestedLoopCount = CheckOpenMPLoop(
6740 OMPD_target_teams_distribute_parallel_for_simd,
6741 getCollapseNumberExpr(Clauses),
6742 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6743 VarsWithImplicitDSA, B);
6744 if (NestedLoopCount == 0)
6745 return StmtError();
6746
6747 assert((CurContext->isDependentContext() || B.builtAll()) &&
6748 "omp target teams distribute parallel for simd loop exprs were not "
6749 "built");
6750
6751 if (!CurContext->isDependentContext()) {
6752 // Finalize the clauses that need pre-built expressions for CodeGen.
6753 for (auto C : Clauses) {
6754 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6755 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6756 B.NumIterations, *this, CurScope,
6757 DSAStack))
6758 return StmtError();
6759 }
6760 }
6761
6762 getCurFunction()->setHasBranchProtectedScope();
6763 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6764 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6765}
6766
Kelvin Lida681182017-01-10 18:08:18 +00006767StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6768 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6769 SourceLocation EndLoc,
6770 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6771 if (!AStmt)
6772 return StmtError();
6773
6774 auto *CS = cast<CapturedStmt>(AStmt);
6775 // 1.2.2 OpenMP Language Terminology
6776 // Structured block - An executable statement with a single entry at the
6777 // top and a single exit at the bottom.
6778 // The point of exit cannot be a branch out of the structured block.
6779 // longjmp() and throw() must not violate the entry/exit criteria.
6780 CS->getCapturedDecl()->setNothrow();
6781
6782 OMPLoopDirective::HelperExprs B;
6783 // In presence of clause 'collapse' with number of loops, it will
6784 // define the nested loops number.
6785 auto NestedLoopCount = CheckOpenMPLoop(
6786 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6787 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6788 VarsWithImplicitDSA, B);
6789 if (NestedLoopCount == 0)
6790 return StmtError();
6791
6792 assert((CurContext->isDependentContext() || B.builtAll()) &&
6793 "omp target teams distribute simd loop exprs were not built");
6794
6795 getCurFunction()->setHasBranchProtectedScope();
6796 return OMPTargetTeamsDistributeSimdDirective::Create(
6797 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6798}
6799
Alexey Bataeved09d242014-05-28 05:53:51 +00006800OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006801 SourceLocation StartLoc,
6802 SourceLocation LParenLoc,
6803 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006804 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006805 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006806 case OMPC_final:
6807 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6808 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006809 case OMPC_num_threads:
6810 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6811 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006812 case OMPC_safelen:
6813 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6814 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006815 case OMPC_simdlen:
6816 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6817 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006818 case OMPC_collapse:
6819 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6820 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006821 case OMPC_ordered:
6822 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6823 break;
Michael Wonge710d542015-08-07 16:16:36 +00006824 case OMPC_device:
6825 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6826 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006827 case OMPC_num_teams:
6828 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6829 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006830 case OMPC_thread_limit:
6831 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6832 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006833 case OMPC_priority:
6834 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6835 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006836 case OMPC_grainsize:
6837 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6838 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006839 case OMPC_num_tasks:
6840 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6841 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006842 case OMPC_hint:
6843 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6844 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006845 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006846 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006847 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006848 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006849 case OMPC_private:
6850 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006851 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006852 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006853 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006854 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006855 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006856 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006857 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006858 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006859 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006860 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006861 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006862 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006863 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006864 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006865 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006866 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006867 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006868 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006869 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006870 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006871 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006872 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006873 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006874 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006875 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006876 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006877 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006878 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006879 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006880 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006881 llvm_unreachable("Clause is not allowed.");
6882 }
6883 return Res;
6884}
6885
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006886// An OpenMP directive such as 'target parallel' has two captured regions:
6887// for the 'target' and 'parallel' respectively. This function returns
6888// the region in which to capture expressions associated with a clause.
6889// A return value of OMPD_unknown signifies that the expression should not
6890// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006891static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6892 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6893 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006894 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6895
6896 switch (CKind) {
6897 case OMPC_if:
6898 switch (DKind) {
6899 case OMPD_target_parallel:
6900 // If this clause applies to the nested 'parallel' region, capture within
6901 // the 'target' region, otherwise do not capture.
6902 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6903 CaptureRegion = OMPD_target;
6904 break;
6905 case OMPD_cancel:
6906 case OMPD_parallel:
6907 case OMPD_parallel_sections:
6908 case OMPD_parallel_for:
6909 case OMPD_parallel_for_simd:
6910 case OMPD_target:
6911 case OMPD_target_simd:
6912 case OMPD_target_parallel_for:
6913 case OMPD_target_parallel_for_simd:
6914 case OMPD_target_teams:
6915 case OMPD_target_teams_distribute:
6916 case OMPD_target_teams_distribute_simd:
6917 case OMPD_target_teams_distribute_parallel_for:
6918 case OMPD_target_teams_distribute_parallel_for_simd:
6919 case OMPD_teams_distribute_parallel_for:
6920 case OMPD_teams_distribute_parallel_for_simd:
6921 case OMPD_distribute_parallel_for:
6922 case OMPD_distribute_parallel_for_simd:
6923 case OMPD_task:
6924 case OMPD_taskloop:
6925 case OMPD_taskloop_simd:
6926 case OMPD_target_data:
6927 case OMPD_target_enter_data:
6928 case OMPD_target_exit_data:
6929 case OMPD_target_update:
6930 // Do not capture if-clause expressions.
6931 break;
6932 case OMPD_threadprivate:
6933 case OMPD_taskyield:
6934 case OMPD_barrier:
6935 case OMPD_taskwait:
6936 case OMPD_cancellation_point:
6937 case OMPD_flush:
6938 case OMPD_declare_reduction:
6939 case OMPD_declare_simd:
6940 case OMPD_declare_target:
6941 case OMPD_end_declare_target:
6942 case OMPD_teams:
6943 case OMPD_simd:
6944 case OMPD_for:
6945 case OMPD_for_simd:
6946 case OMPD_sections:
6947 case OMPD_section:
6948 case OMPD_single:
6949 case OMPD_master:
6950 case OMPD_critical:
6951 case OMPD_taskgroup:
6952 case OMPD_distribute:
6953 case OMPD_ordered:
6954 case OMPD_atomic:
6955 case OMPD_distribute_simd:
6956 case OMPD_teams_distribute:
6957 case OMPD_teams_distribute_simd:
6958 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6959 case OMPD_unknown:
6960 llvm_unreachable("Unknown OpenMP directive");
6961 }
6962 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006963 case OMPC_num_threads:
6964 switch (DKind) {
6965 case OMPD_target_parallel:
6966 CaptureRegion = OMPD_target;
6967 break;
6968 case OMPD_cancel:
6969 case OMPD_parallel:
6970 case OMPD_parallel_sections:
6971 case OMPD_parallel_for:
6972 case OMPD_parallel_for_simd:
6973 case OMPD_target:
6974 case OMPD_target_simd:
6975 case OMPD_target_parallel_for:
6976 case OMPD_target_parallel_for_simd:
6977 case OMPD_target_teams:
6978 case OMPD_target_teams_distribute:
6979 case OMPD_target_teams_distribute_simd:
6980 case OMPD_target_teams_distribute_parallel_for:
6981 case OMPD_target_teams_distribute_parallel_for_simd:
6982 case OMPD_teams_distribute_parallel_for:
6983 case OMPD_teams_distribute_parallel_for_simd:
6984 case OMPD_distribute_parallel_for:
6985 case OMPD_distribute_parallel_for_simd:
6986 case OMPD_task:
6987 case OMPD_taskloop:
6988 case OMPD_taskloop_simd:
6989 case OMPD_target_data:
6990 case OMPD_target_enter_data:
6991 case OMPD_target_exit_data:
6992 case OMPD_target_update:
6993 // Do not capture num_threads-clause expressions.
6994 break;
6995 case OMPD_threadprivate:
6996 case OMPD_taskyield:
6997 case OMPD_barrier:
6998 case OMPD_taskwait:
6999 case OMPD_cancellation_point:
7000 case OMPD_flush:
7001 case OMPD_declare_reduction:
7002 case OMPD_declare_simd:
7003 case OMPD_declare_target:
7004 case OMPD_end_declare_target:
7005 case OMPD_teams:
7006 case OMPD_simd:
7007 case OMPD_for:
7008 case OMPD_for_simd:
7009 case OMPD_sections:
7010 case OMPD_section:
7011 case OMPD_single:
7012 case OMPD_master:
7013 case OMPD_critical:
7014 case OMPD_taskgroup:
7015 case OMPD_distribute:
7016 case OMPD_ordered:
7017 case OMPD_atomic:
7018 case OMPD_distribute_simd:
7019 case OMPD_teams_distribute:
7020 case OMPD_teams_distribute_simd:
7021 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7022 case OMPD_unknown:
7023 llvm_unreachable("Unknown OpenMP directive");
7024 }
7025 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007026 case OMPC_num_teams:
7027 switch (DKind) {
7028 case OMPD_target_teams:
7029 CaptureRegion = OMPD_target;
7030 break;
7031 case OMPD_cancel:
7032 case OMPD_parallel:
7033 case OMPD_parallel_sections:
7034 case OMPD_parallel_for:
7035 case OMPD_parallel_for_simd:
7036 case OMPD_target:
7037 case OMPD_target_simd:
7038 case OMPD_target_parallel:
7039 case OMPD_target_parallel_for:
7040 case OMPD_target_parallel_for_simd:
7041 case OMPD_target_teams_distribute:
7042 case OMPD_target_teams_distribute_simd:
7043 case OMPD_target_teams_distribute_parallel_for:
7044 case OMPD_target_teams_distribute_parallel_for_simd:
7045 case OMPD_teams_distribute_parallel_for:
7046 case OMPD_teams_distribute_parallel_for_simd:
7047 case OMPD_distribute_parallel_for:
7048 case OMPD_distribute_parallel_for_simd:
7049 case OMPD_task:
7050 case OMPD_taskloop:
7051 case OMPD_taskloop_simd:
7052 case OMPD_target_data:
7053 case OMPD_target_enter_data:
7054 case OMPD_target_exit_data:
7055 case OMPD_target_update:
7056 case OMPD_teams:
7057 case OMPD_teams_distribute:
7058 case OMPD_teams_distribute_simd:
7059 // Do not capture num_teams-clause expressions.
7060 break;
7061 case OMPD_threadprivate:
7062 case OMPD_taskyield:
7063 case OMPD_barrier:
7064 case OMPD_taskwait:
7065 case OMPD_cancellation_point:
7066 case OMPD_flush:
7067 case OMPD_declare_reduction:
7068 case OMPD_declare_simd:
7069 case OMPD_declare_target:
7070 case OMPD_end_declare_target:
7071 case OMPD_simd:
7072 case OMPD_for:
7073 case OMPD_for_simd:
7074 case OMPD_sections:
7075 case OMPD_section:
7076 case OMPD_single:
7077 case OMPD_master:
7078 case OMPD_critical:
7079 case OMPD_taskgroup:
7080 case OMPD_distribute:
7081 case OMPD_ordered:
7082 case OMPD_atomic:
7083 case OMPD_distribute_simd:
7084 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7085 case OMPD_unknown:
7086 llvm_unreachable("Unknown OpenMP directive");
7087 }
7088 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007089 case OMPC_thread_limit:
7090 switch (DKind) {
7091 case OMPD_target_teams:
7092 CaptureRegion = OMPD_target;
7093 break;
7094 case OMPD_cancel:
7095 case OMPD_parallel:
7096 case OMPD_parallel_sections:
7097 case OMPD_parallel_for:
7098 case OMPD_parallel_for_simd:
7099 case OMPD_target:
7100 case OMPD_target_simd:
7101 case OMPD_target_parallel:
7102 case OMPD_target_parallel_for:
7103 case OMPD_target_parallel_for_simd:
7104 case OMPD_target_teams_distribute:
7105 case OMPD_target_teams_distribute_simd:
7106 case OMPD_target_teams_distribute_parallel_for:
7107 case OMPD_target_teams_distribute_parallel_for_simd:
7108 case OMPD_teams_distribute_parallel_for:
7109 case OMPD_teams_distribute_parallel_for_simd:
7110 case OMPD_distribute_parallel_for:
7111 case OMPD_distribute_parallel_for_simd:
7112 case OMPD_task:
7113 case OMPD_taskloop:
7114 case OMPD_taskloop_simd:
7115 case OMPD_target_data:
7116 case OMPD_target_enter_data:
7117 case OMPD_target_exit_data:
7118 case OMPD_target_update:
7119 case OMPD_teams:
7120 case OMPD_teams_distribute:
7121 case OMPD_teams_distribute_simd:
7122 // Do not capture thread_limit-clause expressions.
7123 break;
7124 case OMPD_threadprivate:
7125 case OMPD_taskyield:
7126 case OMPD_barrier:
7127 case OMPD_taskwait:
7128 case OMPD_cancellation_point:
7129 case OMPD_flush:
7130 case OMPD_declare_reduction:
7131 case OMPD_declare_simd:
7132 case OMPD_declare_target:
7133 case OMPD_end_declare_target:
7134 case OMPD_simd:
7135 case OMPD_for:
7136 case OMPD_for_simd:
7137 case OMPD_sections:
7138 case OMPD_section:
7139 case OMPD_single:
7140 case OMPD_master:
7141 case OMPD_critical:
7142 case OMPD_taskgroup:
7143 case OMPD_distribute:
7144 case OMPD_ordered:
7145 case OMPD_atomic:
7146 case OMPD_distribute_simd:
7147 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7148 case OMPD_unknown:
7149 llvm_unreachable("Unknown OpenMP directive");
7150 }
7151 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007152 case OMPC_schedule:
7153 case OMPC_dist_schedule:
7154 case OMPC_firstprivate:
7155 case OMPC_lastprivate:
7156 case OMPC_reduction:
7157 case OMPC_linear:
7158 case OMPC_default:
7159 case OMPC_proc_bind:
7160 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007161 case OMPC_safelen:
7162 case OMPC_simdlen:
7163 case OMPC_collapse:
7164 case OMPC_private:
7165 case OMPC_shared:
7166 case OMPC_aligned:
7167 case OMPC_copyin:
7168 case OMPC_copyprivate:
7169 case OMPC_ordered:
7170 case OMPC_nowait:
7171 case OMPC_untied:
7172 case OMPC_mergeable:
7173 case OMPC_threadprivate:
7174 case OMPC_flush:
7175 case OMPC_read:
7176 case OMPC_write:
7177 case OMPC_update:
7178 case OMPC_capture:
7179 case OMPC_seq_cst:
7180 case OMPC_depend:
7181 case OMPC_device:
7182 case OMPC_threads:
7183 case OMPC_simd:
7184 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007185 case OMPC_priority:
7186 case OMPC_grainsize:
7187 case OMPC_nogroup:
7188 case OMPC_num_tasks:
7189 case OMPC_hint:
7190 case OMPC_defaultmap:
7191 case OMPC_unknown:
7192 case OMPC_uniform:
7193 case OMPC_to:
7194 case OMPC_from:
7195 case OMPC_use_device_ptr:
7196 case OMPC_is_device_ptr:
7197 llvm_unreachable("Unexpected OpenMP clause.");
7198 }
7199 return CaptureRegion;
7200}
7201
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007202OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7203 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007204 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007205 SourceLocation NameModifierLoc,
7206 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007207 SourceLocation EndLoc) {
7208 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007209 Stmt *HelperValStmt = nullptr;
7210 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007211 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7212 !Condition->isInstantiationDependent() &&
7213 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007214 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007215 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007216 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007217
Richard Smith03a4aa32016-06-23 19:02:52 +00007218 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007219
7220 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7221 CaptureRegion =
7222 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7223 if (CaptureRegion != OMPD_unknown) {
7224 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7225 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7226 HelperValStmt = buildPreInits(Context, Captures);
7227 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007228 }
7229
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007230 return new (Context)
7231 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7232 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007233}
7234
Alexey Bataev3778b602014-07-17 07:32:53 +00007235OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7236 SourceLocation StartLoc,
7237 SourceLocation LParenLoc,
7238 SourceLocation EndLoc) {
7239 Expr *ValExpr = Condition;
7240 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7241 !Condition->isInstantiationDependent() &&
7242 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007243 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007244 if (Val.isInvalid())
7245 return nullptr;
7246
Richard Smith03a4aa32016-06-23 19:02:52 +00007247 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007248 }
7249
7250 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7251}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007252ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7253 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007254 if (!Op)
7255 return ExprError();
7256
7257 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7258 public:
7259 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007260 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007261 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7262 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007263 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7264 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007265 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7266 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007267 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7268 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007269 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7270 QualType T,
7271 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007272 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7273 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007274 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7275 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007276 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007277 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007278 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007279 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7280 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007281 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7282 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007283 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7284 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007285 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007286 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007287 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007288 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7289 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007290 llvm_unreachable("conversion functions are permitted");
7291 }
7292 } ConvertDiagnoser;
7293 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7294}
7295
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007296static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007297 OpenMPClauseKind CKind,
7298 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007299 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7300 !ValExpr->isInstantiationDependent()) {
7301 SourceLocation Loc = ValExpr->getExprLoc();
7302 ExprResult Value =
7303 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7304 if (Value.isInvalid())
7305 return false;
7306
7307 ValExpr = Value.get();
7308 // The expression must evaluate to a non-negative integer value.
7309 llvm::APSInt Result;
7310 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007311 Result.isSigned() &&
7312 !((!StrictlyPositive && Result.isNonNegative()) ||
7313 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007314 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007315 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7316 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007317 return false;
7318 }
7319 }
7320 return true;
7321}
7322
Alexey Bataev568a8332014-03-06 06:15:19 +00007323OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7324 SourceLocation StartLoc,
7325 SourceLocation LParenLoc,
7326 SourceLocation EndLoc) {
7327 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007328 Stmt *HelperValStmt = nullptr;
7329 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007330
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007331 // OpenMP [2.5, Restrictions]
7332 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007333 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7334 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007335 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007336
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007337 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7338 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7339 if (CaptureRegion != OMPD_unknown) {
7340 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7341 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7342 HelperValStmt = buildPreInits(Context, Captures);
7343 }
7344
7345 return new (Context) OMPNumThreadsClause(
7346 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007347}
7348
Alexey Bataev62c87d22014-03-21 04:51:18 +00007349ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007350 OpenMPClauseKind CKind,
7351 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007352 if (!E)
7353 return ExprError();
7354 if (E->isValueDependent() || E->isTypeDependent() ||
7355 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007356 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007357 llvm::APSInt Result;
7358 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7359 if (ICE.isInvalid())
7360 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007361 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7362 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007363 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007364 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7365 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007366 return ExprError();
7367 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007368 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7369 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7370 << E->getSourceRange();
7371 return ExprError();
7372 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007373 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7374 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007375 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007376 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007377 return ICE;
7378}
7379
7380OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7381 SourceLocation LParenLoc,
7382 SourceLocation EndLoc) {
7383 // OpenMP [2.8.1, simd construct, Description]
7384 // The parameter of the safelen clause must be a constant
7385 // positive integer expression.
7386 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7387 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007388 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007389 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007390 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007391}
7392
Alexey Bataev66b15b52015-08-21 11:14:16 +00007393OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7394 SourceLocation LParenLoc,
7395 SourceLocation EndLoc) {
7396 // OpenMP [2.8.1, simd construct, Description]
7397 // The parameter of the simdlen clause must be a constant
7398 // positive integer expression.
7399 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7400 if (Simdlen.isInvalid())
7401 return nullptr;
7402 return new (Context)
7403 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7404}
7405
Alexander Musman64d33f12014-06-04 07:53:32 +00007406OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7407 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007408 SourceLocation LParenLoc,
7409 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007410 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007411 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007412 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007413 // The parameter of the collapse clause must be a constant
7414 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007415 ExprResult NumForLoopsResult =
7416 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7417 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007418 return nullptr;
7419 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007420 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007421}
7422
Alexey Bataev10e775f2015-07-30 11:36:16 +00007423OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7424 SourceLocation EndLoc,
7425 SourceLocation LParenLoc,
7426 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007427 // OpenMP [2.7.1, loop construct, Description]
7428 // OpenMP [2.8.1, simd construct, Description]
7429 // OpenMP [2.9.6, distribute construct, Description]
7430 // The parameter of the ordered clause must be a constant
7431 // positive integer expression if any.
7432 if (NumForLoops && LParenLoc.isValid()) {
7433 ExprResult NumForLoopsResult =
7434 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7435 if (NumForLoopsResult.isInvalid())
7436 return nullptr;
7437 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007438 } else
7439 NumForLoops = nullptr;
7440 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007441 return new (Context)
7442 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7443}
7444
Alexey Bataeved09d242014-05-28 05:53:51 +00007445OMPClause *Sema::ActOnOpenMPSimpleClause(
7446 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7447 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007448 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007449 switch (Kind) {
7450 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007451 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007452 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7453 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007454 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007455 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007456 Res = ActOnOpenMPProcBindClause(
7457 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7458 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007459 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007460 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007461 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007462 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007463 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007464 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007465 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007466 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007467 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007468 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007469 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007470 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007471 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007472 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007473 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007474 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007475 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007476 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007477 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007478 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007479 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007480 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007481 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007482 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007483 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007484 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007485 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007486 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007487 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007488 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007489 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007490 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007491 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007492 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007493 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007494 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007495 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007496 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007497 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007498 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007499 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007500 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007501 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007502 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007503 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007504 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007505 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007506 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007507 llvm_unreachable("Clause is not allowed.");
7508 }
7509 return Res;
7510}
7511
Alexey Bataev6402bca2015-12-28 07:25:51 +00007512static std::string
7513getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7514 ArrayRef<unsigned> Exclude = llvm::None) {
7515 std::string Values;
7516 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7517 unsigned Skipped = Exclude.size();
7518 auto S = Exclude.begin(), E = Exclude.end();
7519 for (unsigned i = First; i < Last; ++i) {
7520 if (std::find(S, E, i) != E) {
7521 --Skipped;
7522 continue;
7523 }
7524 Values += "'";
7525 Values += getOpenMPSimpleClauseTypeName(K, i);
7526 Values += "'";
7527 if (i == Bound - Skipped)
7528 Values += " or ";
7529 else if (i != Bound + 1 - Skipped)
7530 Values += ", ";
7531 }
7532 return Values;
7533}
7534
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007535OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7536 SourceLocation KindKwLoc,
7537 SourceLocation StartLoc,
7538 SourceLocation LParenLoc,
7539 SourceLocation EndLoc) {
7540 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007541 static_assert(OMPC_DEFAULT_unknown > 0,
7542 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007543 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007544 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7545 /*Last=*/OMPC_DEFAULT_unknown)
7546 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007547 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007548 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007549 switch (Kind) {
7550 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007551 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007552 break;
7553 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007554 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007555 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007556 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007557 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007558 break;
7559 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007560 return new (Context)
7561 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007562}
7563
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007564OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7565 SourceLocation KindKwLoc,
7566 SourceLocation StartLoc,
7567 SourceLocation LParenLoc,
7568 SourceLocation EndLoc) {
7569 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007570 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007571 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7572 /*Last=*/OMPC_PROC_BIND_unknown)
7573 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007574 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007575 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007576 return new (Context)
7577 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007578}
7579
Alexey Bataev56dafe82014-06-20 07:16:17 +00007580OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007581 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007582 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007583 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007584 SourceLocation EndLoc) {
7585 OMPClause *Res = nullptr;
7586 switch (Kind) {
7587 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007588 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7589 assert(Argument.size() == NumberOfElements &&
7590 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007591 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007592 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7593 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7594 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7595 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7596 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007597 break;
7598 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007599 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7600 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7601 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7602 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007603 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007604 case OMPC_dist_schedule:
7605 Res = ActOnOpenMPDistScheduleClause(
7606 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7607 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7608 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007609 case OMPC_defaultmap:
7610 enum { Modifier, DefaultmapKind };
7611 Res = ActOnOpenMPDefaultmapClause(
7612 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7613 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007614 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7615 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007616 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007617 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007618 case OMPC_num_threads:
7619 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007620 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007621 case OMPC_collapse:
7622 case OMPC_default:
7623 case OMPC_proc_bind:
7624 case OMPC_private:
7625 case OMPC_firstprivate:
7626 case OMPC_lastprivate:
7627 case OMPC_shared:
7628 case OMPC_reduction:
7629 case OMPC_linear:
7630 case OMPC_aligned:
7631 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007632 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007633 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007634 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007635 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007636 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007637 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007638 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007639 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007640 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007641 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007642 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007643 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007644 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007645 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007646 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007647 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007648 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007649 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007650 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007651 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007652 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007653 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007654 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007655 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007656 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007657 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007658 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007659 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007660 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007661 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007662 llvm_unreachable("Clause is not allowed.");
7663 }
7664 return Res;
7665}
7666
Alexey Bataev6402bca2015-12-28 07:25:51 +00007667static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7668 OpenMPScheduleClauseModifier M2,
7669 SourceLocation M1Loc, SourceLocation M2Loc) {
7670 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7671 SmallVector<unsigned, 2> Excluded;
7672 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7673 Excluded.push_back(M2);
7674 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7675 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7676 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7677 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7678 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7679 << getListOfPossibleValues(OMPC_schedule,
7680 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7681 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7682 Excluded)
7683 << getOpenMPClauseName(OMPC_schedule);
7684 return true;
7685 }
7686 return false;
7687}
7688
Alexey Bataev56dafe82014-06-20 07:16:17 +00007689OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007690 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007691 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007692 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7693 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7694 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7695 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7696 return nullptr;
7697 // OpenMP, 2.7.1, Loop Construct, Restrictions
7698 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7699 // but not both.
7700 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7701 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7702 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7703 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7704 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7705 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7706 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7707 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7708 return nullptr;
7709 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007710 if (Kind == OMPC_SCHEDULE_unknown) {
7711 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007712 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7713 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7714 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7715 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7716 Exclude);
7717 } else {
7718 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7719 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007720 }
7721 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7722 << Values << getOpenMPClauseName(OMPC_schedule);
7723 return nullptr;
7724 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007725 // OpenMP, 2.7.1, Loop Construct, Restrictions
7726 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7727 // schedule(guided).
7728 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7729 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7730 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7731 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7732 diag::err_omp_schedule_nonmonotonic_static);
7733 return nullptr;
7734 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007735 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007736 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007737 if (ChunkSize) {
7738 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7739 !ChunkSize->isInstantiationDependent() &&
7740 !ChunkSize->containsUnexpandedParameterPack()) {
7741 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7742 ExprResult Val =
7743 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7744 if (Val.isInvalid())
7745 return nullptr;
7746
7747 ValExpr = Val.get();
7748
7749 // OpenMP [2.7.1, Restrictions]
7750 // chunk_size must be a loop invariant integer expression with a positive
7751 // value.
7752 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007753 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7754 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7755 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007756 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007757 return nullptr;
7758 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007759 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7760 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007761 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7762 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7763 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007764 }
7765 }
7766 }
7767
Alexey Bataev6402bca2015-12-28 07:25:51 +00007768 return new (Context)
7769 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007770 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007771}
7772
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007773OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7774 SourceLocation StartLoc,
7775 SourceLocation EndLoc) {
7776 OMPClause *Res = nullptr;
7777 switch (Kind) {
7778 case OMPC_ordered:
7779 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7780 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007781 case OMPC_nowait:
7782 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7783 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007784 case OMPC_untied:
7785 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7786 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007787 case OMPC_mergeable:
7788 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7789 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007790 case OMPC_read:
7791 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7792 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007793 case OMPC_write:
7794 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7795 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007796 case OMPC_update:
7797 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7798 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007799 case OMPC_capture:
7800 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7801 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007802 case OMPC_seq_cst:
7803 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7804 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007805 case OMPC_threads:
7806 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7807 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007808 case OMPC_simd:
7809 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7810 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007811 case OMPC_nogroup:
7812 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7813 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007814 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007815 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007816 case OMPC_num_threads:
7817 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007818 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007819 case OMPC_collapse:
7820 case OMPC_schedule:
7821 case OMPC_private:
7822 case OMPC_firstprivate:
7823 case OMPC_lastprivate:
7824 case OMPC_shared:
7825 case OMPC_reduction:
7826 case OMPC_linear:
7827 case OMPC_aligned:
7828 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007829 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007830 case OMPC_default:
7831 case OMPC_proc_bind:
7832 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007833 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007834 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007835 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007836 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007837 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007838 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007839 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007840 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007841 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007842 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007843 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007844 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007845 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007846 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007847 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007848 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007849 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007850 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007851 llvm_unreachable("Clause is not allowed.");
7852 }
7853 return Res;
7854}
7855
Alexey Bataev236070f2014-06-20 11:19:47 +00007856OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7857 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007858 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007859 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7860}
7861
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007862OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7863 SourceLocation EndLoc) {
7864 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7865}
7866
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007867OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7868 SourceLocation EndLoc) {
7869 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7870}
7871
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007872OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7873 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007874 return new (Context) OMPReadClause(StartLoc, EndLoc);
7875}
7876
Alexey Bataevdea47612014-07-23 07:46:59 +00007877OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7878 SourceLocation EndLoc) {
7879 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7880}
7881
Alexey Bataev67a4f222014-07-23 10:25:33 +00007882OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7883 SourceLocation EndLoc) {
7884 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7885}
7886
Alexey Bataev459dec02014-07-24 06:46:57 +00007887OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7888 SourceLocation EndLoc) {
7889 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7890}
7891
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007892OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7893 SourceLocation EndLoc) {
7894 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7895}
7896
Alexey Bataev346265e2015-09-25 10:37:12 +00007897OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7898 SourceLocation EndLoc) {
7899 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7900}
7901
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007902OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7903 SourceLocation EndLoc) {
7904 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7905}
7906
Alexey Bataevb825de12015-12-07 10:51:44 +00007907OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7908 SourceLocation EndLoc) {
7909 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7910}
7911
Alexey Bataevc5e02582014-06-16 07:08:35 +00007912OMPClause *Sema::ActOnOpenMPVarListClause(
7913 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7914 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7915 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007916 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007917 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7918 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7919 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007920 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007921 switch (Kind) {
7922 case OMPC_private:
7923 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7924 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007925 case OMPC_firstprivate:
7926 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7927 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007928 case OMPC_lastprivate:
7929 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7930 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007931 case OMPC_shared:
7932 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7933 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007934 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007935 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7936 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007937 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007938 case OMPC_linear:
7939 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007940 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007941 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007942 case OMPC_aligned:
7943 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7944 ColonLoc, EndLoc);
7945 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007946 case OMPC_copyin:
7947 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7948 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007949 case OMPC_copyprivate:
7950 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7951 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007952 case OMPC_flush:
7953 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7954 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007955 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007956 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007957 StartLoc, LParenLoc, EndLoc);
7958 break;
7959 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007960 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7961 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7962 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007963 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007964 case OMPC_to:
7965 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7966 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007967 case OMPC_from:
7968 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7969 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007970 case OMPC_use_device_ptr:
7971 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7972 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007973 case OMPC_is_device_ptr:
7974 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7975 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007976 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007977 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007978 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007979 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007980 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007981 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007982 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007983 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007984 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007985 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007986 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007987 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007988 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007989 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007990 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007991 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007992 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007993 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007994 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007995 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007996 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007997 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007998 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007999 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008000 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008001 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008002 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008003 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008004 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008005 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008006 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008007 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008008 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008009 llvm_unreachable("Clause is not allowed.");
8010 }
8011 return Res;
8012}
8013
Alexey Bataev90c228f2016-02-08 09:29:13 +00008014ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008015 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008016 ExprResult Res = BuildDeclRefExpr(
8017 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8018 if (!Res.isUsable())
8019 return ExprError();
8020 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8021 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8022 if (!Res.isUsable())
8023 return ExprError();
8024 }
8025 if (VK != VK_LValue && Res.get()->isGLValue()) {
8026 Res = DefaultLvalueConversion(Res.get());
8027 if (!Res.isUsable())
8028 return ExprError();
8029 }
8030 return Res;
8031}
8032
Alexey Bataev60da77e2016-02-29 05:54:20 +00008033static std::pair<ValueDecl *, bool>
8034getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8035 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008036 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8037 RefExpr->containsUnexpandedParameterPack())
8038 return std::make_pair(nullptr, true);
8039
Alexey Bataevd985eda2016-02-10 11:29:16 +00008040 // OpenMP [3.1, C/C++]
8041 // A list item is a variable name.
8042 // OpenMP [2.9.3.3, Restrictions, p.1]
8043 // A variable that is part of another variable (as an array or
8044 // structure element) cannot appear in a private clause.
8045 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008046 enum {
8047 NoArrayExpr = -1,
8048 ArraySubscript = 0,
8049 OMPArraySection = 1
8050 } IsArrayExpr = NoArrayExpr;
8051 if (AllowArraySection) {
8052 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8053 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8054 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8055 Base = TempASE->getBase()->IgnoreParenImpCasts();
8056 RefExpr = Base;
8057 IsArrayExpr = ArraySubscript;
8058 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8059 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8060 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8061 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8062 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8063 Base = TempASE->getBase()->IgnoreParenImpCasts();
8064 RefExpr = Base;
8065 IsArrayExpr = OMPArraySection;
8066 }
8067 }
8068 ELoc = RefExpr->getExprLoc();
8069 ERange = RefExpr->getSourceRange();
8070 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008071 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8072 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8073 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8074 (S.getCurrentThisType().isNull() || !ME ||
8075 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8076 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008077 if (IsArrayExpr != NoArrayExpr)
8078 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8079 << ERange;
8080 else {
8081 S.Diag(ELoc,
8082 AllowArraySection
8083 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8084 : diag::err_omp_expected_var_name_member_expr)
8085 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8086 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008087 return std::make_pair(nullptr, false);
8088 }
8089 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
8090}
8091
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008092OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8093 SourceLocation StartLoc,
8094 SourceLocation LParenLoc,
8095 SourceLocation EndLoc) {
8096 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008097 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008098 for (auto &RefExpr : VarList) {
8099 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008100 SourceLocation ELoc;
8101 SourceRange ERange;
8102 Expr *SimpleRefExpr = RefExpr;
8103 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008104 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008105 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008106 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008107 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008108 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008109 ValueDecl *D = Res.first;
8110 if (!D)
8111 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008112
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008113 QualType Type = D->getType();
8114 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008115
8116 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8117 // A variable that appears in a private clause must not have an incomplete
8118 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008119 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008120 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008121 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008122
Alexey Bataev758e55e2013-09-06 18:03:48 +00008123 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8124 // in a Construct]
8125 // Variables with the predetermined data-sharing attributes may not be
8126 // listed in data-sharing attributes clauses, except for the cases
8127 // listed below. For these exceptions only, listing a predetermined
8128 // variable in a data-sharing attribute clause is allowed and overrides
8129 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008130 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008131 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008132 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8133 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008134 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008135 continue;
8136 }
8137
Kelvin Libf594a52016-12-17 05:48:59 +00008138 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008139 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008140 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008141 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008142 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8143 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008144 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008145 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008146 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008147 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008148 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008149 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008150 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008151 continue;
8152 }
8153
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008154 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8155 // A list item cannot appear in both a map clause and a data-sharing
8156 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008157 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008158 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008159 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008160 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008161 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008162 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008163 CurrDir == OMPD_target_parallel_for_simd ||
8164 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008165 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008166 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008167 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008168 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8169 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8170 ConflictKind = WhereFoundClauseKind;
8171 return true;
8172 })) {
8173 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008174 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008175 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008176 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008177 ReportOriginalDSA(*this, DSAStack, D, DVar);
8178 continue;
8179 }
8180 }
8181
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008182 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8183 // A variable of class type (or array thereof) that appears in a private
8184 // clause requires an accessible, unambiguous default constructor for the
8185 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008186 // Generate helper private variable and initialize it with the default
8187 // value. The address of the original variable is replaced by the address of
8188 // the new private variable in CodeGen. This new variable is not added to
8189 // IdResolver, so the code in the OpenMP region uses original variable for
8190 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008191 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008192 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8193 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008194 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008195 if (VDPrivate->isInvalidDecl())
8196 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008197 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008198 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008199
Alexey Bataev90c228f2016-02-08 09:29:13 +00008200 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008201 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008202 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008203 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008204 Vars.push_back((VD || CurContext->isDependentContext())
8205 ? RefExpr->IgnoreParens()
8206 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008207 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008208 }
8209
Alexey Bataeved09d242014-05-28 05:53:51 +00008210 if (Vars.empty())
8211 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008212
Alexey Bataev03b340a2014-10-21 03:16:40 +00008213 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8214 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008215}
8216
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008217namespace {
8218class DiagsUninitializedSeveretyRAII {
8219private:
8220 DiagnosticsEngine &Diags;
8221 SourceLocation SavedLoc;
8222 bool IsIgnored;
8223
8224public:
8225 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8226 bool IsIgnored)
8227 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8228 if (!IsIgnored) {
8229 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8230 /*Map*/ diag::Severity::Ignored, Loc);
8231 }
8232 }
8233 ~DiagsUninitializedSeveretyRAII() {
8234 if (!IsIgnored)
8235 Diags.popMappings(SavedLoc);
8236 }
8237};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008238}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008239
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008240OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8241 SourceLocation StartLoc,
8242 SourceLocation LParenLoc,
8243 SourceLocation EndLoc) {
8244 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008245 SmallVector<Expr *, 8> PrivateCopies;
8246 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008247 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008248 bool IsImplicitClause =
8249 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8250 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8251
Alexey Bataeved09d242014-05-28 05:53:51 +00008252 for (auto &RefExpr : VarList) {
8253 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008254 SourceLocation ELoc;
8255 SourceRange ERange;
8256 Expr *SimpleRefExpr = RefExpr;
8257 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008258 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008259 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008260 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008261 PrivateCopies.push_back(nullptr);
8262 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008263 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008264 ValueDecl *D = Res.first;
8265 if (!D)
8266 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008267
Alexey Bataev60da77e2016-02-29 05:54:20 +00008268 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008269 QualType Type = D->getType();
8270 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008271
8272 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8273 // A variable that appears in a private clause must not have an incomplete
8274 // type or a reference type.
8275 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008276 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008277 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008278 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008279
8280 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8281 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008282 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008283 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008284 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008285
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008286 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008287 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008288 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008289 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008290 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008291 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008292 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8293 // A list item that specifies a given variable may not appear in more
8294 // than one clause on the same directive, except that a variable may be
8295 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008296 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00008297 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008298 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008299 << getOpenMPClauseName(DVar.CKind)
8300 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008301 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008302 continue;
8303 }
8304
8305 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8306 // in a Construct]
8307 // Variables with the predetermined data-sharing attributes may not be
8308 // listed in data-sharing attributes clauses, except for the cases
8309 // listed below. For these exceptions only, listing a predetermined
8310 // variable in a data-sharing attribute clause is allowed and overrides
8311 // the variable's predetermined data-sharing attributes.
8312 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8313 // in a Construct, C/C++, p.2]
8314 // Variables with const-qualified type having no mutable member may be
8315 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008316 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008317 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8318 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008319 << getOpenMPClauseName(DVar.CKind)
8320 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008321 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008322 continue;
8323 }
8324
Alexey Bataevf29276e2014-06-18 04:14:57 +00008325 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008326 // OpenMP [2.9.3.4, Restrictions, p.2]
8327 // A list item that is private within a parallel region must not appear
8328 // in a firstprivate clause on a worksharing construct if any of the
8329 // worksharing regions arising from the worksharing construct ever bind
8330 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008331 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008332 !isOpenMPParallelDirective(CurrDir) &&
8333 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008334 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008335 if (DVar.CKind != OMPC_shared &&
8336 (isOpenMPParallelDirective(DVar.DKind) ||
8337 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008338 Diag(ELoc, diag::err_omp_required_access)
8339 << getOpenMPClauseName(OMPC_firstprivate)
8340 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008341 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008342 continue;
8343 }
8344 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008345 // OpenMP [2.9.3.4, Restrictions, p.3]
8346 // A list item that appears in a reduction clause of a parallel construct
8347 // must not appear in a firstprivate clause on a worksharing or task
8348 // construct if any of the worksharing or task regions arising from the
8349 // worksharing or task construct ever bind to any of the parallel regions
8350 // arising from the parallel construct.
8351 // OpenMP [2.9.3.4, Restrictions, p.4]
8352 // A list item that appears in a reduction clause in worksharing
8353 // construct must not appear in a firstprivate clause in a task construct
8354 // encountered during execution of any of the worksharing regions arising
8355 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008356 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008357 DVar = DSAStack->hasInnermostDSA(
8358 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8359 [](OpenMPDirectiveKind K) -> bool {
8360 return isOpenMPParallelDirective(K) ||
8361 isOpenMPWorksharingDirective(K);
8362 },
8363 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008364 if (DVar.CKind == OMPC_reduction &&
8365 (isOpenMPParallelDirective(DVar.DKind) ||
8366 isOpenMPWorksharingDirective(DVar.DKind))) {
8367 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8368 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008369 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008370 continue;
8371 }
8372 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008373
8374 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8375 // A list item that is private within a teams region must not appear in a
8376 // firstprivate clause on a distribute construct if any of the distribute
8377 // regions arising from the distribute construct ever bind to any of the
8378 // teams regions arising from the teams construct.
8379 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8380 // A list item that appears in a reduction clause of a teams construct
8381 // must not appear in a firstprivate clause on a distribute construct if
8382 // any of the distribute regions arising from the distribute construct
8383 // ever bind to any of the teams regions arising from the teams construct.
8384 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8385 // A list item may appear in a firstprivate or lastprivate clause but not
8386 // both.
8387 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008388 DVar = DSAStack->hasInnermostDSA(
8389 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8390 [](OpenMPDirectiveKind K) -> bool {
8391 return isOpenMPTeamsDirective(K);
8392 },
8393 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008394 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8395 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008396 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008397 continue;
8398 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008399 DVar = DSAStack->hasInnermostDSA(
8400 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8401 [](OpenMPDirectiveKind K) -> bool {
8402 return isOpenMPTeamsDirective(K);
8403 },
8404 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008405 if (DVar.CKind == OMPC_reduction &&
8406 isOpenMPTeamsDirective(DVar.DKind)) {
8407 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008408 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008409 continue;
8410 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008411 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008412 if (DVar.CKind == OMPC_lastprivate) {
8413 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008414 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008415 continue;
8416 }
8417 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008418 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8419 // A list item cannot appear in both a map clause and a data-sharing
8420 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008421 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008422 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008423 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008424 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008425 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008426 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008427 CurrDir == OMPD_target_parallel_for_simd ||
8428 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008429 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008430 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008431 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008432 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8433 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8434 ConflictKind = WhereFoundClauseKind;
8435 return true;
8436 })) {
8437 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008438 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008439 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008440 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8441 ReportOriginalDSA(*this, DSAStack, D, DVar);
8442 continue;
8443 }
8444 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008445 }
8446
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008447 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008448 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008449 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008450 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8451 << getOpenMPClauseName(OMPC_firstprivate) << Type
8452 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8453 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008454 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008455 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008456 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008457 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008458 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008459 continue;
8460 }
8461
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008462 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008463 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8464 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008465 // Generate helper private variable and initialize it with the value of the
8466 // original variable. The address of the original variable is replaced by
8467 // the address of the new private variable in the CodeGen. This new variable
8468 // is not added to IdResolver, so the code in the OpenMP region uses
8469 // original variable for proper diagnostics and variable capturing.
8470 Expr *VDInitRefExpr = nullptr;
8471 // For arrays generate initializer for single element and replace it by the
8472 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008473 if (Type->isArrayType()) {
8474 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008475 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008476 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008477 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008478 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008479 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008480 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008481 InitializedEntity Entity =
8482 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008483 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8484
8485 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8486 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8487 if (Result.isInvalid())
8488 VDPrivate->setInvalidDecl();
8489 else
8490 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008491 // Remove temp variable declaration.
8492 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008493 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008494 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8495 ".firstprivate.temp");
8496 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8497 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008498 AddInitializerToDecl(VDPrivate,
8499 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008500 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008501 }
8502 if (VDPrivate->isInvalidDecl()) {
8503 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008504 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008505 diag::note_omp_task_predetermined_firstprivate_here);
8506 }
8507 continue;
8508 }
8509 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008510 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008511 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8512 RefExpr->getExprLoc());
8513 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008514 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008515 if (TopDVar.CKind == OMPC_lastprivate)
8516 Ref = TopDVar.PrivateCopy;
8517 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008518 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008519 if (!IsOpenMPCapturedDecl(D))
8520 ExprCaptures.push_back(Ref->getDecl());
8521 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008522 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008523 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008524 Vars.push_back((VD || CurContext->isDependentContext())
8525 ? RefExpr->IgnoreParens()
8526 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008527 PrivateCopies.push_back(VDPrivateRefExpr);
8528 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008529 }
8530
Alexey Bataeved09d242014-05-28 05:53:51 +00008531 if (Vars.empty())
8532 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008533
8534 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008535 Vars, PrivateCopies, Inits,
8536 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008537}
8538
Alexander Musman1bb328c2014-06-04 13:06:39 +00008539OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8540 SourceLocation StartLoc,
8541 SourceLocation LParenLoc,
8542 SourceLocation EndLoc) {
8543 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008544 SmallVector<Expr *, 8> SrcExprs;
8545 SmallVector<Expr *, 8> DstExprs;
8546 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008547 SmallVector<Decl *, 4> ExprCaptures;
8548 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008549 for (auto &RefExpr : VarList) {
8550 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008551 SourceLocation ELoc;
8552 SourceRange ERange;
8553 Expr *SimpleRefExpr = RefExpr;
8554 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008555 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008556 // It will be analyzed later.
8557 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008558 SrcExprs.push_back(nullptr);
8559 DstExprs.push_back(nullptr);
8560 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008561 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008562 ValueDecl *D = Res.first;
8563 if (!D)
8564 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008565
Alexey Bataev74caaf22016-02-20 04:09:36 +00008566 QualType Type = D->getType();
8567 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008568
8569 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8570 // A variable that appears in a lastprivate clause must not have an
8571 // incomplete type or a reference type.
8572 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008573 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008574 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008575 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008576
8577 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8578 // in a Construct]
8579 // Variables with the predetermined data-sharing attributes may not be
8580 // listed in data-sharing attributes clauses, except for the cases
8581 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008582 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008583 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8584 DVar.CKind != OMPC_firstprivate &&
8585 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8586 Diag(ELoc, diag::err_omp_wrong_dsa)
8587 << getOpenMPClauseName(DVar.CKind)
8588 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008589 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008590 continue;
8591 }
8592
Alexey Bataevf29276e2014-06-18 04:14:57 +00008593 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8594 // OpenMP [2.14.3.5, Restrictions, p.2]
8595 // A list item that is private within a parallel region, or that appears in
8596 // the reduction clause of a parallel construct, must not appear in a
8597 // lastprivate clause on a worksharing construct if any of the corresponding
8598 // worksharing regions ever binds to any of the corresponding parallel
8599 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008600 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008601 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008602 !isOpenMPParallelDirective(CurrDir) &&
8603 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008604 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008605 if (DVar.CKind != OMPC_shared) {
8606 Diag(ELoc, diag::err_omp_required_access)
8607 << getOpenMPClauseName(OMPC_lastprivate)
8608 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008609 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008610 continue;
8611 }
8612 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008613
8614 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8615 // A list item may appear in a firstprivate or lastprivate clause but not
8616 // both.
8617 if (CurrDir == OMPD_distribute) {
8618 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8619 if (DVar.CKind == OMPC_firstprivate) {
8620 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8621 ReportOriginalDSA(*this, DSAStack, D, DVar);
8622 continue;
8623 }
8624 }
8625
Alexander Musman1bb328c2014-06-04 13:06:39 +00008626 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008627 // A variable of class type (or array thereof) that appears in a
8628 // lastprivate clause requires an accessible, unambiguous default
8629 // constructor for the class type, unless the list item is also specified
8630 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008631 // A variable of class type (or array thereof) that appears in a
8632 // lastprivate clause requires an accessible, unambiguous copy assignment
8633 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008634 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008635 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008636 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008637 D->hasAttrs() ? &D->getAttrs() : nullptr);
8638 auto *PseudoSrcExpr =
8639 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008640 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008641 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008642 D->hasAttrs() ? &D->getAttrs() : nullptr);
8643 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008644 // For arrays generate assignment operation for single element and replace
8645 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008646 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008647 PseudoDstExpr, PseudoSrcExpr);
8648 if (AssignmentOp.isInvalid())
8649 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008650 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008651 /*DiscardedValue=*/true);
8652 if (AssignmentOp.isInvalid())
8653 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008654
Alexey Bataev74caaf22016-02-20 04:09:36 +00008655 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008656 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008657 if (TopDVar.CKind == OMPC_firstprivate)
8658 Ref = TopDVar.PrivateCopy;
8659 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008660 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008661 if (!IsOpenMPCapturedDecl(D))
8662 ExprCaptures.push_back(Ref->getDecl());
8663 }
8664 if (TopDVar.CKind == OMPC_firstprivate ||
8665 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008666 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008667 ExprResult RefRes = DefaultLvalueConversion(Ref);
8668 if (!RefRes.isUsable())
8669 continue;
8670 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008671 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8672 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008673 if (!PostUpdateRes.isUsable())
8674 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008675 ExprPostUpdates.push_back(
8676 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008677 }
8678 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008679 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008680 Vars.push_back((VD || CurContext->isDependentContext())
8681 ? RefExpr->IgnoreParens()
8682 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008683 SrcExprs.push_back(PseudoSrcExpr);
8684 DstExprs.push_back(PseudoDstExpr);
8685 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008686 }
8687
8688 if (Vars.empty())
8689 return nullptr;
8690
8691 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008692 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008693 buildPreInits(Context, ExprCaptures),
8694 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008695}
8696
Alexey Bataev758e55e2013-09-06 18:03:48 +00008697OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8698 SourceLocation StartLoc,
8699 SourceLocation LParenLoc,
8700 SourceLocation EndLoc) {
8701 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008702 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008703 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008704 SourceLocation ELoc;
8705 SourceRange ERange;
8706 Expr *SimpleRefExpr = RefExpr;
8707 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008708 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008709 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008710 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008711 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008712 ValueDecl *D = Res.first;
8713 if (!D)
8714 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008715
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008716 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008717 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8718 // in a Construct]
8719 // Variables with the predetermined data-sharing attributes may not be
8720 // listed in data-sharing attributes clauses, except for the cases
8721 // listed below. For these exceptions only, listing a predetermined
8722 // variable in a data-sharing attribute clause is allowed and overrides
8723 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008724 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008725 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8726 DVar.RefExpr) {
8727 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8728 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008729 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008730 continue;
8731 }
8732
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008733 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008734 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008735 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008736 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008737 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8738 ? RefExpr->IgnoreParens()
8739 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008740 }
8741
Alexey Bataeved09d242014-05-28 05:53:51 +00008742 if (Vars.empty())
8743 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008744
8745 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8746}
8747
Alexey Bataevc5e02582014-06-16 07:08:35 +00008748namespace {
8749class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8750 DSAStackTy *Stack;
8751
8752public:
8753 bool VisitDeclRefExpr(DeclRefExpr *E) {
8754 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008755 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008756 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8757 return false;
8758 if (DVar.CKind != OMPC_unknown)
8759 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008760 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8761 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8762 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008763 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008764 return true;
8765 return false;
8766 }
8767 return false;
8768 }
8769 bool VisitStmt(Stmt *S) {
8770 for (auto Child : S->children()) {
8771 if (Child && Visit(Child))
8772 return true;
8773 }
8774 return false;
8775 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008776 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008777};
Alexey Bataev23b69422014-06-18 07:08:49 +00008778} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008779
Alexey Bataev60da77e2016-02-29 05:54:20 +00008780namespace {
8781// Transform MemberExpression for specified FieldDecl of current class to
8782// DeclRefExpr to specified OMPCapturedExprDecl.
8783class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8784 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8785 ValueDecl *Field;
8786 DeclRefExpr *CapturedExpr;
8787
8788public:
8789 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8790 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8791
8792 ExprResult TransformMemberExpr(MemberExpr *E) {
8793 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8794 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008795 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008796 return CapturedExpr;
8797 }
8798 return BaseTransform::TransformMemberExpr(E);
8799 }
8800 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8801};
8802} // namespace
8803
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008804template <typename T>
8805static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8806 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8807 for (auto &Set : Lookups) {
8808 for (auto *D : Set) {
8809 if (auto Res = Gen(cast<ValueDecl>(D)))
8810 return Res;
8811 }
8812 }
8813 return T();
8814}
8815
8816static ExprResult
8817buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8818 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8819 const DeclarationNameInfo &ReductionId, QualType Ty,
8820 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8821 if (ReductionIdScopeSpec.isInvalid())
8822 return ExprError();
8823 SmallVector<UnresolvedSet<8>, 4> Lookups;
8824 if (S) {
8825 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8826 Lookup.suppressDiagnostics();
8827 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8828 auto *D = Lookup.getRepresentativeDecl();
8829 do {
8830 S = S->getParent();
8831 } while (S && !S->isDeclScope(D));
8832 if (S)
8833 S = S->getParent();
8834 Lookups.push_back(UnresolvedSet<8>());
8835 Lookups.back().append(Lookup.begin(), Lookup.end());
8836 Lookup.clear();
8837 }
8838 } else if (auto *ULE =
8839 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8840 Lookups.push_back(UnresolvedSet<8>());
8841 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008842 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008843 if (D == PrevD)
8844 Lookups.push_back(UnresolvedSet<8>());
8845 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8846 Lookups.back().addDecl(DRD);
8847 PrevD = D;
8848 }
8849 }
8850 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8851 Ty->containsUnexpandedParameterPack() ||
8852 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8853 return !D->isInvalidDecl() &&
8854 (D->getType()->isDependentType() ||
8855 D->getType()->isInstantiationDependentType() ||
8856 D->getType()->containsUnexpandedParameterPack());
8857 })) {
8858 UnresolvedSet<8> ResSet;
8859 for (auto &Set : Lookups) {
8860 ResSet.append(Set.begin(), Set.end());
8861 // The last item marks the end of all declarations at the specified scope.
8862 ResSet.addDecl(Set[Set.size() - 1]);
8863 }
8864 return UnresolvedLookupExpr::Create(
8865 SemaRef.Context, /*NamingClass=*/nullptr,
8866 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8867 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8868 }
8869 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8870 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8871 if (!D->isInvalidDecl() &&
8872 SemaRef.Context.hasSameType(D->getType(), Ty))
8873 return D;
8874 return nullptr;
8875 }))
8876 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8877 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8878 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8879 if (!D->isInvalidDecl() &&
8880 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8881 !Ty.isMoreQualifiedThan(D->getType()))
8882 return D;
8883 return nullptr;
8884 })) {
8885 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8886 /*DetectVirtual=*/false);
8887 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8888 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8889 VD->getType().getUnqualifiedType()))) {
8890 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8891 /*DiagID=*/0) !=
8892 Sema::AR_inaccessible) {
8893 SemaRef.BuildBasePathArray(Paths, BasePath);
8894 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8895 }
8896 }
8897 }
8898 }
8899 if (ReductionIdScopeSpec.isSet()) {
8900 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8901 return ExprError();
8902 }
8903 return ExprEmpty();
8904}
8905
Alexey Bataevc5e02582014-06-16 07:08:35 +00008906OMPClause *Sema::ActOnOpenMPReductionClause(
8907 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8908 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008909 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8910 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008911 auto DN = ReductionId.getName();
8912 auto OOK = DN.getCXXOverloadedOperator();
8913 BinaryOperatorKind BOK = BO_Comma;
8914
8915 // OpenMP [2.14.3.6, reduction clause]
8916 // C
8917 // reduction-identifier is either an identifier or one of the following
8918 // operators: +, -, *, &, |, ^, && and ||
8919 // C++
8920 // reduction-identifier is either an id-expression or one of the following
8921 // operators: +, -, *, &, |, ^, && and ||
8922 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8923 switch (OOK) {
8924 case OO_Plus:
8925 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008926 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008927 break;
8928 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008929 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008930 break;
8931 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008932 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008933 break;
8934 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008935 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008936 break;
8937 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008938 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008939 break;
8940 case OO_AmpAmp:
8941 BOK = BO_LAnd;
8942 break;
8943 case OO_PipePipe:
8944 BOK = BO_LOr;
8945 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008946 case OO_New:
8947 case OO_Delete:
8948 case OO_Array_New:
8949 case OO_Array_Delete:
8950 case OO_Slash:
8951 case OO_Percent:
8952 case OO_Tilde:
8953 case OO_Exclaim:
8954 case OO_Equal:
8955 case OO_Less:
8956 case OO_Greater:
8957 case OO_LessEqual:
8958 case OO_GreaterEqual:
8959 case OO_PlusEqual:
8960 case OO_MinusEqual:
8961 case OO_StarEqual:
8962 case OO_SlashEqual:
8963 case OO_PercentEqual:
8964 case OO_CaretEqual:
8965 case OO_AmpEqual:
8966 case OO_PipeEqual:
8967 case OO_LessLess:
8968 case OO_GreaterGreater:
8969 case OO_LessLessEqual:
8970 case OO_GreaterGreaterEqual:
8971 case OO_EqualEqual:
8972 case OO_ExclaimEqual:
8973 case OO_PlusPlus:
8974 case OO_MinusMinus:
8975 case OO_Comma:
8976 case OO_ArrowStar:
8977 case OO_Arrow:
8978 case OO_Call:
8979 case OO_Subscript:
8980 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008981 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008982 case NUM_OVERLOADED_OPERATORS:
8983 llvm_unreachable("Unexpected reduction identifier");
8984 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008985 if (auto II = DN.getAsIdentifierInfo()) {
8986 if (II->isStr("max"))
8987 BOK = BO_GT;
8988 else if (II->isStr("min"))
8989 BOK = BO_LT;
8990 }
8991 break;
8992 }
8993 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008994 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008995 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008996 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008997
8998 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008999 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009000 SmallVector<Expr *, 8> LHSs;
9001 SmallVector<Expr *, 8> RHSs;
9002 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00009003 SmallVector<Decl *, 4> ExprCaptures;
9004 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009005 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9006 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009007 for (auto RefExpr : VarList) {
9008 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009009 // OpenMP [2.1, C/C++]
9010 // A list item is a variable or array section, subject to the restrictions
9011 // specified in Section 2.4 on page 42 and in each of the sections
9012 // describing clauses and directives for which a list appears.
9013 // OpenMP [2.14.3.3, Restrictions, p.1]
9014 // A variable that is part of another variable (as an array or
9015 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009016 if (!FirstIter && IR != ER)
9017 ++IR;
9018 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009019 SourceLocation ELoc;
9020 SourceRange ERange;
9021 Expr *SimpleRefExpr = RefExpr;
9022 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9023 /*AllowArraySection=*/true);
9024 if (Res.second) {
9025 // It will be analyzed later.
9026 Vars.push_back(RefExpr);
9027 Privates.push_back(nullptr);
9028 LHSs.push_back(nullptr);
9029 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009030 // Try to find 'declare reduction' corresponding construct before using
9031 // builtin/overloaded operators.
9032 QualType Type = Context.DependentTy;
9033 CXXCastPath BasePath;
9034 ExprResult DeclareReductionRef = buildDeclareReductionRef(
9035 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
9036 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9037 if (CurContext->isDependentContext() &&
9038 (DeclareReductionRef.isUnset() ||
9039 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
9040 ReductionOps.push_back(DeclareReductionRef.get());
9041 else
9042 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009043 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009044 ValueDecl *D = Res.first;
9045 if (!D)
9046 continue;
9047
Alexey Bataeva1764212015-09-30 09:22:36 +00009048 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009049 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9050 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9051 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009052 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009053 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009054 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9055 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9056 Type = ATy->getElementType();
9057 else
9058 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009059 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009060 } else
9061 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9062 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009063
Alexey Bataevc5e02582014-06-16 07:08:35 +00009064 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9065 // A variable that appears in a private clause must not have an incomplete
9066 // type or a reference type.
9067 if (RequireCompleteType(ELoc, Type,
9068 diag::err_omp_reduction_incomplete_type))
9069 continue;
9070 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009071 // A list item that appears in a reduction clause must not be
9072 // const-qualified.
9073 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009074 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009075 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009076 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009077 bool IsDecl = !VD ||
9078 VD->isThisDeclarationADefinition(Context) ==
9079 VarDecl::DeclarationOnly;
9080 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00009081 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009082 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009083 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009084 continue;
9085 }
9086 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9087 // If a list-item is a reference type then it must bind to the same object
9088 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009089 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009090 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009091 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009092 DSARefChecker Check(DSAStack);
9093 if (Check.Visit(VDDef->getInit())) {
9094 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
9095 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
9096 continue;
9097 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009098 }
9099 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009100
Alexey Bataevc5e02582014-06-16 07:08:35 +00009101 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9102 // in a Construct]
9103 // Variables with the predetermined data-sharing attributes may not be
9104 // listed in data-sharing attributes clauses, except for the cases
9105 // listed below. For these exceptions only, listing a predetermined
9106 // variable in a data-sharing attribute clause is allowed and overrides
9107 // the variable's predetermined data-sharing attributes.
9108 // OpenMP [2.14.3.6, Restrictions, p.3]
9109 // Any number of reduction clauses can be specified on the directive,
9110 // but a list item can appear only once in the reduction clauses for that
9111 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009112 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009113 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009114 if (DVar.CKind == OMPC_reduction) {
9115 Diag(ELoc, diag::err_omp_once_referenced)
9116 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009117 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009118 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009119 } else if (DVar.CKind != OMPC_unknown) {
9120 Diag(ELoc, diag::err_omp_wrong_dsa)
9121 << getOpenMPClauseName(DVar.CKind)
9122 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009123 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009124 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009125 }
9126
9127 // OpenMP [2.14.3.6, Restrictions, p.1]
9128 // A list item that appears in a reduction clause of a worksharing
9129 // construct must be shared in the parallel regions to which any of the
9130 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009131 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9132 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009133 !isOpenMPParallelDirective(CurrDir) &&
9134 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009135 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009136 if (DVar.CKind != OMPC_shared) {
9137 Diag(ELoc, diag::err_omp_required_access)
9138 << getOpenMPClauseName(OMPC_reduction)
9139 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009140 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009141 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009142 }
9143 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009144
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009145 // Try to find 'declare reduction' corresponding construct before using
9146 // builtin/overloaded operators.
9147 CXXCastPath BasePath;
9148 ExprResult DeclareReductionRef = buildDeclareReductionRef(
9149 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
9150 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9151 if (DeclareReductionRef.isInvalid())
9152 continue;
9153 if (CurContext->isDependentContext() &&
9154 (DeclareReductionRef.isUnset() ||
9155 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
9156 Vars.push_back(RefExpr);
9157 Privates.push_back(nullptr);
9158 LHSs.push_back(nullptr);
9159 RHSs.push_back(nullptr);
9160 ReductionOps.push_back(DeclareReductionRef.get());
9161 continue;
9162 }
9163 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9164 // Not allowed reduction identifier is found.
9165 Diag(ReductionId.getLocStart(),
9166 diag::err_omp_unknown_reduction_identifier)
9167 << Type << ReductionIdRange;
9168 continue;
9169 }
9170
9171 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9172 // The type of a list item that appears in a reduction clause must be valid
9173 // for the reduction-identifier. For a max or min reduction in C, the type
9174 // of the list item must be an allowed arithmetic data type: char, int,
9175 // float, double, or _Bool, possibly modified with long, short, signed, or
9176 // unsigned. For a max or min reduction in C++, the type of the list item
9177 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9178 // double, or bool, possibly modified with long, short, signed, or unsigned.
9179 if (DeclareReductionRef.isUnset()) {
9180 if ((BOK == BO_GT || BOK == BO_LT) &&
9181 !(Type->isScalarType() ||
9182 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9183 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
9184 << getLangOpts().CPlusPlus;
9185 if (!ASE && !OASE) {
9186 bool IsDecl = !VD ||
9187 VD->isThisDeclarationADefinition(Context) ==
9188 VarDecl::DeclarationOnly;
9189 Diag(D->getLocation(),
9190 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9191 << D;
9192 }
9193 continue;
9194 }
9195 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
9196 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
9197 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
9198 if (!ASE && !OASE) {
9199 bool IsDecl = !VD ||
9200 VD->isThisDeclarationADefinition(Context) ==
9201 VarDecl::DeclarationOnly;
9202 Diag(D->getLocation(),
9203 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9204 << D;
9205 }
9206 continue;
9207 }
9208 }
9209
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009210 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009211 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009212 D->hasAttrs() ? &D->getAttrs() : nullptr);
9213 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9214 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009215 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009216 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009217 (!ASE &&
9218 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009219 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009220 // Create pseudo array type for private copy. The size for this array will
9221 // be generated during codegen.
9222 // For array subscripts or single variables Private Ty is the same as Type
9223 // (type of the variable or single array element).
9224 PrivateTy = Context.getVariableArrayType(
9225 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9226 Context.getSizeType(), VK_RValue),
9227 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009228 } else if (!ASE && !OASE &&
9229 Context.getAsArrayType(D->getType().getNonReferenceType()))
9230 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009231 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009232 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9233 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009234 // Add initializer for private variable.
9235 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009236 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9237 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9238 if (DeclareReductionRef.isUsable()) {
9239 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9240 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9241 if (DRD->getInitializer()) {
9242 Init = DRDRef;
9243 RHSVD->setInit(DRDRef);
9244 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009245 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009246 } else {
9247 switch (BOK) {
9248 case BO_Add:
9249 case BO_Xor:
9250 case BO_Or:
9251 case BO_LOr:
9252 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9253 if (Type->isScalarType() || Type->isAnyComplexType())
9254 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9255 break;
9256 case BO_Mul:
9257 case BO_LAnd:
9258 if (Type->isScalarType() || Type->isAnyComplexType()) {
9259 // '*' and '&&' reduction ops - initializer is '1'.
9260 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009261 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009262 break;
9263 case BO_And: {
9264 // '&' reduction op - initializer is '~0'.
9265 QualType OrigType = Type;
9266 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9267 Type = ComplexTy->getElementType();
9268 if (Type->isRealFloatingType()) {
9269 llvm::APFloat InitValue =
9270 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9271 /*isIEEE=*/true);
9272 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9273 Type, ELoc);
9274 } else if (Type->isScalarType()) {
9275 auto Size = Context.getTypeSize(Type);
9276 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9277 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9278 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9279 }
9280 if (Init && OrigType->isAnyComplexType()) {
9281 // Init = 0xFFFF + 0xFFFFi;
9282 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9283 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9284 }
9285 Type = OrigType;
9286 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009287 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009288 case BO_LT:
9289 case BO_GT: {
9290 // 'min' reduction op - initializer is 'Largest representable number in
9291 // the reduction list item type'.
9292 // 'max' reduction op - initializer is 'Least representable number in
9293 // the reduction list item type'.
9294 if (Type->isIntegerType() || Type->isPointerType()) {
9295 bool IsSigned = Type->hasSignedIntegerRepresentation();
9296 auto Size = Context.getTypeSize(Type);
9297 QualType IntTy =
9298 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9299 llvm::APInt InitValue =
9300 (BOK != BO_LT)
9301 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9302 : llvm::APInt::getMinValue(Size)
9303 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9304 : llvm::APInt::getMaxValue(Size);
9305 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9306 if (Type->isPointerType()) {
9307 // Cast to pointer type.
9308 auto CastExpr = BuildCStyleCastExpr(
9309 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9310 SourceLocation(), Init);
9311 if (CastExpr.isInvalid())
9312 continue;
9313 Init = CastExpr.get();
9314 }
9315 } else if (Type->isRealFloatingType()) {
9316 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9317 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9318 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9319 Type, ELoc);
9320 }
9321 break;
9322 }
9323 case BO_PtrMemD:
9324 case BO_PtrMemI:
9325 case BO_MulAssign:
9326 case BO_Div:
9327 case BO_Rem:
9328 case BO_Sub:
9329 case BO_Shl:
9330 case BO_Shr:
9331 case BO_LE:
9332 case BO_GE:
9333 case BO_EQ:
9334 case BO_NE:
9335 case BO_AndAssign:
9336 case BO_XorAssign:
9337 case BO_OrAssign:
9338 case BO_Assign:
9339 case BO_AddAssign:
9340 case BO_SubAssign:
9341 case BO_DivAssign:
9342 case BO_RemAssign:
9343 case BO_ShlAssign:
9344 case BO_ShrAssign:
9345 case BO_Comma:
9346 llvm_unreachable("Unexpected reduction operation");
9347 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009348 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009349 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009350 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009351 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009352 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009353 if (RHSVD->isInvalidDecl())
9354 continue;
9355 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009356 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9357 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009358 bool IsDecl =
9359 !VD ||
9360 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9361 Diag(D->getLocation(),
9362 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9363 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009364 continue;
9365 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009366 // Store initializer for single element in private copy. Will be used during
9367 // codegen.
9368 PrivateVD->setInit(RHSVD->getInit());
9369 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009370 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009371 ExprResult ReductionOp;
9372 if (DeclareReductionRef.isUsable()) {
9373 QualType RedTy = DeclareReductionRef.get()->getType();
9374 QualType PtrRedTy = Context.getPointerType(RedTy);
9375 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9376 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9377 if (!BasePath.empty()) {
9378 LHS = DefaultLvalueConversion(LHS.get());
9379 RHS = DefaultLvalueConversion(RHS.get());
9380 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9381 CK_UncheckedDerivedToBase, LHS.get(),
9382 &BasePath, LHS.get()->getValueKind());
9383 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9384 CK_UncheckedDerivedToBase, RHS.get(),
9385 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009386 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009387 FunctionProtoType::ExtProtoInfo EPI;
9388 QualType Params[] = {PtrRedTy, PtrRedTy};
9389 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9390 auto *OVE = new (Context) OpaqueValueExpr(
9391 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9392 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9393 Expr *Args[] = {LHS.get(), RHS.get()};
9394 ReductionOp = new (Context)
9395 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9396 } else {
9397 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9398 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9399 if (ReductionOp.isUsable()) {
9400 if (BOK != BO_LT && BOK != BO_GT) {
9401 ReductionOp =
9402 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9403 BO_Assign, LHSDRE, ReductionOp.get());
9404 } else {
9405 auto *ConditionalOp = new (Context) ConditionalOperator(
9406 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9407 RHSDRE, Type, VK_LValue, OK_Ordinary);
9408 ReductionOp =
9409 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9410 BO_Assign, LHSDRE, ConditionalOp);
9411 }
9412 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9413 }
9414 if (ReductionOp.isInvalid())
9415 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009416 }
9417
Alexey Bataev60da77e2016-02-29 05:54:20 +00009418 DeclRefExpr *Ref = nullptr;
9419 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009420 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009421 if (ASE || OASE) {
9422 TransformExprToCaptures RebuildToCapture(*this, D);
9423 VarsExpr =
9424 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9425 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009426 } else {
9427 VarsExpr = Ref =
9428 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009429 }
9430 if (!IsOpenMPCapturedDecl(D)) {
9431 ExprCaptures.push_back(Ref->getDecl());
9432 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9433 ExprResult RefRes = DefaultLvalueConversion(Ref);
9434 if (!RefRes.isUsable())
9435 continue;
9436 ExprResult PostUpdateRes =
9437 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9438 SimpleRefExpr, RefRes.get());
9439 if (!PostUpdateRes.isUsable())
9440 continue;
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009441 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
9442 Diag(RefExpr->getExprLoc(),
9443 diag::err_omp_reduction_non_addressable_expression)
9444 << RefExpr->getSourceRange();
9445 continue;
9446 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00009447 ExprPostUpdates.push_back(
9448 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009449 }
9450 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009451 }
9452 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9453 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009454 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009455 LHSs.push_back(LHSDRE);
9456 RHSs.push_back(RHSDRE);
9457 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009458 }
9459
9460 if (Vars.empty())
9461 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009462
Alexey Bataevc5e02582014-06-16 07:08:35 +00009463 return OMPReductionClause::Create(
9464 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009465 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009466 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9467 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009468}
9469
Alexey Bataevecba70f2016-04-12 11:02:11 +00009470bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9471 SourceLocation LinLoc) {
9472 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9473 LinKind == OMPC_LINEAR_unknown) {
9474 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9475 return true;
9476 }
9477 return false;
9478}
9479
9480bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9481 OpenMPLinearClauseKind LinKind,
9482 QualType Type) {
9483 auto *VD = dyn_cast_or_null<VarDecl>(D);
9484 // A variable must not have an incomplete type or a reference type.
9485 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9486 return true;
9487 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9488 !Type->isReferenceType()) {
9489 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9490 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9491 return true;
9492 }
9493 Type = Type.getNonReferenceType();
9494
9495 // A list item must not be const-qualified.
9496 if (Type.isConstant(Context)) {
9497 Diag(ELoc, diag::err_omp_const_variable)
9498 << getOpenMPClauseName(OMPC_linear);
9499 if (D) {
9500 bool IsDecl =
9501 !VD ||
9502 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9503 Diag(D->getLocation(),
9504 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9505 << D;
9506 }
9507 return true;
9508 }
9509
9510 // A list item must be of integral or pointer type.
9511 Type = Type.getUnqualifiedType().getCanonicalType();
9512 const auto *Ty = Type.getTypePtrOrNull();
9513 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9514 !Ty->isPointerType())) {
9515 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9516 if (D) {
9517 bool IsDecl =
9518 !VD ||
9519 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9520 Diag(D->getLocation(),
9521 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9522 << D;
9523 }
9524 return true;
9525 }
9526 return false;
9527}
9528
Alexey Bataev182227b2015-08-20 10:54:39 +00009529OMPClause *Sema::ActOnOpenMPLinearClause(
9530 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9531 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9532 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009533 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009534 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009535 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009536 SmallVector<Decl *, 4> ExprCaptures;
9537 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009538 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009539 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009540 for (auto &RefExpr : VarList) {
9541 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009542 SourceLocation ELoc;
9543 SourceRange ERange;
9544 Expr *SimpleRefExpr = RefExpr;
9545 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9546 /*AllowArraySection=*/false);
9547 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009548 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009549 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009550 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009551 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009552 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009553 ValueDecl *D = Res.first;
9554 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009555 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009556
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009557 QualType Type = D->getType();
9558 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009559
9560 // OpenMP [2.14.3.7, linear clause]
9561 // A list-item cannot appear in more than one linear clause.
9562 // A list-item that appears in a linear clause cannot appear in any
9563 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009564 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009565 if (DVar.RefExpr) {
9566 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9567 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009568 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009569 continue;
9570 }
9571
Alexey Bataevecba70f2016-04-12 11:02:11 +00009572 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009573 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009574 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009575
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009576 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009577 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9578 D->hasAttrs() ? &D->getAttrs() : nullptr);
9579 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009580 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009581 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009582 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009583 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009584 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009585 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9586 if (!IsOpenMPCapturedDecl(D)) {
9587 ExprCaptures.push_back(Ref->getDecl());
9588 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9589 ExprResult RefRes = DefaultLvalueConversion(Ref);
9590 if (!RefRes.isUsable())
9591 continue;
9592 ExprResult PostUpdateRes =
9593 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9594 SimpleRefExpr, RefRes.get());
9595 if (!PostUpdateRes.isUsable())
9596 continue;
9597 ExprPostUpdates.push_back(
9598 IgnoredValueConversions(PostUpdateRes.get()).get());
9599 }
9600 }
9601 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009602 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009603 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009604 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009605 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009606 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009607 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009608 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9609
9610 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009611 Vars.push_back((VD || CurContext->isDependentContext())
9612 ? RefExpr->IgnoreParens()
9613 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009614 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009615 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009616 }
9617
9618 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009619 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009620
9621 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009622 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009623 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9624 !Step->isInstantiationDependent() &&
9625 !Step->containsUnexpandedParameterPack()) {
9626 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009627 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009628 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009629 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009630 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009631
Alexander Musman3276a272015-03-21 10:12:56 +00009632 // Build var to save the step value.
9633 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009634 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009635 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009636 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009637 ExprResult CalcStep =
9638 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009639 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009640
Alexander Musman8dba6642014-04-22 13:09:42 +00009641 // Warn about zero linear step (it would be probably better specified as
9642 // making corresponding variables 'const').
9643 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009644 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9645 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009646 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9647 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009648 if (!IsConstant && CalcStep.isUsable()) {
9649 // Calculate the step beforehand instead of doing this on each iteration.
9650 // (This is not used if the number of iterations may be kfold-ed).
9651 CalcStepExpr = CalcStep.get();
9652 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009653 }
9654
Alexey Bataev182227b2015-08-20 10:54:39 +00009655 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9656 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009657 StepExpr, CalcStepExpr,
9658 buildPreInits(Context, ExprCaptures),
9659 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009660}
9661
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009662static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9663 Expr *NumIterations, Sema &SemaRef,
9664 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009665 // Walk the vars and build update/final expressions for the CodeGen.
9666 SmallVector<Expr *, 8> Updates;
9667 SmallVector<Expr *, 8> Finals;
9668 Expr *Step = Clause.getStep();
9669 Expr *CalcStep = Clause.getCalcStep();
9670 // OpenMP [2.14.3.7, linear clause]
9671 // If linear-step is not specified it is assumed to be 1.
9672 if (Step == nullptr)
9673 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009674 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009675 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009676 }
Alexander Musman3276a272015-03-21 10:12:56 +00009677 bool HasErrors = false;
9678 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009679 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009680 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009681 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009682 SourceLocation ELoc;
9683 SourceRange ERange;
9684 Expr *SimpleRefExpr = RefExpr;
9685 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9686 /*AllowArraySection=*/false);
9687 ValueDecl *D = Res.first;
9688 if (Res.second || !D) {
9689 Updates.push_back(nullptr);
9690 Finals.push_back(nullptr);
9691 HasErrors = true;
9692 continue;
9693 }
9694 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9695 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9696 ->getMemberDecl();
9697 }
9698 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009699 Expr *InitExpr = *CurInit;
9700
9701 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009702 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009703 Expr *CapturedRef;
9704 if (LinKind == OMPC_LINEAR_uval)
9705 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9706 else
9707 CapturedRef =
9708 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9709 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9710 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009711
9712 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009713 ExprResult Update;
9714 if (!Info.first) {
9715 Update =
9716 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9717 InitExpr, IV, Step, /* Subtract */ false);
9718 } else
9719 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009720 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9721 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009722
9723 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009724 ExprResult Final;
9725 if (!Info.first) {
9726 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9727 InitExpr, NumIterations, Step,
9728 /* Subtract */ false);
9729 } else
9730 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009731 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9732 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009733
Alexander Musman3276a272015-03-21 10:12:56 +00009734 if (!Update.isUsable() || !Final.isUsable()) {
9735 Updates.push_back(nullptr);
9736 Finals.push_back(nullptr);
9737 HasErrors = true;
9738 } else {
9739 Updates.push_back(Update.get());
9740 Finals.push_back(Final.get());
9741 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009742 ++CurInit;
9743 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009744 }
9745 Clause.setUpdates(Updates);
9746 Clause.setFinals(Finals);
9747 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009748}
9749
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009750OMPClause *Sema::ActOnOpenMPAlignedClause(
9751 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9752 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9753
9754 SmallVector<Expr *, 8> Vars;
9755 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009756 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9757 SourceLocation ELoc;
9758 SourceRange ERange;
9759 Expr *SimpleRefExpr = RefExpr;
9760 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9761 /*AllowArraySection=*/false);
9762 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009763 // It will be analyzed later.
9764 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009765 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009766 ValueDecl *D = Res.first;
9767 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009768 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009769
Alexey Bataev1efd1662016-03-29 10:59:56 +00009770 QualType QType = D->getType();
9771 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009772
9773 // OpenMP [2.8.1, simd construct, Restrictions]
9774 // The type of list items appearing in the aligned clause must be
9775 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009776 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009777 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009778 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009779 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009780 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009781 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009782 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009783 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009784 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009785 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009786 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009787 continue;
9788 }
9789
9790 // OpenMP [2.8.1, simd construct, Restrictions]
9791 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009792 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009793 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009794 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9795 << getOpenMPClauseName(OMPC_aligned);
9796 continue;
9797 }
9798
Alexey Bataev1efd1662016-03-29 10:59:56 +00009799 DeclRefExpr *Ref = nullptr;
9800 if (!VD && IsOpenMPCapturedDecl(D))
9801 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9802 Vars.push_back(DefaultFunctionArrayConversion(
9803 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9804 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009805 }
9806
9807 // OpenMP [2.8.1, simd construct, Description]
9808 // The parameter of the aligned clause, alignment, must be a constant
9809 // positive integer expression.
9810 // If no optional parameter is specified, implementation-defined default
9811 // alignments for SIMD instructions on the target platforms are assumed.
9812 if (Alignment != nullptr) {
9813 ExprResult AlignResult =
9814 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9815 if (AlignResult.isInvalid())
9816 return nullptr;
9817 Alignment = AlignResult.get();
9818 }
9819 if (Vars.empty())
9820 return nullptr;
9821
9822 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9823 EndLoc, Vars, Alignment);
9824}
9825
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009826OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9827 SourceLocation StartLoc,
9828 SourceLocation LParenLoc,
9829 SourceLocation EndLoc) {
9830 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009831 SmallVector<Expr *, 8> SrcExprs;
9832 SmallVector<Expr *, 8> DstExprs;
9833 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009834 for (auto &RefExpr : VarList) {
9835 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9836 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009837 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009838 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009839 SrcExprs.push_back(nullptr);
9840 DstExprs.push_back(nullptr);
9841 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009842 continue;
9843 }
9844
Alexey Bataeved09d242014-05-28 05:53:51 +00009845 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009846 // OpenMP [2.1, C/C++]
9847 // A list item is a variable name.
9848 // OpenMP [2.14.4.1, Restrictions, p.1]
9849 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009850 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009851 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009852 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9853 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009854 continue;
9855 }
9856
9857 Decl *D = DE->getDecl();
9858 VarDecl *VD = cast<VarDecl>(D);
9859
9860 QualType Type = VD->getType();
9861 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9862 // It will be analyzed later.
9863 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009864 SrcExprs.push_back(nullptr);
9865 DstExprs.push_back(nullptr);
9866 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009867 continue;
9868 }
9869
9870 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9871 // A list item that appears in a copyin clause must be threadprivate.
9872 if (!DSAStack->isThreadPrivate(VD)) {
9873 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009874 << getOpenMPClauseName(OMPC_copyin)
9875 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009876 continue;
9877 }
9878
9879 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9880 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009881 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009882 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009883 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009884 auto *SrcVD =
9885 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9886 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009887 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009888 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9889 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009890 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9891 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009892 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009893 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009894 // For arrays generate assignment operation for single element and replace
9895 // it by the original array element in CodeGen.
9896 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9897 PseudoDstExpr, PseudoSrcExpr);
9898 if (AssignmentOp.isInvalid())
9899 continue;
9900 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9901 /*DiscardedValue=*/true);
9902 if (AssignmentOp.isInvalid())
9903 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009904
9905 DSAStack->addDSA(VD, DE, OMPC_copyin);
9906 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009907 SrcExprs.push_back(PseudoSrcExpr);
9908 DstExprs.push_back(PseudoDstExpr);
9909 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009910 }
9911
Alexey Bataeved09d242014-05-28 05:53:51 +00009912 if (Vars.empty())
9913 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009914
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009915 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9916 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009917}
9918
Alexey Bataevbae9a792014-06-27 10:37:06 +00009919OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9920 SourceLocation StartLoc,
9921 SourceLocation LParenLoc,
9922 SourceLocation EndLoc) {
9923 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009924 SmallVector<Expr *, 8> SrcExprs;
9925 SmallVector<Expr *, 8> DstExprs;
9926 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009927 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009928 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9929 SourceLocation ELoc;
9930 SourceRange ERange;
9931 Expr *SimpleRefExpr = RefExpr;
9932 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9933 /*AllowArraySection=*/false);
9934 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009935 // It will be analyzed later.
9936 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009937 SrcExprs.push_back(nullptr);
9938 DstExprs.push_back(nullptr);
9939 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009940 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009941 ValueDecl *D = Res.first;
9942 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009943 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009944
Alexey Bataeve122da12016-03-17 10:50:17 +00009945 QualType Type = D->getType();
9946 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009947
9948 // OpenMP [2.14.4.2, Restrictions, p.2]
9949 // A list item that appears in a copyprivate clause may not appear in a
9950 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009951 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9952 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009953 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9954 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009955 Diag(ELoc, diag::err_omp_wrong_dsa)
9956 << getOpenMPClauseName(DVar.CKind)
9957 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009958 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009959 continue;
9960 }
9961
9962 // OpenMP [2.11.4.2, Restrictions, p.1]
9963 // All list items that appear in a copyprivate clause must be either
9964 // threadprivate or private in the enclosing context.
9965 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009966 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009967 if (DVar.CKind == OMPC_shared) {
9968 Diag(ELoc, diag::err_omp_required_access)
9969 << getOpenMPClauseName(OMPC_copyprivate)
9970 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009971 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009972 continue;
9973 }
9974 }
9975 }
9976
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009977 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009978 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009979 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009980 << getOpenMPClauseName(OMPC_copyprivate) << Type
9981 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009982 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009983 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009984 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009985 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009986 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009987 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009988 continue;
9989 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009990
Alexey Bataevbae9a792014-06-27 10:37:06 +00009991 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9992 // A variable of class type (or array thereof) that appears in a
9993 // copyin clause requires an accessible, unambiguous copy assignment
9994 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009995 Type = Context.getBaseElementType(Type.getNonReferenceType())
9996 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009997 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009998 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9999 D->hasAttrs() ? &D->getAttrs() : nullptr);
10000 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010001 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010002 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10003 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010004 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010005 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010006 PseudoDstExpr, PseudoSrcExpr);
10007 if (AssignmentOp.isInvalid())
10008 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010009 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010010 /*DiscardedValue=*/true);
10011 if (AssignmentOp.isInvalid())
10012 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010013
10014 // No need to mark vars as copyprivate, they are already threadprivate or
10015 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010016 assert(VD || IsOpenMPCapturedDecl(D));
10017 Vars.push_back(
10018 VD ? RefExpr->IgnoreParens()
10019 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010020 SrcExprs.push_back(PseudoSrcExpr);
10021 DstExprs.push_back(PseudoDstExpr);
10022 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010023 }
10024
10025 if (Vars.empty())
10026 return nullptr;
10027
Alexey Bataeva63048e2015-03-23 06:18:07 +000010028 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10029 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010030}
10031
Alexey Bataev6125da92014-07-21 11:26:11 +000010032OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10033 SourceLocation StartLoc,
10034 SourceLocation LParenLoc,
10035 SourceLocation EndLoc) {
10036 if (VarList.empty())
10037 return nullptr;
10038
10039 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10040}
Alexey Bataevdea47612014-07-23 07:46:59 +000010041
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010042OMPClause *
10043Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10044 SourceLocation DepLoc, SourceLocation ColonLoc,
10045 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10046 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010047 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010048 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010049 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010050 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010051 return nullptr;
10052 }
10053 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010054 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10055 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010056 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010057 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010058 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10059 /*Last=*/OMPC_DEPEND_unknown, Except)
10060 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010061 return nullptr;
10062 }
10063 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010064 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010065 llvm::APSInt DepCounter(/*BitWidth=*/32);
10066 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10067 if (DepKind == OMPC_DEPEND_sink) {
10068 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10069 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10070 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010071 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010072 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010073 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10074 DSAStack->getParentOrderedRegionParam()) {
10075 for (auto &RefExpr : VarList) {
10076 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010077 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010078 // It will be analyzed later.
10079 Vars.push_back(RefExpr);
10080 continue;
10081 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010082
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010083 SourceLocation ELoc = RefExpr->getExprLoc();
10084 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10085 if (DepKind == OMPC_DEPEND_sink) {
10086 if (DepCounter >= TotalDepCount) {
10087 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10088 continue;
10089 }
10090 ++DepCounter;
10091 // OpenMP [2.13.9, Summary]
10092 // depend(dependence-type : vec), where dependence-type is:
10093 // 'sink' and where vec is the iteration vector, which has the form:
10094 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10095 // where n is the value specified by the ordered clause in the loop
10096 // directive, xi denotes the loop iteration variable of the i-th nested
10097 // loop associated with the loop directive, and di is a constant
10098 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010099 if (CurContext->isDependentContext()) {
10100 // It will be analyzed later.
10101 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010102 continue;
10103 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010104 SimpleExpr = SimpleExpr->IgnoreImplicit();
10105 OverloadedOperatorKind OOK = OO_None;
10106 SourceLocation OOLoc;
10107 Expr *LHS = SimpleExpr;
10108 Expr *RHS = nullptr;
10109 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10110 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10111 OOLoc = BO->getOperatorLoc();
10112 LHS = BO->getLHS()->IgnoreParenImpCasts();
10113 RHS = BO->getRHS()->IgnoreParenImpCasts();
10114 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10115 OOK = OCE->getOperator();
10116 OOLoc = OCE->getOperatorLoc();
10117 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10118 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10119 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10120 OOK = MCE->getMethodDecl()
10121 ->getNameInfo()
10122 .getName()
10123 .getCXXOverloadedOperator();
10124 OOLoc = MCE->getCallee()->getExprLoc();
10125 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10126 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10127 }
10128 SourceLocation ELoc;
10129 SourceRange ERange;
10130 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10131 /*AllowArraySection=*/false);
10132 if (Res.second) {
10133 // It will be analyzed later.
10134 Vars.push_back(RefExpr);
10135 }
10136 ValueDecl *D = Res.first;
10137 if (!D)
10138 continue;
10139
10140 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10141 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10142 continue;
10143 }
10144 if (RHS) {
10145 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10146 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10147 if (RHSRes.isInvalid())
10148 continue;
10149 }
10150 if (!CurContext->isDependentContext() &&
10151 DSAStack->getParentOrderedRegionParam() &&
10152 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10153 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10154 << DSAStack->getParentLoopControlVariable(
10155 DepCounter.getZExtValue());
10156 continue;
10157 }
10158 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010159 } else {
10160 // OpenMP [2.11.1.1, Restrictions, p.3]
10161 // A variable that is part of another variable (such as a field of a
10162 // structure) but is not an array element or an array section cannot
10163 // appear in a depend clause.
10164 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10165 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10166 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10167 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10168 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010169 (ASE &&
10170 !ASE->getBase()
10171 ->getType()
10172 .getNonReferenceType()
10173 ->isPointerType() &&
10174 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010175 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10176 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010177 continue;
10178 }
10179 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010180 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10181 }
10182
10183 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10184 TotalDepCount > VarList.size() &&
10185 DSAStack->getParentOrderedRegionParam()) {
10186 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10187 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10188 }
10189 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10190 Vars.empty())
10191 return nullptr;
10192 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010193 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10194 DepKind, DepLoc, ColonLoc, Vars);
10195 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10196 DSAStack->addDoacrossDependClause(C, OpsOffs);
10197 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010198}
Michael Wonge710d542015-08-07 16:16:36 +000010199
10200OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10201 SourceLocation LParenLoc,
10202 SourceLocation EndLoc) {
10203 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010204
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010205 // OpenMP [2.9.1, Restrictions]
10206 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010207 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10208 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010209 return nullptr;
10210
Michael Wonge710d542015-08-07 16:16:36 +000010211 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10212}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010213
10214static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10215 DSAStackTy *Stack, CXXRecordDecl *RD) {
10216 if (!RD || RD->isInvalidDecl())
10217 return true;
10218
10219 auto QTy = SemaRef.Context.getRecordType(RD);
10220 if (RD->isDynamicClass()) {
10221 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10222 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10223 return false;
10224 }
10225 auto *DC = RD;
10226 bool IsCorrect = true;
10227 for (auto *I : DC->decls()) {
10228 if (I) {
10229 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10230 if (MD->isStatic()) {
10231 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10232 SemaRef.Diag(MD->getLocation(),
10233 diag::note_omp_static_member_in_target);
10234 IsCorrect = false;
10235 }
10236 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10237 if (VD->isStaticDataMember()) {
10238 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10239 SemaRef.Diag(VD->getLocation(),
10240 diag::note_omp_static_member_in_target);
10241 IsCorrect = false;
10242 }
10243 }
10244 }
10245 }
10246
10247 for (auto &I : RD->bases()) {
10248 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10249 I.getType()->getAsCXXRecordDecl()))
10250 IsCorrect = false;
10251 }
10252 return IsCorrect;
10253}
10254
10255static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10256 DSAStackTy *Stack, QualType QTy) {
10257 NamedDecl *ND;
10258 if (QTy->isIncompleteType(&ND)) {
10259 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10260 return false;
10261 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010262 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010263 return false;
10264 }
10265 return true;
10266}
10267
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010268/// \brief Return true if it can be proven that the provided array expression
10269/// (array section or array subscript) does NOT specify the whole size of the
10270/// array whose base type is \a BaseQTy.
10271static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10272 const Expr *E,
10273 QualType BaseQTy) {
10274 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10275
10276 // If this is an array subscript, it refers to the whole size if the size of
10277 // the dimension is constant and equals 1. Also, an array section assumes the
10278 // format of an array subscript if no colon is used.
10279 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10280 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10281 return ATy->getSize().getSExtValue() != 1;
10282 // Size can't be evaluated statically.
10283 return false;
10284 }
10285
10286 assert(OASE && "Expecting array section if not an array subscript.");
10287 auto *LowerBound = OASE->getLowerBound();
10288 auto *Length = OASE->getLength();
10289
10290 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010291 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010292 if (LowerBound) {
10293 llvm::APSInt ConstLowerBound;
10294 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10295 return false; // Can't get the integer value as a constant.
10296 if (ConstLowerBound.getSExtValue())
10297 return true;
10298 }
10299
10300 // If we don't have a length we covering the whole dimension.
10301 if (!Length)
10302 return false;
10303
10304 // If the base is a pointer, we don't have a way to get the size of the
10305 // pointee.
10306 if (BaseQTy->isPointerType())
10307 return false;
10308
10309 // We can only check if the length is the same as the size of the dimension
10310 // if we have a constant array.
10311 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10312 if (!CATy)
10313 return false;
10314
10315 llvm::APSInt ConstLength;
10316 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10317 return false; // Can't get the integer value as a constant.
10318
10319 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10320}
10321
10322// Return true if it can be proven that the provided array expression (array
10323// section or array subscript) does NOT specify a single element of the array
10324// whose base type is \a BaseQTy.
10325static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010326 const Expr *E,
10327 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010328 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10329
10330 // An array subscript always refer to a single element. Also, an array section
10331 // assumes the format of an array subscript if no colon is used.
10332 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10333 return false;
10334
10335 assert(OASE && "Expecting array section if not an array subscript.");
10336 auto *Length = OASE->getLength();
10337
10338 // If we don't have a length we have to check if the array has unitary size
10339 // for this dimension. Also, we should always expect a length if the base type
10340 // is pointer.
10341 if (!Length) {
10342 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10343 return ATy->getSize().getSExtValue() != 1;
10344 // We cannot assume anything.
10345 return false;
10346 }
10347
10348 // Check if the length evaluates to 1.
10349 llvm::APSInt ConstLength;
10350 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10351 return false; // Can't get the integer value as a constant.
10352
10353 return ConstLength.getSExtValue() != 1;
10354}
10355
Samuel Antao661c0902016-05-26 17:39:58 +000010356// Return the expression of the base of the mappable expression or null if it
10357// cannot be determined and do all the necessary checks to see if the expression
10358// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010359// components of the expression.
10360static Expr *CheckMapClauseExpressionBase(
10361 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010362 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10363 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010364 SourceLocation ELoc = E->getExprLoc();
10365 SourceRange ERange = E->getSourceRange();
10366
10367 // The base of elements of list in a map clause have to be either:
10368 // - a reference to variable or field.
10369 // - a member expression.
10370 // - an array expression.
10371 //
10372 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10373 // reference to 'r'.
10374 //
10375 // If we have:
10376 //
10377 // struct SS {
10378 // Bla S;
10379 // foo() {
10380 // #pragma omp target map (S.Arr[:12]);
10381 // }
10382 // }
10383 //
10384 // We want to retrieve the member expression 'this->S';
10385
10386 Expr *RelevantExpr = nullptr;
10387
Samuel Antao5de996e2016-01-22 20:21:36 +000010388 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10389 // If a list item is an array section, it must specify contiguous storage.
10390 //
10391 // For this restriction it is sufficient that we make sure only references
10392 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010393 // exist except in the rightmost expression (unless they cover the whole
10394 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010395 //
10396 // r.ArrS[3:5].Arr[6:7]
10397 //
10398 // r.ArrS[3:5].x
10399 //
10400 // but these would be valid:
10401 // r.ArrS[3].Arr[6:7]
10402 //
10403 // r.ArrS[3].x
10404
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010405 bool AllowUnitySizeArraySection = true;
10406 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010407
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010408 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010409 E = E->IgnoreParenImpCasts();
10410
10411 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10412 if (!isa<VarDecl>(CurE->getDecl()))
10413 break;
10414
10415 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010416
10417 // If we got a reference to a declaration, we should not expect any array
10418 // section before that.
10419 AllowUnitySizeArraySection = false;
10420 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010421
10422 // Record the component.
10423 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10424 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010425 continue;
10426 }
10427
10428 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10429 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10430
10431 if (isa<CXXThisExpr>(BaseE))
10432 // We found a base expression: this->Val.
10433 RelevantExpr = CurE;
10434 else
10435 E = BaseE;
10436
10437 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10438 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10439 << CurE->getSourceRange();
10440 break;
10441 }
10442
10443 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10444
10445 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10446 // A bit-field cannot appear in a map clause.
10447 //
10448 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010449 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10450 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010451 break;
10452 }
10453
10454 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10455 // If the type of a list item is a reference to a type T then the type
10456 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010457 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010458
10459 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10460 // A list item cannot be a variable that is a member of a structure with
10461 // a union type.
10462 //
10463 if (auto *RT = CurType->getAs<RecordType>())
10464 if (RT->isUnionType()) {
10465 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10466 << CurE->getSourceRange();
10467 break;
10468 }
10469
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010470 // If we got a member expression, we should not expect any array section
10471 // before that:
10472 //
10473 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10474 // If a list item is an element of a structure, only the rightmost symbol
10475 // of the variable reference can be an array section.
10476 //
10477 AllowUnitySizeArraySection = false;
10478 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010479
10480 // Record the component.
10481 CurComponents.push_back(
10482 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010483 continue;
10484 }
10485
10486 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10487 E = CurE->getBase()->IgnoreParenImpCasts();
10488
10489 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10490 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10491 << 0 << CurE->getSourceRange();
10492 break;
10493 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010494
10495 // If we got an array subscript that express the whole dimension we
10496 // can have any array expressions before. If it only expressing part of
10497 // the dimension, we can only have unitary-size array expressions.
10498 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10499 E->getType()))
10500 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010501
10502 // Record the component - we don't have any declaration associated.
10503 CurComponents.push_back(
10504 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010505 continue;
10506 }
10507
10508 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010509 E = CurE->getBase()->IgnoreParenImpCasts();
10510
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010511 auto CurType =
10512 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10513
Samuel Antao5de996e2016-01-22 20:21:36 +000010514 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10515 // If the type of a list item is a reference to a type T then the type
10516 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010517 if (CurType->isReferenceType())
10518 CurType = CurType->getPointeeType();
10519
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010520 bool IsPointer = CurType->isAnyPointerType();
10521
10522 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010523 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10524 << 0 << CurE->getSourceRange();
10525 break;
10526 }
10527
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010528 bool NotWhole =
10529 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10530 bool NotUnity =
10531 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10532
Samuel Antaodab51bb2016-07-18 23:22:11 +000010533 if (AllowWholeSizeArraySection) {
10534 // Any array section is currently allowed. Allowing a whole size array
10535 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010536 //
10537 // If this array section refers to the whole dimension we can still
10538 // accept other array sections before this one, except if the base is a
10539 // pointer. Otherwise, only unitary sections are accepted.
10540 if (NotWhole || IsPointer)
10541 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010542 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010543 // A unity or whole array section is not allowed and that is not
10544 // compatible with the properties of the current array section.
10545 SemaRef.Diag(
10546 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10547 << CurE->getSourceRange();
10548 break;
10549 }
Samuel Antao90927002016-04-26 14:54:23 +000010550
10551 // Record the component - we don't have any declaration associated.
10552 CurComponents.push_back(
10553 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010554 continue;
10555 }
10556
10557 // If nothing else worked, this is not a valid map clause expression.
10558 SemaRef.Diag(ELoc,
10559 diag::err_omp_expected_named_var_member_or_array_expression)
10560 << ERange;
10561 break;
10562 }
10563
10564 return RelevantExpr;
10565}
10566
10567// Return true if expression E associated with value VD has conflicts with other
10568// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010569static bool CheckMapConflicts(
10570 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10571 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010572 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10573 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010574 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010575 SourceLocation ELoc = E->getExprLoc();
10576 SourceRange ERange = E->getSourceRange();
10577
10578 // In order to easily check the conflicts we need to match each component of
10579 // the expression under test with the components of the expressions that are
10580 // already in the stack.
10581
Samuel Antao5de996e2016-01-22 20:21:36 +000010582 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010583 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010584 "Map clause expression with unexpected base!");
10585
10586 // Variables to help detecting enclosing problems in data environment nests.
10587 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010588 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010589
Samuel Antao90927002016-04-26 14:54:23 +000010590 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10591 VD, CurrentRegionOnly,
10592 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010593 StackComponents,
10594 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010595
Samuel Antao5de996e2016-01-22 20:21:36 +000010596 assert(!StackComponents.empty() &&
10597 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010598 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010599 "Map clause expression with unexpected base!");
10600
Samuel Antao90927002016-04-26 14:54:23 +000010601 // The whole expression in the stack.
10602 auto *RE = StackComponents.front().getAssociatedExpression();
10603
Samuel Antao5de996e2016-01-22 20:21:36 +000010604 // Expressions must start from the same base. Here we detect at which
10605 // point both expressions diverge from each other and see if we can
10606 // detect if the memory referred to both expressions is contiguous and
10607 // do not overlap.
10608 auto CI = CurComponents.rbegin();
10609 auto CE = CurComponents.rend();
10610 auto SI = StackComponents.rbegin();
10611 auto SE = StackComponents.rend();
10612 for (; CI != CE && SI != SE; ++CI, ++SI) {
10613
10614 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10615 // At most one list item can be an array item derived from a given
10616 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010617 if (CurrentRegionOnly &&
10618 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10619 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10620 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10621 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10622 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010623 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010624 << CI->getAssociatedExpression()->getSourceRange();
10625 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10626 diag::note_used_here)
10627 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010628 return true;
10629 }
10630
10631 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010632 if (CI->getAssociatedExpression()->getStmtClass() !=
10633 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010634 break;
10635
10636 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010637 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010638 break;
10639 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010640 // Check if the extra components of the expressions in the enclosing
10641 // data environment are redundant for the current base declaration.
10642 // If they are, the maps completely overlap, which is legal.
10643 for (; SI != SE; ++SI) {
10644 QualType Type;
10645 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010646 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010647 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010648 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10649 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010650 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10651 Type =
10652 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10653 }
10654 if (Type.isNull() || Type->isAnyPointerType() ||
10655 CheckArrayExpressionDoesNotReferToWholeSize(
10656 SemaRef, SI->getAssociatedExpression(), Type))
10657 break;
10658 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010659
10660 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10661 // List items of map clauses in the same construct must not share
10662 // original storage.
10663 //
10664 // If the expressions are exactly the same or one is a subset of the
10665 // other, it means they are sharing storage.
10666 if (CI == CE && SI == SE) {
10667 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010668 if (CKind == OMPC_map)
10669 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10670 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010671 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010672 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10673 << ERange;
10674 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010675 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10676 << RE->getSourceRange();
10677 return true;
10678 } else {
10679 // If we find the same expression in the enclosing data environment,
10680 // that is legal.
10681 IsEnclosedByDataEnvironmentExpr = true;
10682 return false;
10683 }
10684 }
10685
Samuel Antao90927002016-04-26 14:54:23 +000010686 QualType DerivedType =
10687 std::prev(CI)->getAssociatedDeclaration()->getType();
10688 SourceLocation DerivedLoc =
10689 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010690
10691 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10692 // If the type of a list item is a reference to a type T then the type
10693 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010694 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010695
10696 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10697 // A variable for which the type is pointer and an array section
10698 // derived from that variable must not appear as list items of map
10699 // clauses of the same construct.
10700 //
10701 // Also, cover one of the cases in:
10702 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10703 // If any part of the original storage of a list item has corresponding
10704 // storage in the device data environment, all of the original storage
10705 // must have corresponding storage in the device data environment.
10706 //
10707 if (DerivedType->isAnyPointerType()) {
10708 if (CI == CE || SI == SE) {
10709 SemaRef.Diag(
10710 DerivedLoc,
10711 diag::err_omp_pointer_mapped_along_with_derived_section)
10712 << DerivedLoc;
10713 } else {
10714 assert(CI != CE && SI != SE);
10715 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10716 << DerivedLoc;
10717 }
10718 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10719 << RE->getSourceRange();
10720 return true;
10721 }
10722
10723 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10724 // List items of map clauses in the same construct must not share
10725 // original storage.
10726 //
10727 // An expression is a subset of the other.
10728 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010729 if (CKind == OMPC_map)
10730 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10731 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010732 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010733 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10734 << ERange;
10735 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010736 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10737 << RE->getSourceRange();
10738 return true;
10739 }
10740
10741 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010742 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010743 if (!CurrentRegionOnly && SI != SE)
10744 EnclosingExpr = RE;
10745
10746 // The current expression is a subset of the expression in the data
10747 // environment.
10748 IsEnclosedByDataEnvironmentExpr |=
10749 (!CurrentRegionOnly && CI != CE && SI == SE);
10750
10751 return false;
10752 });
10753
10754 if (CurrentRegionOnly)
10755 return FoundError;
10756
10757 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10758 // If any part of the original storage of a list item has corresponding
10759 // storage in the device data environment, all of the original storage must
10760 // have corresponding storage in the device data environment.
10761 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10762 // If a list item is an element of a structure, and a different element of
10763 // the structure has a corresponding list item in the device data environment
10764 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010765 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010766 // data environment prior to the task encountering the construct.
10767 //
10768 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10769 SemaRef.Diag(ELoc,
10770 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10771 << ERange;
10772 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10773 << EnclosingExpr->getSourceRange();
10774 return true;
10775 }
10776
10777 return FoundError;
10778}
10779
Samuel Antao661c0902016-05-26 17:39:58 +000010780namespace {
10781// Utility struct that gathers all the related lists associated with a mappable
10782// expression.
10783struct MappableVarListInfo final {
10784 // The list of expressions.
10785 ArrayRef<Expr *> VarList;
10786 // The list of processed expressions.
10787 SmallVector<Expr *, 16> ProcessedVarList;
10788 // The mappble components for each expression.
10789 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10790 // The base declaration of the variable.
10791 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10792
10793 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10794 // We have a list of components and base declarations for each entry in the
10795 // variable list.
10796 VarComponents.reserve(VarList.size());
10797 VarBaseDeclarations.reserve(VarList.size());
10798 }
10799};
10800}
10801
10802// Check the validity of the provided variable list for the provided clause kind
10803// \a CKind. In the check process the valid expressions, and mappable expression
10804// components and variables are extracted and used to fill \a Vars,
10805// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10806// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10807static void
10808checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10809 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10810 SourceLocation StartLoc,
10811 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10812 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010813 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10814 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010815 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010816
Samuel Antao90927002016-04-26 14:54:23 +000010817 // Keep track of the mappable components and base declarations in this clause.
10818 // Each entry in the list is going to have a list of components associated. We
10819 // record each set of the components so that we can build the clause later on.
10820 // In the end we should have the same amount of declarations and component
10821 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010822
Samuel Antao661c0902016-05-26 17:39:58 +000010823 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010824 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010825 SourceLocation ELoc = RE->getExprLoc();
10826
Kelvin Li0bff7af2015-11-23 05:32:03 +000010827 auto *VE = RE->IgnoreParenLValueCasts();
10828
10829 if (VE->isValueDependent() || VE->isTypeDependent() ||
10830 VE->isInstantiationDependent() ||
10831 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010832 // We can only analyze this information once the missing information is
10833 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010834 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010835 continue;
10836 }
10837
10838 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010839
Samuel Antao5de996e2016-01-22 20:21:36 +000010840 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010841 SemaRef.Diag(ELoc,
10842 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010843 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010844 continue;
10845 }
10846
Samuel Antao90927002016-04-26 14:54:23 +000010847 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10848 ValueDecl *CurDeclaration = nullptr;
10849
10850 // Obtain the array or member expression bases if required. Also, fill the
10851 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010852 auto *BE =
10853 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010854 if (!BE)
10855 continue;
10856
Samuel Antao90927002016-04-26 14:54:23 +000010857 assert(!CurComponents.empty() &&
10858 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010859
Samuel Antao90927002016-04-26 14:54:23 +000010860 // For the following checks, we rely on the base declaration which is
10861 // expected to be associated with the last component. The declaration is
10862 // expected to be a variable or a field (if 'this' is being mapped).
10863 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10864 assert(CurDeclaration && "Null decl on map clause.");
10865 assert(
10866 CurDeclaration->isCanonicalDecl() &&
10867 "Expecting components to have associated only canonical declarations.");
10868
10869 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10870 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010871
10872 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010873 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010874
10875 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010876 // threadprivate variables cannot appear in a map clause.
10877 // OpenMP 4.5 [2.10.5, target update Construct]
10878 // threadprivate variables cannot appear in a from clause.
10879 if (VD && DSAS->isThreadPrivate(VD)) {
10880 auto DVar = DSAS->getTopDSA(VD, false);
10881 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10882 << getOpenMPClauseName(CKind);
10883 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010884 continue;
10885 }
10886
Samuel Antao5de996e2016-01-22 20:21:36 +000010887 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10888 // A list item cannot appear in both a map clause and a data-sharing
10889 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010890
Samuel Antao5de996e2016-01-22 20:21:36 +000010891 // Check conflicts with other map clause expressions. We check the conflicts
10892 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010893 // environment, because the restrictions are different. We only have to
10894 // check conflicts across regions for the map clauses.
10895 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10896 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010897 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010898 if (CKind == OMPC_map &&
10899 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10900 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010901 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010902
Samuel Antao661c0902016-05-26 17:39:58 +000010903 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010904 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10905 // If the type of a list item is a reference to a type T then the type will
10906 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010907 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010908
Samuel Antao661c0902016-05-26 17:39:58 +000010909 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10910 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010911 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010912 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010913 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10914 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010915 continue;
10916
Samuel Antao661c0902016-05-26 17:39:58 +000010917 if (CKind == OMPC_map) {
10918 // target enter data
10919 // OpenMP [2.10.2, Restrictions, p. 99]
10920 // A map-type must be specified in all map clauses and must be either
10921 // to or alloc.
10922 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10923 if (DKind == OMPD_target_enter_data &&
10924 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10925 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10926 << (IsMapTypeImplicit ? 1 : 0)
10927 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10928 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010929 continue;
10930 }
Samuel Antao661c0902016-05-26 17:39:58 +000010931
10932 // target exit_data
10933 // OpenMP [2.10.3, Restrictions, p. 102]
10934 // A map-type must be specified in all map clauses and must be either
10935 // from, release, or delete.
10936 if (DKind == OMPD_target_exit_data &&
10937 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10938 MapType == OMPC_MAP_delete)) {
10939 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10940 << (IsMapTypeImplicit ? 1 : 0)
10941 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10942 << getOpenMPDirectiveName(DKind);
10943 continue;
10944 }
10945
10946 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10947 // A list item cannot appear in both a map clause and a data-sharing
10948 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010949 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010950 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010951 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010952 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10953 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010954 auto DVar = DSAS->getTopDSA(VD, false);
10955 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010956 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010957 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010958 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010959 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10960 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10961 continue;
10962 }
10963 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010964 }
10965
Samuel Antao90927002016-04-26 14:54:23 +000010966 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010967 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010968
10969 // Store the components in the stack so that they can be used to check
10970 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010971 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10972 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010973
10974 // Save the components and declaration to create the clause. For purposes of
10975 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010976 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010977 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10978 MVLI.VarComponents.back().append(CurComponents.begin(),
10979 CurComponents.end());
10980 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10981 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010982 }
Samuel Antao661c0902016-05-26 17:39:58 +000010983}
10984
10985OMPClause *
10986Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10987 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10988 SourceLocation MapLoc, SourceLocation ColonLoc,
10989 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10990 SourceLocation LParenLoc, SourceLocation EndLoc) {
10991 MappableVarListInfo MVLI(VarList);
10992 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10993 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010994
Samuel Antao5de996e2016-01-22 20:21:36 +000010995 // We need to produce a map clause even if we don't have variables so that
10996 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010997 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10998 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10999 MVLI.VarComponents, MapTypeModifier, MapType,
11000 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011001}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011002
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011003QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11004 TypeResult ParsedType) {
11005 assert(ParsedType.isUsable());
11006
11007 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11008 if (ReductionType.isNull())
11009 return QualType();
11010
11011 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11012 // A type name in a declare reduction directive cannot be a function type, an
11013 // array type, a reference type, or a type qualified with const, volatile or
11014 // restrict.
11015 if (ReductionType.hasQualifiers()) {
11016 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11017 return QualType();
11018 }
11019
11020 if (ReductionType->isFunctionType()) {
11021 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11022 return QualType();
11023 }
11024 if (ReductionType->isReferenceType()) {
11025 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11026 return QualType();
11027 }
11028 if (ReductionType->isArrayType()) {
11029 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11030 return QualType();
11031 }
11032 return ReductionType;
11033}
11034
11035Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11036 Scope *S, DeclContext *DC, DeclarationName Name,
11037 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11038 AccessSpecifier AS, Decl *PrevDeclInScope) {
11039 SmallVector<Decl *, 8> Decls;
11040 Decls.reserve(ReductionTypes.size());
11041
11042 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11043 ForRedeclaration);
11044 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11045 // A reduction-identifier may not be re-declared in the current scope for the
11046 // same type or for a type that is compatible according to the base language
11047 // rules.
11048 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11049 OMPDeclareReductionDecl *PrevDRD = nullptr;
11050 bool InCompoundScope = true;
11051 if (S != nullptr) {
11052 // Find previous declaration with the same name not referenced in other
11053 // declarations.
11054 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11055 InCompoundScope =
11056 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11057 LookupName(Lookup, S);
11058 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11059 /*AllowInlineNamespace=*/false);
11060 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11061 auto Filter = Lookup.makeFilter();
11062 while (Filter.hasNext()) {
11063 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11064 if (InCompoundScope) {
11065 auto I = UsedAsPrevious.find(PrevDecl);
11066 if (I == UsedAsPrevious.end())
11067 UsedAsPrevious[PrevDecl] = false;
11068 if (auto *D = PrevDecl->getPrevDeclInScope())
11069 UsedAsPrevious[D] = true;
11070 }
11071 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11072 PrevDecl->getLocation();
11073 }
11074 Filter.done();
11075 if (InCompoundScope) {
11076 for (auto &PrevData : UsedAsPrevious) {
11077 if (!PrevData.second) {
11078 PrevDRD = PrevData.first;
11079 break;
11080 }
11081 }
11082 }
11083 } else if (PrevDeclInScope != nullptr) {
11084 auto *PrevDRDInScope = PrevDRD =
11085 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11086 do {
11087 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11088 PrevDRDInScope->getLocation();
11089 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11090 } while (PrevDRDInScope != nullptr);
11091 }
11092 for (auto &TyData : ReductionTypes) {
11093 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11094 bool Invalid = false;
11095 if (I != PreviousRedeclTypes.end()) {
11096 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11097 << TyData.first;
11098 Diag(I->second, diag::note_previous_definition);
11099 Invalid = true;
11100 }
11101 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11102 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11103 Name, TyData.first, PrevDRD);
11104 DC->addDecl(DRD);
11105 DRD->setAccess(AS);
11106 Decls.push_back(DRD);
11107 if (Invalid)
11108 DRD->setInvalidDecl();
11109 else
11110 PrevDRD = DRD;
11111 }
11112
11113 return DeclGroupPtrTy::make(
11114 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11115}
11116
11117void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11118 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11119
11120 // Enter new function scope.
11121 PushFunctionScope();
11122 getCurFunction()->setHasBranchProtectedScope();
11123 getCurFunction()->setHasOMPDeclareReductionCombiner();
11124
11125 if (S != nullptr)
11126 PushDeclContext(S, DRD);
11127 else
11128 CurContext = DRD;
11129
Faisal Valid143a0c2017-04-01 21:30:49 +000011130 PushExpressionEvaluationContext(
11131 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011132
11133 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011134 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11135 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11136 // uses semantics of argument handles by value, but it should be passed by
11137 // reference. C lang does not support references, so pass all parameters as
11138 // pointers.
11139 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011140 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011141 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011142 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11143 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11144 // uses semantics of argument handles by value, but it should be passed by
11145 // reference. C lang does not support references, so pass all parameters as
11146 // pointers.
11147 // Create 'T omp_out;' variable.
11148 auto *OmpOutParm =
11149 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11150 if (S != nullptr) {
11151 PushOnScopeChains(OmpInParm, S);
11152 PushOnScopeChains(OmpOutParm, S);
11153 } else {
11154 DRD->addDecl(OmpInParm);
11155 DRD->addDecl(OmpOutParm);
11156 }
11157}
11158
11159void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11160 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11161 DiscardCleanupsInEvaluationContext();
11162 PopExpressionEvaluationContext();
11163
11164 PopDeclContext();
11165 PopFunctionScopeInfo();
11166
11167 if (Combiner != nullptr)
11168 DRD->setCombiner(Combiner);
11169 else
11170 DRD->setInvalidDecl();
11171}
11172
11173void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11174 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11175
11176 // Enter new function scope.
11177 PushFunctionScope();
11178 getCurFunction()->setHasBranchProtectedScope();
11179
11180 if (S != nullptr)
11181 PushDeclContext(S, DRD);
11182 else
11183 CurContext = DRD;
11184
Faisal Valid143a0c2017-04-01 21:30:49 +000011185 PushExpressionEvaluationContext(
11186 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011187
11188 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011189 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11190 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11191 // uses semantics of argument handles by value, but it should be passed by
11192 // reference. C lang does not support references, so pass all parameters as
11193 // pointers.
11194 // Create 'T omp_priv;' variable.
11195 auto *OmpPrivParm =
11196 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011197 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11198 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11199 // uses semantics of argument handles by value, but it should be passed by
11200 // reference. C lang does not support references, so pass all parameters as
11201 // pointers.
11202 // Create 'T omp_orig;' variable.
11203 auto *OmpOrigParm =
11204 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011205 if (S != nullptr) {
11206 PushOnScopeChains(OmpPrivParm, S);
11207 PushOnScopeChains(OmpOrigParm, S);
11208 } else {
11209 DRD->addDecl(OmpPrivParm);
11210 DRD->addDecl(OmpOrigParm);
11211 }
11212}
11213
11214void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11215 Expr *Initializer) {
11216 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11217 DiscardCleanupsInEvaluationContext();
11218 PopExpressionEvaluationContext();
11219
11220 PopDeclContext();
11221 PopFunctionScopeInfo();
11222
11223 if (Initializer != nullptr)
11224 DRD->setInitializer(Initializer);
11225 else
11226 DRD->setInvalidDecl();
11227}
11228
11229Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11230 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11231 for (auto *D : DeclReductions.get()) {
11232 if (IsValid) {
11233 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11234 if (S != nullptr)
11235 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11236 } else
11237 D->setInvalidDecl();
11238 }
11239 return DeclReductions;
11240}
11241
David Majnemer9d168222016-08-05 17:44:54 +000011242OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011243 SourceLocation StartLoc,
11244 SourceLocation LParenLoc,
11245 SourceLocation EndLoc) {
11246 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011247 Stmt *HelperValStmt = nullptr;
11248 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011249
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011250 // OpenMP [teams Constrcut, Restrictions]
11251 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011252 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11253 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011254 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011255
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011256 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11257 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11258 if (CaptureRegion != OMPD_unknown) {
11259 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11260 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11261 HelperValStmt = buildPreInits(Context, Captures);
11262 }
11263
11264 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11265 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011266}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011267
11268OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11269 SourceLocation StartLoc,
11270 SourceLocation LParenLoc,
11271 SourceLocation EndLoc) {
11272 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011273 Stmt *HelperValStmt = nullptr;
11274 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011275
11276 // OpenMP [teams Constrcut, Restrictions]
11277 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011278 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11279 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011280 return nullptr;
11281
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011282 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11283 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11284 if (CaptureRegion != OMPD_unknown) {
11285 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11286 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11287 HelperValStmt = buildPreInits(Context, Captures);
11288 }
11289
11290 return new (Context) OMPThreadLimitClause(
11291 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011292}
Alexey Bataeva0569352015-12-01 10:17:31 +000011293
11294OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11295 SourceLocation StartLoc,
11296 SourceLocation LParenLoc,
11297 SourceLocation EndLoc) {
11298 Expr *ValExpr = Priority;
11299
11300 // OpenMP [2.9.1, task Constrcut]
11301 // The priority-value is a non-negative numerical scalar expression.
11302 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11303 /*StrictlyPositive=*/false))
11304 return nullptr;
11305
11306 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11307}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011308
11309OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11310 SourceLocation StartLoc,
11311 SourceLocation LParenLoc,
11312 SourceLocation EndLoc) {
11313 Expr *ValExpr = Grainsize;
11314
11315 // OpenMP [2.9.2, taskloop Constrcut]
11316 // The parameter of the grainsize clause must be a positive integer
11317 // expression.
11318 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11319 /*StrictlyPositive=*/true))
11320 return nullptr;
11321
11322 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11323}
Alexey Bataev382967a2015-12-08 12:06:20 +000011324
11325OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11326 SourceLocation StartLoc,
11327 SourceLocation LParenLoc,
11328 SourceLocation EndLoc) {
11329 Expr *ValExpr = NumTasks;
11330
11331 // OpenMP [2.9.2, taskloop Constrcut]
11332 // The parameter of the num_tasks clause must be a positive integer
11333 // expression.
11334 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11335 /*StrictlyPositive=*/true))
11336 return nullptr;
11337
11338 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11339}
11340
Alexey Bataev28c75412015-12-15 08:19:24 +000011341OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11342 SourceLocation LParenLoc,
11343 SourceLocation EndLoc) {
11344 // OpenMP [2.13.2, critical construct, Description]
11345 // ... where hint-expression is an integer constant expression that evaluates
11346 // to a valid lock hint.
11347 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11348 if (HintExpr.isInvalid())
11349 return nullptr;
11350 return new (Context)
11351 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11352}
11353
Carlo Bertollib4adf552016-01-15 18:50:31 +000011354OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11355 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11356 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11357 SourceLocation EndLoc) {
11358 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11359 std::string Values;
11360 Values += "'";
11361 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11362 Values += "'";
11363 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11364 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11365 return nullptr;
11366 }
11367 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011368 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011369 if (ChunkSize) {
11370 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11371 !ChunkSize->isInstantiationDependent() &&
11372 !ChunkSize->containsUnexpandedParameterPack()) {
11373 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11374 ExprResult Val =
11375 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11376 if (Val.isInvalid())
11377 return nullptr;
11378
11379 ValExpr = Val.get();
11380
11381 // OpenMP [2.7.1, Restrictions]
11382 // chunk_size must be a loop invariant integer expression with a positive
11383 // value.
11384 llvm::APSInt Result;
11385 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11386 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11387 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11388 << "dist_schedule" << ChunkSize->getSourceRange();
11389 return nullptr;
11390 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011391 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11392 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011393 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11394 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11395 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011396 }
11397 }
11398 }
11399
11400 return new (Context)
11401 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011402 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011403}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011404
11405OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11406 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11407 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11408 SourceLocation KindLoc, SourceLocation EndLoc) {
11409 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011410 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011411 std::string Value;
11412 SourceLocation Loc;
11413 Value += "'";
11414 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11415 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011416 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011417 Loc = MLoc;
11418 } else {
11419 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011420 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011421 Loc = KindLoc;
11422 }
11423 Value += "'";
11424 Diag(Loc, diag::err_omp_unexpected_clause_value)
11425 << Value << getOpenMPClauseName(OMPC_defaultmap);
11426 return nullptr;
11427 }
11428
11429 return new (Context)
11430 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11431}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011432
11433bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11434 DeclContext *CurLexicalContext = getCurLexicalContext();
11435 if (!CurLexicalContext->isFileContext() &&
11436 !CurLexicalContext->isExternCContext() &&
11437 !CurLexicalContext->isExternCXXContext()) {
11438 Diag(Loc, diag::err_omp_region_not_file_context);
11439 return false;
11440 }
11441 if (IsInOpenMPDeclareTargetContext) {
11442 Diag(Loc, diag::err_omp_enclosed_declare_target);
11443 return false;
11444 }
11445
11446 IsInOpenMPDeclareTargetContext = true;
11447 return true;
11448}
11449
11450void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11451 assert(IsInOpenMPDeclareTargetContext &&
11452 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11453
11454 IsInOpenMPDeclareTargetContext = false;
11455}
11456
David Majnemer9d168222016-08-05 17:44:54 +000011457void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11458 CXXScopeSpec &ScopeSpec,
11459 const DeclarationNameInfo &Id,
11460 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11461 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011462 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11463 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11464
11465 if (Lookup.isAmbiguous())
11466 return;
11467 Lookup.suppressDiagnostics();
11468
11469 if (!Lookup.isSingleResult()) {
11470 if (TypoCorrection Corrected =
11471 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11472 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11473 CTK_ErrorRecovery)) {
11474 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11475 << Id.getName());
11476 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11477 return;
11478 }
11479
11480 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11481 return;
11482 }
11483
11484 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11485 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11486 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11487 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11488
11489 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11490 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11491 ND->addAttr(A);
11492 if (ASTMutationListener *ML = Context.getASTMutationListener())
11493 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11494 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11495 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11496 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11497 << Id.getName();
11498 }
11499 } else
11500 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11501}
11502
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011503static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11504 Sema &SemaRef, Decl *D) {
11505 if (!D)
11506 return;
11507 Decl *LD = nullptr;
11508 if (isa<TagDecl>(D)) {
11509 LD = cast<TagDecl>(D)->getDefinition();
11510 } else if (isa<VarDecl>(D)) {
11511 LD = cast<VarDecl>(D)->getDefinition();
11512
11513 // If this is an implicit variable that is legal and we do not need to do
11514 // anything.
11515 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011516 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11517 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11518 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011519 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011520 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011521 return;
11522 }
11523
11524 } else if (isa<FunctionDecl>(D)) {
11525 const FunctionDecl *FD = nullptr;
11526 if (cast<FunctionDecl>(D)->hasBody(FD))
11527 LD = const_cast<FunctionDecl *>(FD);
11528
11529 // If the definition is associated with the current declaration in the
11530 // target region (it can be e.g. a lambda) that is legal and we do not need
11531 // to do anything else.
11532 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011533 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11534 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11535 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011536 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011537 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011538 return;
11539 }
11540 }
11541 if (!LD)
11542 LD = D;
11543 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11544 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11545 // Outlined declaration is not declared target.
11546 if (LD->isOutOfLine()) {
11547 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11548 SemaRef.Diag(SL, diag::note_used_here) << SR;
11549 } else {
11550 DeclContext *DC = LD->getDeclContext();
11551 while (DC) {
11552 if (isa<FunctionDecl>(DC) &&
11553 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11554 break;
11555 DC = DC->getParent();
11556 }
11557 if (DC)
11558 return;
11559
11560 // Is not declared in target context.
11561 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11562 SemaRef.Diag(SL, diag::note_used_here) << SR;
11563 }
11564 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011565 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11566 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11567 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011568 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011569 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011570 }
11571}
11572
11573static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11574 Sema &SemaRef, DSAStackTy *Stack,
11575 ValueDecl *VD) {
11576 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11577 return true;
11578 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11579 return false;
11580 return true;
11581}
11582
11583void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11584 if (!D || D->isInvalidDecl())
11585 return;
11586 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11587 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11588 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11589 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11590 if (DSAStack->isThreadPrivate(VD)) {
11591 Diag(SL, diag::err_omp_threadprivate_in_target);
11592 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11593 return;
11594 }
11595 }
11596 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11597 // Problem if any with var declared with incomplete type will be reported
11598 // as normal, so no need to check it here.
11599 if ((E || !VD->getType()->isIncompleteType()) &&
11600 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11601 // Mark decl as declared target to prevent further diagnostic.
11602 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011603 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11604 Context, OMPDeclareTargetDeclAttr::MT_To);
11605 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011606 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011607 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011608 }
11609 return;
11610 }
11611 }
11612 if (!E) {
11613 // Checking declaration inside declare target region.
11614 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11615 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011616 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11617 Context, OMPDeclareTargetDeclAttr::MT_To);
11618 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011619 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011620 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011621 }
11622 return;
11623 }
11624 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11625}
Samuel Antao661c0902016-05-26 17:39:58 +000011626
11627OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11628 SourceLocation StartLoc,
11629 SourceLocation LParenLoc,
11630 SourceLocation EndLoc) {
11631 MappableVarListInfo MVLI(VarList);
11632 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11633 if (MVLI.ProcessedVarList.empty())
11634 return nullptr;
11635
11636 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11637 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11638 MVLI.VarComponents);
11639}
Samuel Antaoec172c62016-05-26 17:49:04 +000011640
11641OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11642 SourceLocation StartLoc,
11643 SourceLocation LParenLoc,
11644 SourceLocation EndLoc) {
11645 MappableVarListInfo MVLI(VarList);
11646 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11647 if (MVLI.ProcessedVarList.empty())
11648 return nullptr;
11649
11650 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11651 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11652 MVLI.VarComponents);
11653}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011654
11655OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11656 SourceLocation StartLoc,
11657 SourceLocation LParenLoc,
11658 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011659 MappableVarListInfo MVLI(VarList);
11660 SmallVector<Expr *, 8> PrivateCopies;
11661 SmallVector<Expr *, 8> Inits;
11662
Carlo Bertolli2404b172016-07-13 15:37:16 +000011663 for (auto &RefExpr : VarList) {
11664 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11665 SourceLocation ELoc;
11666 SourceRange ERange;
11667 Expr *SimpleRefExpr = RefExpr;
11668 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11669 if (Res.second) {
11670 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011671 MVLI.ProcessedVarList.push_back(RefExpr);
11672 PrivateCopies.push_back(nullptr);
11673 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011674 }
11675 ValueDecl *D = Res.first;
11676 if (!D)
11677 continue;
11678
11679 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011680 Type = Type.getNonReferenceType().getUnqualifiedType();
11681
11682 auto *VD = dyn_cast<VarDecl>(D);
11683
11684 // Item should be a pointer or reference to pointer.
11685 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011686 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11687 << 0 << RefExpr->getSourceRange();
11688 continue;
11689 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011690
11691 // Build the private variable and the expression that refers to it.
11692 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11693 D->hasAttrs() ? &D->getAttrs() : nullptr);
11694 if (VDPrivate->isInvalidDecl())
11695 continue;
11696
11697 CurContext->addDecl(VDPrivate);
11698 auto VDPrivateRefExpr = buildDeclRefExpr(
11699 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11700
11701 // Add temporary variable to initialize the private copy of the pointer.
11702 auto *VDInit =
11703 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11704 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11705 RefExpr->getExprLoc());
11706 AddInitializerToDecl(VDPrivate,
11707 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011708 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011709
11710 // If required, build a capture to implement the privatization initialized
11711 // with the current list item value.
11712 DeclRefExpr *Ref = nullptr;
11713 if (!VD)
11714 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11715 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11716 PrivateCopies.push_back(VDPrivateRefExpr);
11717 Inits.push_back(VDInitRefExpr);
11718
11719 // We need to add a data sharing attribute for this variable to make sure it
11720 // is correctly captured. A variable that shows up in a use_device_ptr has
11721 // similar properties of a first private variable.
11722 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11723
11724 // Create a mappable component for the list item. List items in this clause
11725 // only need a component.
11726 MVLI.VarBaseDeclarations.push_back(D);
11727 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11728 MVLI.VarComponents.back().push_back(
11729 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011730 }
11731
Samuel Antaocc10b852016-07-28 14:23:26 +000011732 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011733 return nullptr;
11734
Samuel Antaocc10b852016-07-28 14:23:26 +000011735 return OMPUseDevicePtrClause::Create(
11736 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11737 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011738}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011739
11740OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11741 SourceLocation StartLoc,
11742 SourceLocation LParenLoc,
11743 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011744 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011745 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011746 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011747 SourceLocation ELoc;
11748 SourceRange ERange;
11749 Expr *SimpleRefExpr = RefExpr;
11750 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11751 if (Res.second) {
11752 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011753 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011754 }
11755 ValueDecl *D = Res.first;
11756 if (!D)
11757 continue;
11758
11759 QualType Type = D->getType();
11760 // item should be a pointer or array or reference to pointer or array
11761 if (!Type.getNonReferenceType()->isPointerType() &&
11762 !Type.getNonReferenceType()->isArrayType()) {
11763 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11764 << 0 << RefExpr->getSourceRange();
11765 continue;
11766 }
Samuel Antao6890b092016-07-28 14:25:09 +000011767
11768 // Check if the declaration in the clause does not show up in any data
11769 // sharing attribute.
11770 auto DVar = DSAStack->getTopDSA(D, false);
11771 if (isOpenMPPrivate(DVar.CKind)) {
11772 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11773 << getOpenMPClauseName(DVar.CKind)
11774 << getOpenMPClauseName(OMPC_is_device_ptr)
11775 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11776 ReportOriginalDSA(*this, DSAStack, D, DVar);
11777 continue;
11778 }
11779
11780 Expr *ConflictExpr;
11781 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011782 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011783 [&ConflictExpr](
11784 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11785 OpenMPClauseKind) -> bool {
11786 ConflictExpr = R.front().getAssociatedExpression();
11787 return true;
11788 })) {
11789 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11790 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11791 << ConflictExpr->getSourceRange();
11792 continue;
11793 }
11794
11795 // Store the components in the stack so that they can be used to check
11796 // against other clauses later on.
11797 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11798 DSAStack->addMappableExpressionComponents(
11799 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11800
11801 // Record the expression we've just processed.
11802 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11803
11804 // Create a mappable component for the list item. List items in this clause
11805 // only need a component. We use a null declaration to signal fields in
11806 // 'this'.
11807 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11808 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11809 "Unexpected device pointer expression!");
11810 MVLI.VarBaseDeclarations.push_back(
11811 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11812 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11813 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011814 }
11815
Samuel Antao6890b092016-07-28 14:25:09 +000011816 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011817 return nullptr;
11818
Samuel Antao6890b092016-07-28 14:25:09 +000011819 return OMPIsDevicePtrClause::Create(
11820 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11821 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011822}