blob: 9c6948b90269f2fae3ac152b36765a3eddd9c566 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000121 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000122 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
123 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000124 /// \brief true, if check for DSA must be from parent directive, false, if
125 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000127 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000129 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130
131 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
132
David Majnemer9d168222016-08-05 17:44:54 +0000133 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000134
135 /// \brief Checks if the variable is a local for OpenMP region.
136 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000137
Alexey Bataev4b465392017-04-26 15:06:24 +0000138 bool isStackEmpty() const {
139 return Stack.empty() ||
140 Stack.back().second != CurrentNonCapturingFunctionScope ||
141 Stack.back().first.empty();
142 }
143
Alexey Bataev758e55e2013-09-06 18:03:48 +0000144public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000145 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000146
Alexey Bataevaac108a2015-06-23 04:51:00 +0000147 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
148 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000150 bool isForceVarCapturing() const { return ForceCapturing; }
151 void setForceVarCapturing(bool V) { ForceCapturing = V; }
152
Alexey Bataev758e55e2013-09-06 18:03:48 +0000153 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000154 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 if (Stack.empty() ||
156 Stack.back().second != CurrentNonCapturingFunctionScope)
157 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
158 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
159 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 }
161
162 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000163 assert(!Stack.back().first.empty() &&
164 "Data-sharing attributes stack is empty!");
165 Stack.back().first.pop_back();
166 }
167
168 /// Start new OpenMP region stack in new non-capturing function.
169 void pushFunction() {
170 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
171 assert(!isa<CapturingScopeInfo>(CurFnScope));
172 CurrentNonCapturingFunctionScope = CurFnScope;
173 }
174 /// Pop region stack for non-capturing function.
175 void popFunction(const FunctionScopeInfo *OldFSI) {
176 if (!Stack.empty() && Stack.back().second == OldFSI) {
177 assert(Stack.back().first.empty());
178 Stack.pop_back();
179 }
180 CurrentNonCapturingFunctionScope = nullptr;
181 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
182 if (!isa<CapturingScopeInfo>(FSI)) {
183 CurrentNonCapturingFunctionScope = FSI;
184 break;
185 }
186 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 }
188
Alexey Bataev28c75412015-12-15 08:19:24 +0000189 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
190 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
191 }
192 const std::pair<OMPCriticalDirective *, llvm::APSInt>
193 getCriticalWithHint(const DeclarationNameInfo &Name) const {
194 auto I = Criticals.find(Name.getAsString());
195 if (I != Criticals.end())
196 return I->second;
197 return std::make_pair(nullptr, llvm::APSInt());
198 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000199 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000200 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000201 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000202 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000203
Alexey Bataev9c821032015-04-30 04:23:23 +0000204 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000205 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000206 /// \brief Check if the specified variable is a loop control variable for
207 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000208 /// \return The index of the loop control variable in the list of associated
209 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000210 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000211 /// \brief Check if the specified variable is a loop control variable for
212 /// parent region.
213 /// \return The index of the loop control variable in the list of associated
214 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000215 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000216 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
217 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000218 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000219
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000221 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
222 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000223
Alexey Bataev758e55e2013-09-06 18:03:48 +0000224 /// \brief Returns data sharing attributes from top of the stack for the
225 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000226 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000227 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000228 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000229 /// \brief Checks if the specified variables has data-sharing attributes which
230 /// match specified \a CPred predicate in any directive which matches \a DPred
231 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000232 DSAVarData hasDSA(ValueDecl *D,
233 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
234 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
235 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000236 /// \brief Checks if the specified variables has data-sharing attributes which
237 /// match specified \a CPred predicate in any innermost directive which
238 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000239 DSAVarData
240 hasInnermostDSA(ValueDecl *D,
241 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
242 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
243 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000244 /// \brief Checks if the specified variables has explicit data-sharing
245 /// attributes which match specified \a CPred predicate at the specified
246 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000247 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000248 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000249 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000250
251 /// \brief Returns true if the directive at level \Level matches in the
252 /// specified \a DPred predicate.
253 bool hasExplicitDirective(
254 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
255 unsigned Level);
256
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000257 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000258 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
259 const DeclarationNameInfo &,
260 SourceLocation)> &DPred,
261 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000262
Alexey Bataev758e55e2013-09-06 18:03:48 +0000263 /// \brief Returns currently analyzed directive.
264 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000265 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000267 /// \brief Returns parent directive.
268 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000269 if (isStackEmpty() || Stack.back().first.size() == 1)
270 return OMPD_unknown;
271 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000272 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273
274 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000275 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000276 assert(!isStackEmpty());
277 Stack.back().first.back().DefaultAttr = DSA_none;
278 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000279 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000280 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000281 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000282 assert(!isStackEmpty());
283 Stack.back().first.back().DefaultAttr = DSA_shared;
284 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000285 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000286
287 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000288 return isStackEmpty() ? DSA_unspecified
289 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000291 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000292 return isStackEmpty() ? SourceLocation()
293 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000294 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000295
Alexey Bataevf29276e2014-06-18 04:14:57 +0000296 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000297 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000298 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000299 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000300 }
301
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000303 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000304 assert(!isStackEmpty());
305 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
306 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000307 }
308 /// \brief Returns true, if parent region is ordered (has associated
309 /// 'ordered' clause), false - otherwise.
310 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000311 if (isStackEmpty() || Stack.back().first.size() == 1)
312 return false;
313 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000314 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000315 /// \brief Returns optional parameter for the ordered region.
316 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000317 if (isStackEmpty() || Stack.back().first.size() == 1)
318 return nullptr;
319 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000320 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000321 /// \brief Marks current region as nowait (it has a 'nowait' clause).
322 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000323 assert(!isStackEmpty());
324 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000325 }
326 /// \brief Returns true, if parent region is nowait (has associated
327 /// 'nowait' clause), false - otherwise.
328 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000329 if (isStackEmpty() || Stack.back().first.size() == 1)
330 return false;
331 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000332 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000333 /// \brief Marks parent region as cancel region.
334 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 if (!isStackEmpty() && Stack.back().first.size() > 1) {
336 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
337 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
338 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000339 }
340 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000341 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000342 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000343 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000344
Alexey Bataev9c821032015-04-30 04:23:23 +0000345 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000346 void setAssociatedLoops(unsigned Val) {
347 assert(!isStackEmpty());
348 Stack.back().first.back().AssociatedLoops = Val;
349 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000350 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000351 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000352 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000353 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000354
Alexey Bataev13314bf2014-10-09 04:18:56 +0000355 /// \brief Marks current target region as one with closely nested teams
356 /// region.
357 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000358 if (!isStackEmpty() && Stack.back().first.size() > 1) {
359 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
360 TeamsRegionLoc;
361 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000362 }
363 /// \brief Returns true, if current region has closely nested teams region.
364 bool hasInnerTeamsRegion() const {
365 return getInnerTeamsRegionLoc().isValid();
366 }
367 /// \brief Returns location of the nested teams region (if any).
368 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000369 return isStackEmpty() ? SourceLocation()
370 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000371 }
372
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000373 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000374 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000375 }
376 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000377 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000378 }
379 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000380 return isStackEmpty() ? SourceLocation()
381 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000382 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000383
Samuel Antao4c8035b2016-12-12 18:00:20 +0000384 /// Do the check specified in \a Check to all component lists and return true
385 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000386 bool checkMappableExprComponentListsForDecl(
387 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000388 const llvm::function_ref<
389 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
390 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000391 if (isStackEmpty())
392 return false;
393 auto SI = Stack.back().first.rbegin();
394 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000395
396 if (SI == SE)
397 return false;
398
399 if (CurrentRegionOnly) {
400 SE = std::next(SI);
401 } else {
402 ++SI;
403 }
404
405 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000406 auto MI = SI->MappedExprComponents.find(VD);
407 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000408 for (auto &L : MI->second.Components)
409 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000410 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000411 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000412 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000413 }
414
Samuel Antao4c8035b2016-12-12 18:00:20 +0000415 /// Create a new mappable expression component list associated with a given
416 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000417 void addMappableExpressionComponents(
418 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000419 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
420 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000421 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000422 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000423 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000424 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000425 MEC.Components.resize(MEC.Components.size() + 1);
426 MEC.Components.back().append(Components.begin(), Components.end());
427 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000428 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000429
430 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000431 assert(!isStackEmpty());
432 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000433 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000434 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000435 assert(!isStackEmpty() && Stack.back().first.size() > 1);
436 auto &StackElem = *std::next(Stack.back().first.rbegin());
437 assert(isOpenMPWorksharingDirective(StackElem.Directive));
438 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000439 }
440 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
441 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000442 assert(!isStackEmpty());
443 auto &StackElem = Stack.back().first.back();
444 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
445 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000446 return llvm::make_range(Ref.begin(), Ref.end());
447 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000448 return llvm::make_range(StackElem.DoacrossDepends.end(),
449 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000450 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000451};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000452bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000453 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
454 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000455}
Alexey Bataeved09d242014-05-28 05:53:51 +0000456} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000457
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000458static ValueDecl *getCanonicalDecl(ValueDecl *D) {
459 auto *VD = dyn_cast<VarDecl>(D);
460 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000461 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000462 VD = VD->getCanonicalDecl();
463 D = VD;
464 } else {
465 assert(FD);
466 FD = FD->getCanonicalDecl();
467 D = FD;
468 }
469 return D;
470}
471
David Majnemer9d168222016-08-05 17:44:54 +0000472DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000473 ValueDecl *D) {
474 D = getCanonicalDecl(D);
475 auto *VD = dyn_cast<VarDecl>(D);
476 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000477 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000478 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000479 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
480 // in a region but not in construct]
481 // File-scope or namespace-scope variables referenced in called routines
482 // in the region are shared unless they appear in a threadprivate
483 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000484 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000485 DVar.CKind = OMPC_shared;
486
487 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
488 // in a region but not in construct]
489 // Variables with static storage duration that are declared in called
490 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000491 if (VD && VD->hasGlobalStorage())
492 DVar.CKind = OMPC_shared;
493
494 // Non-static data members are shared by default.
495 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000496 DVar.CKind = OMPC_shared;
497
Alexey Bataev758e55e2013-09-06 18:03:48 +0000498 return DVar;
499 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000500
Alexey Bataev758e55e2013-09-06 18:03:48 +0000501 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000502 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
503 // in a Construct, C/C++, predetermined, p.1]
504 // Variables with automatic storage duration that are declared in a scope
505 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000506 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
507 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000508 DVar.CKind = OMPC_private;
509 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000510 }
511
Alexey Bataev758e55e2013-09-06 18:03:48 +0000512 // Explicitly specified attributes and local variables with predetermined
513 // attributes.
514 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000515 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000516 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000518 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 return DVar;
520 }
521
522 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
523 // in a Construct, C/C++, implicitly determined, p.1]
524 // In a parallel or task construct, the data-sharing attributes of these
525 // variables are determined by the default clause, if present.
526 switch (Iter->DefaultAttr) {
527 case DSA_shared:
528 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000529 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000530 return DVar;
531 case DSA_none:
532 return DVar;
533 case DSA_unspecified:
534 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
535 // in a Construct, implicitly determined, p.2]
536 // In a parallel construct, if no default clause is present, these
537 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000538 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000539 if (isOpenMPParallelDirective(DVar.DKind) ||
540 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000541 DVar.CKind = OMPC_shared;
542 return DVar;
543 }
544
545 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
546 // in a Construct, implicitly determined, p.4]
547 // In a task construct, if no default clause is present, a variable that in
548 // the enclosing context is determined to be shared by all implicit tasks
549 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000550 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000551 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000552 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000553 do {
554 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000555 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000556 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000557 // In a task construct, if no default clause is present, a variable
558 // whose data-sharing attribute is not determined by the rules above is
559 // firstprivate.
560 DVarTemp = getDSA(I, D);
561 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000562 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000563 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000564 return DVar;
565 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000566 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000567 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000568 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000569 return DVar;
570 }
571 }
572 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
573 // in a Construct, implicitly determined, p.3]
574 // For constructs other than task, if no default clause is present, these
575 // variables inherit their data-sharing attributes from the enclosing
576 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000577 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578}
579
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000581 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000582 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000583 auto &StackElem = Stack.back().first.back();
584 auto It = StackElem.AlignedMap.find(D);
585 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000586 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000587 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000588 return nullptr;
589 } else {
590 assert(It->second && "Unexpected nullptr expr in the aligned map");
591 return It->second;
592 }
593 return nullptr;
594}
595
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000596void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000597 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000598 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000599 auto &StackElem = Stack.back().first.back();
600 StackElem.LCVMap.insert(
601 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000602}
603
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000604DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000605 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000606 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000607 auto &StackElem = Stack.back().first.back();
608 auto It = StackElem.LCVMap.find(D);
609 if (It != StackElem.LCVMap.end())
610 return It->second;
611 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000612}
613
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000614DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000615 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
616 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000617 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000618 auto &StackElem = *std::next(Stack.back().first.rbegin());
619 auto It = StackElem.LCVMap.find(D);
620 if (It != StackElem.LCVMap.end())
621 return It->second;
622 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000623}
624
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000625ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000626 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
627 "Data-sharing attributes stack is empty");
628 auto &StackElem = *std::next(Stack.back().first.rbegin());
629 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000630 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000631 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000632 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000633 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000634 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000635}
636
Alexey Bataev90c228f2016-02-08 09:29:13 +0000637void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
638 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000639 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000640 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000641 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000642 Data.Attributes = A;
643 Data.RefExpr.setPointer(E);
644 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000645 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000646 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
647 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000648 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
649 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
650 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
651 (isLoopControlVariable(D).first && A == OMPC_private));
652 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
653 Data.RefExpr.setInt(/*IntVal=*/true);
654 return;
655 }
656 const bool IsLastprivate =
657 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
658 Data.Attributes = A;
659 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
660 Data.PrivateCopy = PrivateCopy;
661 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000662 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000663 Data.Attributes = A;
664 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
665 Data.PrivateCopy = nullptr;
666 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668}
669
Alexey Bataeved09d242014-05-28 05:53:51 +0000670bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000671 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000672 if (!isStackEmpty() && Stack.back().first.size() > 1) {
673 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000674 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000675 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000676 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000677 if (I == E)
678 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000679 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000680 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000681 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000682 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000683 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000684 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000685 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000686}
687
Alexey Bataev39f915b82015-05-08 10:41:21 +0000688/// \brief Build a variable declaration for OpenMP loop iteration variable.
689static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000690 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000691 DeclContext *DC = SemaRef.CurContext;
692 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
693 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
694 VarDecl *Decl =
695 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000696 if (Attrs) {
697 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
698 I != E; ++I)
699 Decl->addAttr(*I);
700 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000701 Decl->setImplicit();
702 return Decl;
703}
704
705static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
706 SourceLocation Loc,
707 bool RefersToCapture = false) {
708 D->setReferenced();
709 D->markUsed(S.Context);
710 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
711 SourceLocation(), D, RefersToCapture, Loc, Ty,
712 VK_LValue);
713}
714
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000715DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
716 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000717 DSAVarData DVar;
718
719 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
720 // in a Construct, C/C++, predetermined, p.1]
721 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000722 auto *VD = dyn_cast<VarDecl>(D);
723 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
724 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000725 SemaRef.getLangOpts().OpenMPUseTLS &&
726 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000727 (VD && VD->getStorageClass() == SC_Register &&
728 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
729 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000730 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000731 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000732 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000733 auto TI = Threadprivates.find(D);
734 if (TI != Threadprivates.end()) {
735 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 DVar.CKind = OMPC_threadprivate;
737 return DVar;
738 }
739
Alexey Bataev4b465392017-04-26 15:06:24 +0000740 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000741 // Not in OpenMP execution region and top scope was already checked.
742 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000743
Alexey Bataev758e55e2013-09-06 18:03:48 +0000744 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000745 // in a Construct, C/C++, predetermined, p.4]
746 // Static data members are shared.
747 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
748 // in a Construct, C/C++, predetermined, p.7]
749 // Variables with static storage duration that are declared in a scope
750 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000751 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000752 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000753 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000754 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000755 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000756
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000757 DVar.CKind = OMPC_shared;
758 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000759 }
760
761 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000762 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
763 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000764 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
765 // in a Construct, C/C++, predetermined, p.6]
766 // Variables with const qualified type having no mutable member are
767 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000768 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000769 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000770 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
771 if (auto *CTD = CTSD->getSpecializedTemplate())
772 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000773 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000774 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
775 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000776 // Variables with const-qualified type having no mutable member may be
777 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000778 DSAVarData DVarTemp = hasDSA(
779 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
780 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000781 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
782 return DVar;
783
Alexey Bataev758e55e2013-09-06 18:03:48 +0000784 DVar.CKind = OMPC_shared;
785 return DVar;
786 }
787
Alexey Bataev758e55e2013-09-06 18:03:48 +0000788 // Explicitly specified attributes and local variables with predetermined
789 // attributes.
Alexey Bataev4b465392017-04-26 15:06:24 +0000790 auto StartI = std::next(Stack.back().first.rbegin());
791 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000792 if (FromParent && StartI != EndI)
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000793 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000794 auto I = std::prev(StartI);
795 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000796 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000797 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000798 DVar.CKind = I->SharingMap[D].Attributes;
799 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000800 }
801
802 return DVar;
803}
804
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000805DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
806 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000807 if (isStackEmpty()) {
808 StackTy::reverse_iterator I;
809 return getDSA(I, D);
810 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000811 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000812 auto StartI = Stack.back().first.rbegin();
813 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000814 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000815 StartI = std::next(StartI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000816 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000817}
818
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000819DSAStackTy::DSAVarData
820DSAStackTy::hasDSA(ValueDecl *D,
821 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
822 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
823 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000824 if (isStackEmpty())
825 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000826 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000827 auto StartI = std::next(Stack.back().first.rbegin());
828 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000829 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000830 StartI = std::next(StartI);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000831 if (StartI == EndI)
832 return {};
833 auto I = std::prev(StartI);
834 do {
835 ++I;
Haojian Wu85ddc4c2017-04-27 12:22:33 +0000836 if (I == EndI)
837 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000838 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000839 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000840 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000841 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000842 return DVar;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000843 } while (I != EndI);
844 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000845}
846
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000847DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
848 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
849 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
850 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000851 if (isStackEmpty())
852 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000853 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000854 auto StartI = std::next(Stack.back().first.rbegin());
855 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000856 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000857 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000858 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +0000859 return {};
Alexey Bataeve3978122016-07-19 05:06:39 +0000860 DSAVarData DVar = getDSA(StartI, D);
861 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000862}
863
Alexey Bataevaac108a2015-06-23 04:51:00 +0000864bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000865 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000866 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000867 if (CPred(ClauseKindMode))
868 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000869 if (isStackEmpty())
870 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000871 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000872 auto StartI = Stack.back().first.begin();
873 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000874 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000875 return false;
876 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000877 return (StartI->SharingMap.count(D) > 0) &&
878 StartI->SharingMap[D].RefExpr.getPointer() &&
879 CPred(StartI->SharingMap[D].Attributes) &&
880 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000881}
882
Samuel Antao4be30e92015-10-02 17:14:03 +0000883bool DSAStackTy::hasExplicitDirective(
884 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
885 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000886 if (isStackEmpty())
887 return false;
888 auto StartI = Stack.back().first.begin();
889 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000890 if (std::distance(StartI, EndI) <= (int)Level)
891 return false;
892 std::advance(StartI, Level);
893 return DPred(StartI->Directive);
894}
895
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000896bool DSAStackTy::hasDirective(
897 const llvm::function_ref<bool(OpenMPDirectiveKind,
898 const DeclarationNameInfo &, SourceLocation)>
899 &DPred,
900 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000901 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000902 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +0000903 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +0000904 auto StartI = std::next(Stack.back().first.rbegin());
905 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000906 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000907 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000908 for (auto I = StartI, EE = EndI; I != EE; ++I) {
909 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
910 return true;
911 }
912 return false;
913}
914
Alexey Bataev758e55e2013-09-06 18:03:48 +0000915void Sema::InitDataSharingAttributesStack() {
916 VarDataSharingAttributesStack = new DSAStackTy(*this);
917}
918
919#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
920
Alexey Bataev4b465392017-04-26 15:06:24 +0000921void Sema::pushOpenMPFunctionRegion() {
922 DSAStack->pushFunction();
923}
924
925void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
926 DSAStack->popFunction(OldFSI);
927}
928
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000929bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000930 assert(LangOpts.OpenMP && "OpenMP is not allowed");
931
932 auto &Ctx = getASTContext();
933 bool IsByRef = true;
934
935 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000936 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000937
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000938 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000939 // This table summarizes how a given variable should be passed to the device
940 // given its type and the clauses where it appears. This table is based on
941 // the description in OpenMP 4.5 [2.10.4, target Construct] and
942 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
943 //
944 // =========================================================================
945 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
946 // | |(tofrom:scalar)| | pvt | | | |
947 // =========================================================================
948 // | scl | | | | - | | bycopy|
949 // | scl | | - | x | - | - | bycopy|
950 // | scl | | x | - | - | - | null |
951 // | scl | x | | | - | | byref |
952 // | scl | x | - | x | - | - | bycopy|
953 // | scl | x | x | - | - | - | null |
954 // | scl | | - | - | - | x | byref |
955 // | scl | x | - | - | - | x | byref |
956 //
957 // | agg | n.a. | | | - | | byref |
958 // | agg | n.a. | - | x | - | - | byref |
959 // | agg | n.a. | x | - | - | - | null |
960 // | agg | n.a. | - | - | - | x | byref |
961 // | agg | n.a. | - | - | - | x[] | byref |
962 //
963 // | ptr | n.a. | | | - | | bycopy|
964 // | ptr | n.a. | - | x | - | - | bycopy|
965 // | ptr | n.a. | x | - | - | - | null |
966 // | ptr | n.a. | - | - | - | x | byref |
967 // | ptr | n.a. | - | - | - | x[] | bycopy|
968 // | ptr | n.a. | - | - | x | | bycopy|
969 // | ptr | n.a. | - | - | x | x | bycopy|
970 // | ptr | n.a. | - | - | x | x[] | bycopy|
971 // =========================================================================
972 // Legend:
973 // scl - scalar
974 // ptr - pointer
975 // agg - aggregate
976 // x - applies
977 // - - invalid in this combination
978 // [] - mapped with an array section
979 // byref - should be mapped by reference
980 // byval - should be mapped by value
981 // null - initialize a local variable to null on the device
982 //
983 // Observations:
984 // - All scalar declarations that show up in a map clause have to be passed
985 // by reference, because they may have been mapped in the enclosing data
986 // environment.
987 // - If the scalar value does not fit the size of uintptr, it has to be
988 // passed by reference, regardless the result in the table above.
989 // - For pointers mapped by value that have either an implicit map or an
990 // array section, the runtime library may pass the NULL value to the
991 // device instead of the value passed to it by the compiler.
992
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000993 if (Ty->isReferenceType())
994 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000995
996 // Locate map clauses and see if the variable being captured is referred to
997 // in any of those clauses. Here we only care about variables, not fields,
998 // because fields are part of aggregates.
999 bool IsVariableUsedInMapClause = false;
1000 bool IsVariableAssociatedWithSection = false;
1001
1002 DSAStack->checkMappableExprComponentListsForDecl(
1003 D, /*CurrentRegionOnly=*/true,
1004 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001005 MapExprComponents,
1006 OpenMPClauseKind WhereFoundClauseKind) {
1007 // Only the map clause information influences how a variable is
1008 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001009 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001010 if (WhereFoundClauseKind != OMPC_map)
1011 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001012
1013 auto EI = MapExprComponents.rbegin();
1014 auto EE = MapExprComponents.rend();
1015
1016 assert(EI != EE && "Invalid map expression!");
1017
1018 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1019 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1020
1021 ++EI;
1022 if (EI == EE)
1023 return false;
1024
1025 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1026 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1027 isa<MemberExpr>(EI->getAssociatedExpression())) {
1028 IsVariableAssociatedWithSection = true;
1029 // There is nothing more we need to know about this variable.
1030 return true;
1031 }
1032
1033 // Keep looking for more map info.
1034 return false;
1035 });
1036
1037 if (IsVariableUsedInMapClause) {
1038 // If variable is identified in a map clause it is always captured by
1039 // reference except if it is a pointer that is dereferenced somehow.
1040 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1041 } else {
1042 // By default, all the data that has a scalar type is mapped by copy.
1043 IsByRef = !Ty->isScalarType();
1044 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001045 }
1046
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001047 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1048 IsByRef = !DSAStack->hasExplicitDSA(
1049 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1050 Level, /*NotLastprivate=*/true);
1051 }
1052
Samuel Antao86ace552016-04-27 22:40:57 +00001053 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001054 // and alignment, because the runtime library only deals with uintptr types.
1055 // If it does not fit the uintptr size, we need to pass the data by reference
1056 // instead.
1057 if (!IsByRef &&
1058 (Ctx.getTypeSizeInChars(Ty) >
1059 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001060 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001061 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001062 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001063
1064 return IsByRef;
1065}
1066
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001067unsigned Sema::getOpenMPNestingLevel() const {
1068 assert(getLangOpts().OpenMP);
1069 return DSAStack->getNestingLevel();
1070}
1071
Alexey Bataev90c228f2016-02-08 09:29:13 +00001072VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001073 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001074 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001075
1076 // If we are attempting to capture a global variable in a directive with
1077 // 'target' we return true so that this global is also mapped to the device.
1078 //
1079 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1080 // then it should not be captured. Therefore, an extra check has to be
1081 // inserted here once support for 'declare target' is added.
1082 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001083 auto *VD = dyn_cast<VarDecl>(D);
1084 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001085 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001086 !DSAStack->isClauseParsingMode())
1087 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001088 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001089 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1090 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001091 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001092 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001093 false))
1094 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001095 }
1096
Alexey Bataev48977c32015-08-04 08:10:48 +00001097 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1098 (!DSAStack->isClauseParsingMode() ||
1099 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001100 auto &&Info = DSAStack->isLoopControlVariable(D);
1101 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001102 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001103 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001105 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001106 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001107 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001108 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001109 DVarPrivate = DSAStack->hasDSA(
1110 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1111 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001112 if (DVarPrivate.CKind != OMPC_unknown)
1113 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001114 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001115 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001116}
1117
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001118bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001119 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1120 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001121 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001122}
1123
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001124bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001125 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1126 // Return true if the current level is no longer enclosed in a target region.
1127
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001128 auto *VD = dyn_cast<VarDecl>(D);
1129 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001130 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1131 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001132}
1133
Alexey Bataeved09d242014-05-28 05:53:51 +00001134void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001135
1136void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1137 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001138 Scope *CurScope, SourceLocation Loc) {
1139 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001140 PushExpressionEvaluationContext(
1141 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001142}
1143
Alexey Bataevaac108a2015-06-23 04:51:00 +00001144void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1145 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001146}
1147
Alexey Bataevaac108a2015-06-23 04:51:00 +00001148void Sema::EndOpenMPClause() {
1149 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001150}
1151
Alexey Bataev758e55e2013-09-06 18:03:48 +00001152void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001153 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1154 // A variable of class type (or array thereof) that appears in a lastprivate
1155 // clause requires an accessible, unambiguous default constructor for the
1156 // class type, unless the list item is also specified in a firstprivate
1157 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001158 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001159 for (auto *C : D->clauses()) {
1160 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1161 SmallVector<Expr *, 8> PrivateCopies;
1162 for (auto *DE : Clause->varlists()) {
1163 if (DE->isValueDependent() || DE->isTypeDependent()) {
1164 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001165 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001166 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001167 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001168 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1169 QualType Type = VD->getType().getNonReferenceType();
1170 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001171 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001172 // Generate helper private variable and initialize it with the
1173 // default value. The address of the original variable is replaced
1174 // by the address of the new private variable in CodeGen. This new
1175 // variable is not added to IdResolver, so the code in the OpenMP
1176 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001177 auto *VDPrivate = buildVarDecl(
1178 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001179 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001180 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001181 if (VDPrivate->isInvalidDecl())
1182 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001183 PrivateCopies.push_back(buildDeclRefExpr(
1184 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001185 } else {
1186 // The variable is also a firstprivate, so initialization sequence
1187 // for private copy is generated already.
1188 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001189 }
1190 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001191 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001192 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001193 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001194 }
1195 }
1196 }
1197
Alexey Bataev758e55e2013-09-06 18:03:48 +00001198 DSAStack->pop();
1199 DiscardCleanupsInEvaluationContext();
1200 PopExpressionEvaluationContext();
1201}
1202
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001203static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1204 Expr *NumIterations, Sema &SemaRef,
1205 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001206
Alexey Bataeva769e072013-03-22 06:34:35 +00001207namespace {
1208
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001209class VarDeclFilterCCC : public CorrectionCandidateCallback {
1210private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001211 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001212
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001213public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001214 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001215 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001216 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001217 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001218 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001219 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1220 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001221 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001222 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001223 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001224};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001225
1226class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1227private:
1228 Sema &SemaRef;
1229
1230public:
1231 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1232 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1233 NamedDecl *ND = Candidate.getCorrectionDecl();
1234 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1235 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1236 SemaRef.getCurScope());
1237 }
1238 return false;
1239 }
1240};
1241
Alexey Bataeved09d242014-05-28 05:53:51 +00001242} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001243
1244ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1245 CXXScopeSpec &ScopeSpec,
1246 const DeclarationNameInfo &Id) {
1247 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1248 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1249
1250 if (Lookup.isAmbiguous())
1251 return ExprError();
1252
1253 VarDecl *VD;
1254 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001255 if (TypoCorrection Corrected = CorrectTypo(
1256 Id, LookupOrdinaryName, CurScope, nullptr,
1257 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001258 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001259 PDiag(Lookup.empty()
1260 ? diag::err_undeclared_var_use_suggest
1261 : diag::err_omp_expected_var_arg_suggest)
1262 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001263 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001264 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001265 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1266 : diag::err_omp_expected_var_arg)
1267 << Id.getName();
1268 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001269 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 } else {
1271 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001272 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001273 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1274 return ExprError();
1275 }
1276 }
1277 Lookup.suppressDiagnostics();
1278
1279 // OpenMP [2.9.2, Syntax, C/C++]
1280 // Variables must be file-scope, namespace-scope, or static block-scope.
1281 if (!VD->hasGlobalStorage()) {
1282 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001283 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1284 bool IsDecl =
1285 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001286 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001287 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1288 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001289 return ExprError();
1290 }
1291
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001292 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1293 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001294 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1295 // A threadprivate directive for file-scope variables must appear outside
1296 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001297 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1298 !getCurLexicalContext()->isTranslationUnit()) {
1299 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001300 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1301 bool IsDecl =
1302 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1303 Diag(VD->getLocation(),
1304 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1305 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001306 return ExprError();
1307 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001308 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1309 // A threadprivate directive for static class member variables must appear
1310 // in the class definition, in the same scope in which the member
1311 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001312 if (CanonicalVD->isStaticDataMember() &&
1313 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1314 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001315 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1316 bool IsDecl =
1317 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1318 Diag(VD->getLocation(),
1319 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1320 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001321 return ExprError();
1322 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1324 // A threadprivate directive for namespace-scope variables must appear
1325 // outside any definition or declaration other than the namespace
1326 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001327 if (CanonicalVD->getDeclContext()->isNamespace() &&
1328 (!getCurLexicalContext()->isFileContext() ||
1329 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1330 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001331 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1332 bool IsDecl =
1333 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1334 Diag(VD->getLocation(),
1335 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1336 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001337 return ExprError();
1338 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001339 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1340 // A threadprivate directive for static block-scope variables must appear
1341 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001342 if (CanonicalVD->isStaticLocal() && CurScope &&
1343 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001344 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001345 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1346 bool IsDecl =
1347 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1348 Diag(VD->getLocation(),
1349 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1350 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001351 return ExprError();
1352 }
1353
1354 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1355 // A threadprivate directive must lexically precede all references to any
1356 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001357 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001358 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001359 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001360 return ExprError();
1361 }
1362
1363 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001364 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1365 SourceLocation(), VD,
1366 /*RefersToEnclosingVariableOrCapture=*/false,
1367 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001368}
1369
Alexey Bataeved09d242014-05-28 05:53:51 +00001370Sema::DeclGroupPtrTy
1371Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1372 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001373 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001374 CurContext->addDecl(D);
1375 return DeclGroupPtrTy::make(DeclGroupRef(D));
1376 }
David Blaikie0403cb12016-01-15 23:43:25 +00001377 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001378}
1379
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001380namespace {
1381class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1382 Sema &SemaRef;
1383
1384public:
1385 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001386 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001387 if (VD->hasLocalStorage()) {
1388 SemaRef.Diag(E->getLocStart(),
1389 diag::err_omp_local_var_in_threadprivate_init)
1390 << E->getSourceRange();
1391 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1392 << VD << VD->getSourceRange();
1393 return true;
1394 }
1395 }
1396 return false;
1397 }
1398 bool VisitStmt(const Stmt *S) {
1399 for (auto Child : S->children()) {
1400 if (Child && Visit(Child))
1401 return true;
1402 }
1403 return false;
1404 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001405 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001406};
1407} // namespace
1408
Alexey Bataeved09d242014-05-28 05:53:51 +00001409OMPThreadPrivateDecl *
1410Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001411 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001412 for (auto &RefExpr : VarList) {
1413 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001414 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1415 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001416
Alexey Bataev376b4a42016-02-09 09:41:09 +00001417 // Mark variable as used.
1418 VD->setReferenced();
1419 VD->markUsed(Context);
1420
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001421 QualType QType = VD->getType();
1422 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1423 // It will be analyzed later.
1424 Vars.push_back(DE);
1425 continue;
1426 }
1427
Alexey Bataeva769e072013-03-22 06:34:35 +00001428 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1429 // A threadprivate variable must not have an incomplete type.
1430 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001431 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001432 continue;
1433 }
1434
1435 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1436 // A threadprivate variable must not have a reference type.
1437 if (VD->getType()->isReferenceType()) {
1438 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001439 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1440 bool IsDecl =
1441 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1442 Diag(VD->getLocation(),
1443 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1444 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001445 continue;
1446 }
1447
Samuel Antaof8b50122015-07-13 22:54:53 +00001448 // Check if this is a TLS variable. If TLS is not being supported, produce
1449 // the corresponding diagnostic.
1450 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1451 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1452 getLangOpts().OpenMPUseTLS &&
1453 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001454 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1455 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001456 Diag(ILoc, diag::err_omp_var_thread_local)
1457 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001458 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
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001466 // Check if initial value of threadprivate variable reference variable with
1467 // local storage (it is not supported by runtime).
1468 if (auto Init = VD->getAnyInitializer()) {
1469 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001470 if (Checker.Visit(Init))
1471 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001472 }
1473
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001475 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001476 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1477 Context, SourceRange(Loc, Loc)));
1478 if (auto *ML = Context.getASTMutationListener())
1479 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001480 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001481 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001482 if (!Vars.empty()) {
1483 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1484 Vars);
1485 D->setAccess(AS_public);
1486 }
1487 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001488}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001489
Alexey Bataev7ff55242014-06-19 09:13:45 +00001490static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001491 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001492 bool IsLoopIterVar = false) {
1493 if (DVar.RefExpr) {
1494 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1495 << getOpenMPClauseName(DVar.CKind);
1496 return;
1497 }
1498 enum {
1499 PDSA_StaticMemberShared,
1500 PDSA_StaticLocalVarShared,
1501 PDSA_LoopIterVarPrivate,
1502 PDSA_LoopIterVarLinear,
1503 PDSA_LoopIterVarLastprivate,
1504 PDSA_ConstVarShared,
1505 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001506 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001507 PDSA_LocalVarPrivate,
1508 PDSA_Implicit
1509 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001510 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001511 auto ReportLoc = D->getLocation();
1512 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001513 if (IsLoopIterVar) {
1514 if (DVar.CKind == OMPC_private)
1515 Reason = PDSA_LoopIterVarPrivate;
1516 else if (DVar.CKind == OMPC_lastprivate)
1517 Reason = PDSA_LoopIterVarLastprivate;
1518 else
1519 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001520 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1521 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001522 Reason = PDSA_TaskVarFirstprivate;
1523 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001525 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001526 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001527 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001528 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001529 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001530 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001531 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001532 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001533 ReportHint = true;
1534 Reason = PDSA_LocalVarPrivate;
1535 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001536 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001537 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001538 << Reason << ReportHint
1539 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1540 } else if (DVar.ImplicitDSALoc.isValid()) {
1541 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1542 << getOpenMPClauseName(DVar.CKind);
1543 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001544}
1545
Alexey Bataev758e55e2013-09-06 18:03:48 +00001546namespace {
1547class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1548 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001549 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001550 bool ErrorFound;
1551 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001552 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001553 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001554
Alexey Bataev758e55e2013-09-06 18:03:48 +00001555public:
1556 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001557 if (E->isTypeDependent() || E->isValueDependent() ||
1558 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1559 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001560 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001561 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001562 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1563 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001564
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001565 auto DVar = Stack->getTopDSA(VD, false);
1566 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001567 if (DVar.RefExpr)
1568 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001569
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001570 auto ELoc = E->getExprLoc();
1571 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 // The default(none) clause requires that each variable that is referenced
1573 // in the construct, and does not have a predetermined data-sharing
1574 // attribute, must have its data-sharing attribute explicitly determined
1575 // by being listed in a data-sharing attribute clause.
1576 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001577 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001578 VarsWithInheritedDSA.count(VD) == 0) {
1579 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001580 return;
1581 }
1582
1583 // OpenMP [2.9.3.6, Restrictions, p.2]
1584 // A list item that appears in a reduction clause of the innermost
1585 // enclosing worksharing or parallel construct may not be accessed in an
1586 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001587 DVar = Stack->hasInnermostDSA(
1588 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1589 [](OpenMPDirectiveKind K) -> bool {
1590 return isOpenMPParallelDirective(K) ||
1591 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1592 },
1593 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001594 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001595 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001596 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1597 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001598 return;
1599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001600
1601 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001602 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001603 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1604 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001605 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001606 }
1607 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001608 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001609 if (E->isTypeDependent() || E->isValueDependent() ||
1610 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1611 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001612 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1613 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1614 auto DVar = Stack->getTopDSA(FD, false);
1615 // Check if the variable has explicit DSA set and stop analysis if it
1616 // so.
1617 if (DVar.RefExpr)
1618 return;
1619
1620 auto ELoc = E->getExprLoc();
1621 auto DKind = Stack->getCurrentDirective();
1622 // OpenMP [2.9.3.6, Restrictions, p.2]
1623 // A list item that appears in a reduction clause of the innermost
1624 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001625 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001626 DVar = Stack->hasInnermostDSA(
1627 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1628 [](OpenMPDirectiveKind K) -> bool {
1629 return isOpenMPParallelDirective(K) ||
1630 isOpenMPWorksharingDirective(K) ||
1631 isOpenMPTeamsDirective(K);
1632 },
1633 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001634 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001635 ErrorFound = true;
1636 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1637 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1638 return;
1639 }
1640
1641 // Define implicit data-sharing attributes for task.
1642 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001643 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1644 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001645 ImplicitFirstprivate.push_back(E);
1646 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001647 } else
1648 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001649 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001650 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001651 for (auto *C : S->clauses()) {
1652 // Skip analysis of arguments of implicitly defined firstprivate clause
1653 // for task directives.
1654 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1655 for (auto *CC : C->children()) {
1656 if (CC)
1657 Visit(CC);
1658 }
1659 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001660 }
1661 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001662 for (auto *C : S->children()) {
1663 if (C && !isa<OMPExecutableDirective>(C))
1664 Visit(C);
1665 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001666 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001667
1668 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001669 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001670 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001671 return VarsWithInheritedDSA;
1672 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001673
Alexey Bataev7ff55242014-06-19 09:13:45 +00001674 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1675 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001676};
Alexey Bataeved09d242014-05-28 05:53:51 +00001677} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001678
Alexey Bataevbae9a792014-06-27 10:37:06 +00001679void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001680 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001681 case OMPD_parallel:
1682 case OMPD_parallel_for:
1683 case OMPD_parallel_for_simd:
1684 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001685 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001686 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001687 QualType KmpInt32PtrTy =
1688 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001689 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001690 std::make_pair(".global_tid.", KmpInt32PtrTy),
1691 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1692 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001693 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001694 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1695 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001696 break;
1697 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001698 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001699 case OMPD_target_parallel: {
1700 Sema::CapturedParamNameType ParamsTarget[] = {
1701 std::make_pair(StringRef(), QualType()) // __context with shared vars
1702 };
1703 // Start a captured region for 'target' with no implicit parameters.
1704 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1705 ParamsTarget);
1706 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1707 QualType KmpInt32PtrTy =
1708 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001709 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001710 std::make_pair(".global_tid.", KmpInt32PtrTy),
1711 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1712 std::make_pair(StringRef(), QualType()) // __context with shared vars
1713 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001714 // Start a captured region for 'teams' or 'parallel'. Both regions have
1715 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001716 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001717 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001718 break;
1719 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001720 case OMPD_simd:
1721 case OMPD_for:
1722 case OMPD_for_simd:
1723 case OMPD_sections:
1724 case OMPD_section:
1725 case OMPD_single:
1726 case OMPD_master:
1727 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001728 case OMPD_taskgroup:
1729 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001730 case OMPD_ordered:
1731 case OMPD_atomic:
1732 case OMPD_target_data:
1733 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001734 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001735 case OMPD_target_parallel_for_simd:
1736 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001737 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001738 std::make_pair(StringRef(), QualType()) // __context with shared vars
1739 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001740 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1741 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001742 break;
1743 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001744 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001745 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001746 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1747 FunctionProtoType::ExtProtoInfo EPI;
1748 EPI.Variadic = true;
1749 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001750 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001751 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001752 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1753 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1754 std::make_pair(".copy_fn.",
1755 Context.getPointerType(CopyFnType).withConst()),
1756 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001757 std::make_pair(StringRef(), QualType()) // __context with shared vars
1758 };
1759 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1760 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001761 // Mark this captured region as inlined, because we don't use outlined
1762 // function directly.
1763 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1764 AlwaysInlineAttr::CreateImplicit(
1765 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001766 break;
1767 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001768 case OMPD_taskloop:
1769 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001770 QualType KmpInt32Ty =
1771 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1772 QualType KmpUInt64Ty =
1773 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1774 QualType KmpInt64Ty =
1775 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1776 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1777 FunctionProtoType::ExtProtoInfo EPI;
1778 EPI.Variadic = true;
1779 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001780 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001781 std::make_pair(".global_tid.", KmpInt32Ty),
1782 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1783 std::make_pair(".privates.",
1784 Context.VoidPtrTy.withConst().withRestrict()),
1785 std::make_pair(
1786 ".copy_fn.",
1787 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1788 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1789 std::make_pair(".lb.", KmpUInt64Ty),
1790 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1791 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001792 std::make_pair(StringRef(), QualType()) // __context with shared vars
1793 };
1794 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1795 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001796 // Mark this captured region as inlined, because we don't use outlined
1797 // function directly.
1798 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1799 AlwaysInlineAttr::CreateImplicit(
1800 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001801 break;
1802 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001803 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001804 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001805 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001806 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001807 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001808 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001809 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001810 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001811 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001812 case OMPD_target_teams_distribute_parallel_for_simd:
1813 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001814 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1815 QualType KmpInt32PtrTy =
1816 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1817 Sema::CapturedParamNameType Params[] = {
1818 std::make_pair(".global_tid.", KmpInt32PtrTy),
1819 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1820 std::make_pair(".previous.lb.", Context.getSizeType()),
1821 std::make_pair(".previous.ub.", Context.getSizeType()),
1822 std::make_pair(StringRef(), QualType()) // __context with shared vars
1823 };
1824 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1825 Params);
1826 break;
1827 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001828 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001829 case OMPD_taskyield:
1830 case OMPD_barrier:
1831 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001832 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001833 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001834 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001835 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001836 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001837 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001838 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001839 case OMPD_declare_target:
1840 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001841 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001842 llvm_unreachable("OpenMP Directive is not allowed");
1843 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001844 llvm_unreachable("Unknown OpenMP directive");
1845 }
1846}
1847
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001848int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1849 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1850 getOpenMPCaptureRegions(CaptureRegions, DKind);
1851 return CaptureRegions.size();
1852}
1853
Alexey Bataev3392d762016-02-16 11:18:12 +00001854static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001855 Expr *CaptureExpr, bool WithInit,
1856 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001857 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001858 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001859 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001860 QualType Ty = Init->getType();
1861 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1862 if (S.getLangOpts().CPlusPlus)
1863 Ty = C.getLValueReferenceType(Ty);
1864 else {
1865 Ty = C.getPointerType(Ty);
1866 ExprResult Res =
1867 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1868 if (!Res.isUsable())
1869 return nullptr;
1870 Init = Res.get();
1871 }
Alexey Bataev61205072016-03-02 04:57:40 +00001872 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001873 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001874 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1875 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001876 if (!WithInit)
1877 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001878 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001879 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001880 return CED;
1881}
1882
Alexey Bataev61205072016-03-02 04:57:40 +00001883static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1884 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001885 OMPCapturedExprDecl *CD;
1886 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1887 CD = cast<OMPCapturedExprDecl>(VD);
1888 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001889 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1890 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001891 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001892 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001893}
1894
Alexey Bataev5a3af132016-03-29 08:58:54 +00001895static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1896 if (!Ref) {
1897 auto *CD =
1898 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1899 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1900 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1901 CaptureExpr->getExprLoc());
1902 }
1903 ExprResult Res = Ref;
1904 if (!S.getLangOpts().CPlusPlus &&
1905 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1906 Ref->getType()->isPointerType())
1907 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1908 if (!Res.isUsable())
1909 return ExprError();
1910 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001911}
1912
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001913namespace {
1914// OpenMP directives parsed in this section are represented as a
1915// CapturedStatement with an associated statement. If a syntax error
1916// is detected during the parsing of the associated statement, the
1917// compiler must abort processing and close the CapturedStatement.
1918//
1919// Combined directives such as 'target parallel' have more than one
1920// nested CapturedStatements. This RAII ensures that we unwind out
1921// of all the nested CapturedStatements when an error is found.
1922class CaptureRegionUnwinderRAII {
1923private:
1924 Sema &S;
1925 bool &ErrorFound;
1926 OpenMPDirectiveKind DKind;
1927
1928public:
1929 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1930 OpenMPDirectiveKind DKind)
1931 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1932 ~CaptureRegionUnwinderRAII() {
1933 if (ErrorFound) {
1934 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1935 while (--ThisCaptureLevel >= 0)
1936 S.ActOnCapturedRegionError();
1937 }
1938 }
1939};
1940} // namespace
1941
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001942StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1943 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001944 bool ErrorFound = false;
1945 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1946 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001947 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001948 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001949 return StmtError();
1950 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001951
1952 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001953 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001954 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001955 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001956 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001957 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001958 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001959 Clause->getClauseKind() == OMPC_copyprivate ||
1960 (getLangOpts().OpenMPUseTLS &&
1961 getASTContext().getTargetInfo().isTLSSupported() &&
1962 Clause->getClauseKind() == OMPC_copyin)) {
1963 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001964 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001965 for (auto *VarRef : Clause->children()) {
1966 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001967 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001968 }
1969 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001970 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001971 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001972 if (auto *C = OMPClauseWithPreInit::get(Clause))
1973 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001974 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1975 if (auto *E = C->getPostUpdateExpr())
1976 MarkDeclarationsReferencedInExpr(E);
1977 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001978 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001979 if (Clause->getClauseKind() == OMPC_schedule)
1980 SC = cast<OMPScheduleClause>(Clause);
1981 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001982 OC = cast<OMPOrderedClause>(Clause);
1983 else if (Clause->getClauseKind() == OMPC_linear)
1984 LCs.push_back(cast<OMPLinearClause>(Clause));
1985 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001986 // OpenMP, 2.7.1 Loop Construct, Restrictions
1987 // The nonmonotonic modifier cannot be specified if an ordered clause is
1988 // specified.
1989 if (SC &&
1990 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1991 SC->getSecondScheduleModifier() ==
1992 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1993 OC) {
1994 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1995 ? SC->getFirstScheduleModifierLoc()
1996 : SC->getSecondScheduleModifierLoc(),
1997 diag::err_omp_schedule_nonmonotonic_ordered)
1998 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1999 ErrorFound = true;
2000 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002001 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2002 for (auto *C : LCs) {
2003 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2004 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2005 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002006 ErrorFound = true;
2007 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002008 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2009 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2010 OC->getNumForLoops()) {
2011 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2012 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2013 ErrorFound = true;
2014 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002015 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002016 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002017 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002018 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002019 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2020 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2021 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2022 // Mark all variables in private list clauses as used in inner region.
2023 // Required for proper codegen of combined directives.
2024 // TODO: add processing for other clauses.
2025 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2026 for (auto *C : PICs) {
2027 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2028 // Find the particular capture region for the clause if the
2029 // directive is a combined one with multiple capture regions.
2030 // If the directive is not a combined one, the capture region
2031 // associated with the clause is OMPD_unknown and is generated
2032 // only once.
2033 if (CaptureRegion == ThisCaptureRegion ||
2034 CaptureRegion == OMPD_unknown) {
2035 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2036 for (auto *D : DS->decls())
2037 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2038 }
2039 }
2040 }
2041 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002042 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002043 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002044 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002045}
2046
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002047static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2048 OpenMPDirectiveKind CancelRegion,
2049 SourceLocation StartLoc) {
2050 // CancelRegion is only needed for cancel and cancellation_point.
2051 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2052 return false;
2053
2054 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2055 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2056 return false;
2057
2058 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2059 << getOpenMPDirectiveName(CancelRegion);
2060 return true;
2061}
2062
2063static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002064 OpenMPDirectiveKind CurrentRegion,
2065 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002066 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002067 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002068 if (Stack->getCurScope()) {
2069 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002070 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002071 bool NestingProhibited = false;
2072 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002073 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002074 enum {
2075 NoRecommend,
2076 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002077 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002078 ShouldBeInTargetRegion,
2079 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002080 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002081 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002082 // OpenMP [2.16, Nesting of Regions]
2083 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002084 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002085 // An ordered construct with the simd clause is the only OpenMP
2086 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002087 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002088 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2089 // message.
2090 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2091 ? diag::err_omp_prohibited_region_simd
2092 : diag::warn_omp_nesting_simd);
2093 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002094 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002095 if (ParentRegion == OMPD_atomic) {
2096 // OpenMP [2.16, Nesting of Regions]
2097 // OpenMP constructs may not be nested inside an atomic region.
2098 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2099 return true;
2100 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002101 if (CurrentRegion == OMPD_section) {
2102 // OpenMP [2.7.2, sections Construct, Restrictions]
2103 // Orphaned section directives are prohibited. That is, the section
2104 // directives must appear within the sections construct and must not be
2105 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002106 if (ParentRegion != OMPD_sections &&
2107 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002108 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2109 << (ParentRegion != OMPD_unknown)
2110 << getOpenMPDirectiveName(ParentRegion);
2111 return true;
2112 }
2113 return false;
2114 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002115 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002116 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002117 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002118 if (ParentRegion == OMPD_unknown &&
2119 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002120 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002121 if (CurrentRegion == OMPD_cancellation_point ||
2122 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002123 // OpenMP [2.16, Nesting of Regions]
2124 // A cancellation point construct for which construct-type-clause is
2125 // taskgroup must be nested inside a task construct. A cancellation
2126 // point construct for which construct-type-clause is not taskgroup must
2127 // be closely nested inside an OpenMP construct that matches the type
2128 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002129 // A cancel construct for which construct-type-clause is taskgroup must be
2130 // nested inside a task construct. A cancel construct for which
2131 // construct-type-clause is not taskgroup must be closely nested inside an
2132 // OpenMP construct that matches the type specified in
2133 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002134 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002135 !((CancelRegion == OMPD_parallel &&
2136 (ParentRegion == OMPD_parallel ||
2137 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002138 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002139 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2140 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002141 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2142 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002143 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2144 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002145 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002146 // OpenMP [2.16, Nesting of Regions]
2147 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002148 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002149 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002150 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002151 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2152 // OpenMP [2.16, Nesting of Regions]
2153 // A critical region may not be nested (closely or otherwise) inside a
2154 // critical region with the same name. Note that this restriction is not
2155 // sufficient to prevent deadlock.
2156 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002157 bool DeadLock = Stack->hasDirective(
2158 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2159 const DeclarationNameInfo &DNI,
2160 SourceLocation Loc) -> bool {
2161 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2162 PreviousCriticalLoc = Loc;
2163 return true;
2164 } else
2165 return false;
2166 },
2167 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002168 if (DeadLock) {
2169 SemaRef.Diag(StartLoc,
2170 diag::err_omp_prohibited_region_critical_same_name)
2171 << CurrentName.getName();
2172 if (PreviousCriticalLoc.isValid())
2173 SemaRef.Diag(PreviousCriticalLoc,
2174 diag::note_omp_previous_critical_region);
2175 return true;
2176 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002177 } else if (CurrentRegion == OMPD_barrier) {
2178 // OpenMP [2.16, Nesting of Regions]
2179 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002180 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002181 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2182 isOpenMPTaskingDirective(ParentRegion) ||
2183 ParentRegion == OMPD_master ||
2184 ParentRegion == OMPD_critical ||
2185 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002186 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002187 !isOpenMPParallelDirective(CurrentRegion) &&
2188 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002189 // OpenMP [2.16, Nesting of Regions]
2190 // A worksharing region may not be closely nested inside a worksharing,
2191 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002192 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2193 isOpenMPTaskingDirective(ParentRegion) ||
2194 ParentRegion == OMPD_master ||
2195 ParentRegion == OMPD_critical ||
2196 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002197 Recommend = ShouldBeInParallelRegion;
2198 } else if (CurrentRegion == OMPD_ordered) {
2199 // OpenMP [2.16, Nesting of Regions]
2200 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002201 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002202 // An ordered region must be closely nested inside a loop region (or
2203 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002204 // OpenMP [2.8.1,simd Construct, Restrictions]
2205 // An ordered construct with the simd clause is the only OpenMP construct
2206 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002207 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002208 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002209 !(isOpenMPSimdDirective(ParentRegion) ||
2210 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002211 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002212 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002213 // OpenMP [2.16, Nesting of Regions]
2214 // If specified, a teams construct must be contained within a target
2215 // construct.
2216 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002217 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002218 Recommend = ShouldBeInTargetRegion;
2219 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2220 }
Kelvin Libf594a52016-12-17 05:48:59 +00002221 if (!NestingProhibited &&
2222 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2223 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2224 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002225 // OpenMP [2.16, Nesting of Regions]
2226 // distribute, parallel, parallel sections, parallel workshare, and the
2227 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2228 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002229 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2230 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002231 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002232 }
David Majnemer9d168222016-08-05 17:44:54 +00002233 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002234 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002235 // OpenMP 4.5 [2.17 Nesting of Regions]
2236 // The region associated with the distribute construct must be strictly
2237 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002238 NestingProhibited =
2239 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002240 Recommend = ShouldBeInTeamsRegion;
2241 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002242 if (!NestingProhibited &&
2243 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2244 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2245 // OpenMP 4.5 [2.17 Nesting of Regions]
2246 // If a target, target update, target data, target enter data, or
2247 // target exit data construct is encountered during execution of a
2248 // target region, the behavior is unspecified.
2249 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002250 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2251 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002252 if (isOpenMPTargetExecutionDirective(K)) {
2253 OffendingRegion = K;
2254 return true;
2255 } else
2256 return false;
2257 },
2258 false /* don't skip top directive */);
2259 CloseNesting = false;
2260 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002261 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002262 if (OrphanSeen) {
2263 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2264 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2265 } else {
2266 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2267 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2268 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2269 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002270 return true;
2271 }
2272 }
2273 return false;
2274}
2275
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002276static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2277 ArrayRef<OMPClause *> Clauses,
2278 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2279 bool ErrorFound = false;
2280 unsigned NamedModifiersNumber = 0;
2281 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2282 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002283 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002284 for (const auto *C : Clauses) {
2285 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2286 // At most one if clause without a directive-name-modifier can appear on
2287 // the directive.
2288 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2289 if (FoundNameModifiers[CurNM]) {
2290 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2291 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2292 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2293 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002294 } else if (CurNM != OMPD_unknown) {
2295 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002296 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002297 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002298 FoundNameModifiers[CurNM] = IC;
2299 if (CurNM == OMPD_unknown)
2300 continue;
2301 // Check if the specified name modifier is allowed for the current
2302 // directive.
2303 // At most one if clause with the particular directive-name-modifier can
2304 // appear on the directive.
2305 bool MatchFound = false;
2306 for (auto NM : AllowedNameModifiers) {
2307 if (CurNM == NM) {
2308 MatchFound = true;
2309 break;
2310 }
2311 }
2312 if (!MatchFound) {
2313 S.Diag(IC->getNameModifierLoc(),
2314 diag::err_omp_wrong_if_directive_name_modifier)
2315 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2316 ErrorFound = true;
2317 }
2318 }
2319 }
2320 // If any if clause on the directive includes a directive-name-modifier then
2321 // all if clauses on the directive must include a directive-name-modifier.
2322 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2323 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2324 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2325 diag::err_omp_no_more_if_clause);
2326 } else {
2327 std::string Values;
2328 std::string Sep(", ");
2329 unsigned AllowedCnt = 0;
2330 unsigned TotalAllowedNum =
2331 AllowedNameModifiers.size() - NamedModifiersNumber;
2332 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2333 ++Cnt) {
2334 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2335 if (!FoundNameModifiers[NM]) {
2336 Values += "'";
2337 Values += getOpenMPDirectiveName(NM);
2338 Values += "'";
2339 if (AllowedCnt + 2 == TotalAllowedNum)
2340 Values += " or ";
2341 else if (AllowedCnt + 1 != TotalAllowedNum)
2342 Values += Sep;
2343 ++AllowedCnt;
2344 }
2345 }
2346 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2347 diag::err_omp_unnamed_if_clause)
2348 << (TotalAllowedNum > 1) << Values;
2349 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002350 for (auto Loc : NameModifierLoc) {
2351 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2352 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002353 ErrorFound = true;
2354 }
2355 return ErrorFound;
2356}
2357
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002358StmtResult Sema::ActOnOpenMPExecutableDirective(
2359 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2360 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2361 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002362 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002363 // First check CancelRegion which is then used in checkNestingOfRegions.
2364 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2365 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002366 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002367 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002368
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002369 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002370 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002371 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002372 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002373 if (AStmt) {
2374 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2375
2376 // Check default data sharing attributes for referenced variables.
2377 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002378 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2379 Stmt *S = AStmt;
2380 while (--ThisCaptureLevel >= 0)
2381 S = cast<CapturedStmt>(S)->getCapturedStmt();
2382 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002383 if (DSAChecker.isErrorFound())
2384 return StmtError();
2385 // Generate list of implicitly defined firstprivate variables.
2386 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002387
2388 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2389 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2390 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2391 SourceLocation(), SourceLocation())) {
2392 ClausesWithImplicit.push_back(Implicit);
2393 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2394 DSAChecker.getImplicitFirstprivate().size();
2395 } else
2396 ErrorFound = true;
2397 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002398 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002399
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002400 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002401 switch (Kind) {
2402 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002403 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2404 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002405 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002406 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002407 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002408 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2409 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002410 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002411 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002412 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2413 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002414 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002415 case OMPD_for_simd:
2416 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2417 EndLoc, VarsWithInheritedDSA);
2418 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002419 case OMPD_sections:
2420 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2421 EndLoc);
2422 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002423 case OMPD_section:
2424 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002425 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002426 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2427 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002428 case OMPD_single:
2429 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2430 EndLoc);
2431 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002432 case OMPD_master:
2433 assert(ClausesWithImplicit.empty() &&
2434 "No clauses are allowed for 'omp master' directive");
2435 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2436 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002437 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002438 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2439 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002440 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002441 case OMPD_parallel_for:
2442 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2443 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002444 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002445 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002446 case OMPD_parallel_for_simd:
2447 Res = ActOnOpenMPParallelForSimdDirective(
2448 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002449 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002450 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002451 case OMPD_parallel_sections:
2452 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2453 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002454 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002455 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002456 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002457 Res =
2458 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002459 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002460 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002461 case OMPD_taskyield:
2462 assert(ClausesWithImplicit.empty() &&
2463 "No clauses are allowed for 'omp taskyield' directive");
2464 assert(AStmt == nullptr &&
2465 "No associated statement allowed for 'omp taskyield' directive");
2466 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2467 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002468 case OMPD_barrier:
2469 assert(ClausesWithImplicit.empty() &&
2470 "No clauses are allowed for 'omp barrier' directive");
2471 assert(AStmt == nullptr &&
2472 "No associated statement allowed for 'omp barrier' directive");
2473 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2474 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002475 case OMPD_taskwait:
2476 assert(ClausesWithImplicit.empty() &&
2477 "No clauses are allowed for 'omp taskwait' directive");
2478 assert(AStmt == nullptr &&
2479 "No associated statement allowed for 'omp taskwait' directive");
2480 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2481 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002482 case OMPD_taskgroup:
2483 assert(ClausesWithImplicit.empty() &&
2484 "No clauses are allowed for 'omp taskgroup' directive");
2485 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2486 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002487 case OMPD_flush:
2488 assert(AStmt == nullptr &&
2489 "No associated statement allowed for 'omp flush' directive");
2490 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2491 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002492 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002493 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2494 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002495 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002496 case OMPD_atomic:
2497 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2498 EndLoc);
2499 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002500 case OMPD_teams:
2501 Res =
2502 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2503 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002504 case OMPD_target:
2505 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2506 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002507 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002508 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002509 case OMPD_target_parallel:
2510 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2511 StartLoc, EndLoc);
2512 AllowedNameModifiers.push_back(OMPD_target);
2513 AllowedNameModifiers.push_back(OMPD_parallel);
2514 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002515 case OMPD_target_parallel_for:
2516 Res = ActOnOpenMPTargetParallelForDirective(
2517 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2518 AllowedNameModifiers.push_back(OMPD_target);
2519 AllowedNameModifiers.push_back(OMPD_parallel);
2520 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002521 case OMPD_cancellation_point:
2522 assert(ClausesWithImplicit.empty() &&
2523 "No clauses are allowed for 'omp cancellation point' directive");
2524 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2525 "cancellation point' directive");
2526 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2527 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002528 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002529 assert(AStmt == nullptr &&
2530 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002531 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2532 CancelRegion);
2533 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002534 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002535 case OMPD_target_data:
2536 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2537 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002538 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002539 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002540 case OMPD_target_enter_data:
2541 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2542 EndLoc);
2543 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2544 break;
Samuel Antao72590762016-01-19 20:04:50 +00002545 case OMPD_target_exit_data:
2546 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2547 EndLoc);
2548 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2549 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002550 case OMPD_taskloop:
2551 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2552 EndLoc, VarsWithInheritedDSA);
2553 AllowedNameModifiers.push_back(OMPD_taskloop);
2554 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002555 case OMPD_taskloop_simd:
2556 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2557 EndLoc, VarsWithInheritedDSA);
2558 AllowedNameModifiers.push_back(OMPD_taskloop);
2559 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002560 case OMPD_distribute:
2561 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2562 EndLoc, VarsWithInheritedDSA);
2563 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002564 case OMPD_target_update:
2565 assert(!AStmt && "Statement is not allowed for target update");
2566 Res =
2567 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2568 AllowedNameModifiers.push_back(OMPD_target_update);
2569 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002570 case OMPD_distribute_parallel_for:
2571 Res = ActOnOpenMPDistributeParallelForDirective(
2572 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2573 AllowedNameModifiers.push_back(OMPD_parallel);
2574 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002575 case OMPD_distribute_parallel_for_simd:
2576 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2577 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2578 AllowedNameModifiers.push_back(OMPD_parallel);
2579 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002580 case OMPD_distribute_simd:
2581 Res = ActOnOpenMPDistributeSimdDirective(
2582 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2583 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002584 case OMPD_target_parallel_for_simd:
2585 Res = ActOnOpenMPTargetParallelForSimdDirective(
2586 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2587 AllowedNameModifiers.push_back(OMPD_target);
2588 AllowedNameModifiers.push_back(OMPD_parallel);
2589 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002590 case OMPD_target_simd:
2591 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2592 EndLoc, VarsWithInheritedDSA);
2593 AllowedNameModifiers.push_back(OMPD_target);
2594 break;
Kelvin Li02532872016-08-05 14:37:37 +00002595 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002596 Res = ActOnOpenMPTeamsDistributeDirective(
2597 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002598 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002599 case OMPD_teams_distribute_simd:
2600 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2601 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2602 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002603 case OMPD_teams_distribute_parallel_for_simd:
2604 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2605 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2606 AllowedNameModifiers.push_back(OMPD_parallel);
2607 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002608 case OMPD_teams_distribute_parallel_for:
2609 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2610 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2611 AllowedNameModifiers.push_back(OMPD_parallel);
2612 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002613 case OMPD_target_teams:
2614 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2615 EndLoc);
2616 AllowedNameModifiers.push_back(OMPD_target);
2617 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002618 case OMPD_target_teams_distribute:
2619 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2620 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2621 AllowedNameModifiers.push_back(OMPD_target);
2622 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002623 case OMPD_target_teams_distribute_parallel_for:
2624 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2625 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2626 AllowedNameModifiers.push_back(OMPD_target);
2627 AllowedNameModifiers.push_back(OMPD_parallel);
2628 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002629 case OMPD_target_teams_distribute_parallel_for_simd:
2630 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2631 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2632 AllowedNameModifiers.push_back(OMPD_target);
2633 AllowedNameModifiers.push_back(OMPD_parallel);
2634 break;
Kelvin Lida681182017-01-10 18:08:18 +00002635 case OMPD_target_teams_distribute_simd:
2636 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2637 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2638 AllowedNameModifiers.push_back(OMPD_target);
2639 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002640 case OMPD_declare_target:
2641 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002642 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002643 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002644 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002645 llvm_unreachable("OpenMP Directive is not allowed");
2646 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002647 llvm_unreachable("Unknown OpenMP directive");
2648 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002649
Alexey Bataev4acb8592014-07-07 13:01:15 +00002650 for (auto P : VarsWithInheritedDSA) {
2651 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2652 << P.first << P.second->getSourceRange();
2653 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002654 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2655
2656 if (!AllowedNameModifiers.empty())
2657 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2658 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002659
Alexey Bataeved09d242014-05-28 05:53:51 +00002660 if (ErrorFound)
2661 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002662 return Res;
2663}
2664
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002665Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2666 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002667 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002668 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2669 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002670 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002671 assert(Linears.size() == LinModifiers.size());
2672 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002673 if (!DG || DG.get().isNull())
2674 return DeclGroupPtrTy();
2675
2676 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002677 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002678 return DG;
2679 }
2680 auto *ADecl = DG.get().getSingleDecl();
2681 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2682 ADecl = FTD->getTemplatedDecl();
2683
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002684 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2685 if (!FD) {
2686 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002687 return DeclGroupPtrTy();
2688 }
2689
Alexey Bataev2af33e32016-04-07 12:45:37 +00002690 // OpenMP [2.8.2, declare simd construct, Description]
2691 // The parameter of the simdlen clause must be a constant positive integer
2692 // expression.
2693 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002694 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002695 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002696 // OpenMP [2.8.2, declare simd construct, Description]
2697 // The special this pointer can be used as if was one of the arguments to the
2698 // function in any of the linear, aligned, or uniform clauses.
2699 // The uniform clause declares one or more arguments to have an invariant
2700 // value for all concurrent invocations of the function in the execution of a
2701 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002702 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2703 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002704 for (auto *E : Uniforms) {
2705 E = E->IgnoreParenImpCasts();
2706 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2707 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2708 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2709 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002710 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2711 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002712 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002713 }
2714 if (isa<CXXThisExpr>(E)) {
2715 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002716 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002717 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002718 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2719 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002720 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002721 // OpenMP [2.8.2, declare simd construct, Description]
2722 // The aligned clause declares that the object to which each list item points
2723 // is aligned to the number of bytes expressed in the optional parameter of
2724 // the aligned clause.
2725 // The special this pointer can be used as if was one of the arguments to the
2726 // function in any of the linear, aligned, or uniform clauses.
2727 // The type of list items appearing in the aligned clause must be array,
2728 // pointer, reference to array, or reference to pointer.
2729 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2730 Expr *AlignedThis = nullptr;
2731 for (auto *E : Aligneds) {
2732 E = E->IgnoreParenImpCasts();
2733 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2734 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2735 auto *CanonPVD = PVD->getCanonicalDecl();
2736 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2737 FD->getParamDecl(PVD->getFunctionScopeIndex())
2738 ->getCanonicalDecl() == CanonPVD) {
2739 // OpenMP [2.8.1, simd construct, Restrictions]
2740 // A list-item cannot appear in more than one aligned clause.
2741 if (AlignedArgs.count(CanonPVD) > 0) {
2742 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2743 << 1 << E->getSourceRange();
2744 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2745 diag::note_omp_explicit_dsa)
2746 << getOpenMPClauseName(OMPC_aligned);
2747 continue;
2748 }
2749 AlignedArgs[CanonPVD] = E;
2750 QualType QTy = PVD->getType()
2751 .getNonReferenceType()
2752 .getUnqualifiedType()
2753 .getCanonicalType();
2754 const Type *Ty = QTy.getTypePtrOrNull();
2755 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2756 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2757 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2758 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2759 }
2760 continue;
2761 }
2762 }
2763 if (isa<CXXThisExpr>(E)) {
2764 if (AlignedThis) {
2765 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2766 << 2 << E->getSourceRange();
2767 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2768 << getOpenMPClauseName(OMPC_aligned);
2769 }
2770 AlignedThis = E;
2771 continue;
2772 }
2773 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2774 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2775 }
2776 // The optional parameter of the aligned clause, alignment, must be a constant
2777 // positive integer expression. If no optional parameter is specified,
2778 // implementation-defined default alignments for SIMD instructions on the
2779 // target platforms are assumed.
2780 SmallVector<Expr *, 4> NewAligns;
2781 for (auto *E : Alignments) {
2782 ExprResult Align;
2783 if (E)
2784 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2785 NewAligns.push_back(Align.get());
2786 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002787 // OpenMP [2.8.2, declare simd construct, Description]
2788 // The linear clause declares one or more list items to be private to a SIMD
2789 // lane and to have a linear relationship with respect to the iteration space
2790 // of a loop.
2791 // The special this pointer can be used as if was one of the arguments to the
2792 // function in any of the linear, aligned, or uniform clauses.
2793 // When a linear-step expression is specified in a linear clause it must be
2794 // either a constant integer expression or an integer-typed parameter that is
2795 // specified in a uniform clause on the directive.
2796 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2797 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2798 auto MI = LinModifiers.begin();
2799 for (auto *E : Linears) {
2800 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2801 ++MI;
2802 E = E->IgnoreParenImpCasts();
2803 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2804 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2805 auto *CanonPVD = PVD->getCanonicalDecl();
2806 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2807 FD->getParamDecl(PVD->getFunctionScopeIndex())
2808 ->getCanonicalDecl() == CanonPVD) {
2809 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2810 // A list-item cannot appear in more than one linear clause.
2811 if (LinearArgs.count(CanonPVD) > 0) {
2812 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2813 << getOpenMPClauseName(OMPC_linear)
2814 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2815 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2816 diag::note_omp_explicit_dsa)
2817 << getOpenMPClauseName(OMPC_linear);
2818 continue;
2819 }
2820 // Each argument can appear in at most one uniform or linear clause.
2821 if (UniformedArgs.count(CanonPVD) > 0) {
2822 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2823 << getOpenMPClauseName(OMPC_linear)
2824 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2825 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2826 diag::note_omp_explicit_dsa)
2827 << getOpenMPClauseName(OMPC_uniform);
2828 continue;
2829 }
2830 LinearArgs[CanonPVD] = E;
2831 if (E->isValueDependent() || E->isTypeDependent() ||
2832 E->isInstantiationDependent() ||
2833 E->containsUnexpandedParameterPack())
2834 continue;
2835 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2836 PVD->getOriginalType());
2837 continue;
2838 }
2839 }
2840 if (isa<CXXThisExpr>(E)) {
2841 if (UniformedLinearThis) {
2842 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2843 << getOpenMPClauseName(OMPC_linear)
2844 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2845 << E->getSourceRange();
2846 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2847 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2848 : OMPC_linear);
2849 continue;
2850 }
2851 UniformedLinearThis = E;
2852 if (E->isValueDependent() || E->isTypeDependent() ||
2853 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2854 continue;
2855 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2856 E->getType());
2857 continue;
2858 }
2859 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2860 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2861 }
2862 Expr *Step = nullptr;
2863 Expr *NewStep = nullptr;
2864 SmallVector<Expr *, 4> NewSteps;
2865 for (auto *E : Steps) {
2866 // Skip the same step expression, it was checked already.
2867 if (Step == E || !E) {
2868 NewSteps.push_back(E ? NewStep : nullptr);
2869 continue;
2870 }
2871 Step = E;
2872 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2873 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2874 auto *CanonPVD = PVD->getCanonicalDecl();
2875 if (UniformedArgs.count(CanonPVD) == 0) {
2876 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2877 << Step->getSourceRange();
2878 } else if (E->isValueDependent() || E->isTypeDependent() ||
2879 E->isInstantiationDependent() ||
2880 E->containsUnexpandedParameterPack() ||
2881 CanonPVD->getType()->hasIntegerRepresentation())
2882 NewSteps.push_back(Step);
2883 else {
2884 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2885 << Step->getSourceRange();
2886 }
2887 continue;
2888 }
2889 NewStep = Step;
2890 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2891 !Step->isInstantiationDependent() &&
2892 !Step->containsUnexpandedParameterPack()) {
2893 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2894 .get();
2895 if (NewStep)
2896 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2897 }
2898 NewSteps.push_back(NewStep);
2899 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002900 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2901 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002902 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002903 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2904 const_cast<Expr **>(Linears.data()), Linears.size(),
2905 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2906 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002907 ADecl->addAttr(NewAttr);
2908 return ConvertDeclToDeclGroup(ADecl);
2909}
2910
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002911StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2912 Stmt *AStmt,
2913 SourceLocation StartLoc,
2914 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002915 if (!AStmt)
2916 return StmtError();
2917
Alexey Bataev9959db52014-05-06 10:08:46 +00002918 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2919 // 1.2.2 OpenMP Language Terminology
2920 // Structured block - An executable statement with a single entry at the
2921 // top and a single exit at the bottom.
2922 // The point of exit cannot be a branch out of the structured block.
2923 // longjmp() and throw() must not violate the entry/exit criteria.
2924 CS->getCapturedDecl()->setNothrow();
2925
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002926 getCurFunction()->setHasBranchProtectedScope();
2927
Alexey Bataev25e5b442015-09-15 12:52:43 +00002928 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2929 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002930}
2931
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002932namespace {
2933/// \brief Helper class for checking canonical form of the OpenMP loops and
2934/// extracting iteration space of each loop in the loop nest, that will be used
2935/// for IR generation.
2936class OpenMPIterationSpaceChecker {
2937 /// \brief Reference to Sema.
2938 Sema &SemaRef;
2939 /// \brief A location for diagnostics (when there is no some better location).
2940 SourceLocation DefaultLoc;
2941 /// \brief A location for diagnostics (when increment is not compatible).
2942 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002943 /// \brief A source location for referring to loop init later.
2944 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002945 /// \brief A source location for referring to condition later.
2946 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002947 /// \brief A source location for referring to increment later.
2948 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002949 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002950 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002951 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002952 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002953 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002954 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002955 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002956 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002957 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002958 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002959 /// \brief This flag is true when condition is one of:
2960 /// Var < UB
2961 /// Var <= UB
2962 /// UB > Var
2963 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002964 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002965 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002966 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002967 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002968 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002969
2970public:
2971 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002972 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002973 /// \brief Check init-expr for canonical loop form and save loop counter
2974 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002975 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002976 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2977 /// for less/greater and for strict/non-strict comparison.
2978 bool CheckCond(Expr *S);
2979 /// \brief Check incr-expr for canonical loop form and return true if it
2980 /// does not conform, otherwise save loop step (#Step).
2981 bool CheckInc(Expr *S);
2982 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002983 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002984 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002985 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002986 /// \brief Source range of the loop init.
2987 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2988 /// \brief Source range of the loop condition.
2989 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2990 /// \brief Source range of the loop increment.
2991 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2992 /// \brief True if the step should be subtracted.
2993 bool ShouldSubtractStep() const { return SubtractStep; }
2994 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002995 Expr *
2996 BuildNumIterations(Scope *S, const bool LimitedType,
2997 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002998 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002999 Expr *BuildPreCond(Scope *S, Expr *Cond,
3000 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003001 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003002 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3003 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003004 /// \brief Build reference expression to the private counter be used for
3005 /// codegen.
3006 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003007 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003008 Expr *BuildCounterInit() const;
3009 /// \brief Build step of the counter be used for codegen.
3010 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003011 /// \brief Return true if any expression is dependent.
3012 bool Dependent() const;
3013
3014private:
3015 /// \brief Check the right-hand side of an assignment in the increment
3016 /// expression.
3017 bool CheckIncRHS(Expr *RHS);
3018 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003019 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003020 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003021 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003022 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003023 /// \brief Helper to set loop increment.
3024 bool SetStep(Expr *NewStep, bool Subtract);
3025};
3026
3027bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003028 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003029 assert(!LB && !UB && !Step);
3030 return false;
3031 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003032 return LCDecl->getType()->isDependentType() ||
3033 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3034 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003035}
3036
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003037static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003038 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3039 E = ExprTemp->getSubExpr();
3040
3041 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3042 E = MTE->GetTemporaryExpr();
3043
3044 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3045 E = Binder->getSubExpr();
3046
3047 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3048 E = ICE->getSubExprAsWritten();
3049 return E->IgnoreParens();
3050}
3051
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003052bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3053 Expr *NewLCRefExpr,
3054 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003055 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003056 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003057 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003058 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003059 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003060 LCDecl = getCanonicalDecl(NewLCDecl);
3061 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003062 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3063 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003064 if ((Ctor->isCopyOrMoveConstructor() ||
3065 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3066 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003067 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003068 LB = NewLB;
3069 return false;
3070}
3071
3072bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003073 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003074 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003075 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3076 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003077 if (!NewUB)
3078 return true;
3079 UB = NewUB;
3080 TestIsLessOp = LessOp;
3081 TestIsStrictOp = StrictOp;
3082 ConditionSrcRange = SR;
3083 ConditionLoc = SL;
3084 return false;
3085}
3086
3087bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3088 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003089 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003090 if (!NewStep)
3091 return true;
3092 if (!NewStep->isValueDependent()) {
3093 // Check that the step is integer expression.
3094 SourceLocation StepLoc = NewStep->getLocStart();
3095 ExprResult Val =
3096 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3097 if (Val.isInvalid())
3098 return true;
3099 NewStep = Val.get();
3100
3101 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3102 // If test-expr is of form var relational-op b and relational-op is < or
3103 // <= then incr-expr must cause var to increase on each iteration of the
3104 // loop. If test-expr is of form var relational-op b and relational-op is
3105 // > or >= then incr-expr must cause var to decrease on each iteration of
3106 // the loop.
3107 // If test-expr is of form b relational-op var and relational-op is < or
3108 // <= then incr-expr must cause var to decrease on each iteration of the
3109 // loop. If test-expr is of form b relational-op var and relational-op is
3110 // > or >= then incr-expr must cause var to increase on each iteration of
3111 // the loop.
3112 llvm::APSInt Result;
3113 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3114 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3115 bool IsConstNeg =
3116 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003117 bool IsConstPos =
3118 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003119 bool IsConstZero = IsConstant && !Result.getBoolValue();
3120 if (UB && (IsConstZero ||
3121 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003122 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003123 SemaRef.Diag(NewStep->getExprLoc(),
3124 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003125 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003126 SemaRef.Diag(ConditionLoc,
3127 diag::note_omp_loop_cond_requres_compatible_incr)
3128 << TestIsLessOp << ConditionSrcRange;
3129 return true;
3130 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003131 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003132 NewStep =
3133 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3134 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003135 Subtract = !Subtract;
3136 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003137 }
3138
3139 Step = NewStep;
3140 SubtractStep = Subtract;
3141 return false;
3142}
3143
Alexey Bataev9c821032015-04-30 04:23:23 +00003144bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003145 // Check init-expr for canonical loop form and save loop counter
3146 // variable - #Var and its initialization value - #LB.
3147 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3148 // var = lb
3149 // integer-type var = lb
3150 // random-access-iterator-type var = lb
3151 // pointer-type var = lb
3152 //
3153 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003154 if (EmitDiags) {
3155 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3156 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003157 return true;
3158 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003159 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3160 if (!ExprTemp->cleanupsHaveSideEffects())
3161 S = ExprTemp->getSubExpr();
3162
Alexander Musmana5f070a2014-10-01 06:03:56 +00003163 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003164 if (Expr *E = dyn_cast<Expr>(S))
3165 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003166 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003167 if (BO->getOpcode() == BO_Assign) {
3168 auto *LHS = BO->getLHS()->IgnoreParens();
3169 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3170 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3171 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3172 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3173 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3174 }
3175 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3176 if (ME->isArrow() &&
3177 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3178 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3179 }
3180 }
David Majnemer9d168222016-08-05 17:44:54 +00003181 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003182 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003183 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003184 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003185 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003186 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003187 SemaRef.Diag(S->getLocStart(),
3188 diag::ext_omp_loop_not_canonical_init)
3189 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003190 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003191 }
3192 }
3193 }
David Majnemer9d168222016-08-05 17:44:54 +00003194 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003195 if (CE->getOperator() == OO_Equal) {
3196 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003197 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003198 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3199 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3200 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3201 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3202 }
3203 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3204 if (ME->isArrow() &&
3205 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3206 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3207 }
3208 }
3209 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003210
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003211 if (Dependent() || SemaRef.CurContext->isDependentContext())
3212 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003213 if (EmitDiags) {
3214 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3215 << S->getSourceRange();
3216 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003217 return true;
3218}
3219
Alexey Bataev23b69422014-06-18 07:08:49 +00003220/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003221/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003222static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003223 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003224 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003225 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003226 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3227 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003228 if ((Ctor->isCopyOrMoveConstructor() ||
3229 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3230 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003231 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003232 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3233 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3234 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3235 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3236 return getCanonicalDecl(ME->getMemberDecl());
3237 return getCanonicalDecl(VD);
3238 }
3239 }
3240 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3241 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3242 return getCanonicalDecl(ME->getMemberDecl());
3243 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003244}
3245
3246bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3247 // Check test-expr for canonical form, save upper-bound UB, flags for
3248 // less/greater and for strict/non-strict comparison.
3249 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3250 // var relational-op b
3251 // b relational-op var
3252 //
3253 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003254 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003255 return true;
3256 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003257 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003258 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003259 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003260 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003261 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003262 return SetUB(BO->getRHS(),
3263 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3264 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3265 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003266 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003267 return SetUB(BO->getLHS(),
3268 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3269 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3270 BO->getSourceRange(), BO->getOperatorLoc());
3271 }
David Majnemer9d168222016-08-05 17:44:54 +00003272 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003273 if (CE->getNumArgs() == 2) {
3274 auto Op = CE->getOperator();
3275 switch (Op) {
3276 case OO_Greater:
3277 case OO_GreaterEqual:
3278 case OO_Less:
3279 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003280 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003281 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3282 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3283 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003284 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003285 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3286 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3287 CE->getOperatorLoc());
3288 break;
3289 default:
3290 break;
3291 }
3292 }
3293 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003294 if (Dependent() || SemaRef.CurContext->isDependentContext())
3295 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003296 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003297 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003298 return true;
3299}
3300
3301bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3302 // RHS of canonical loop form increment can be:
3303 // var + incr
3304 // incr + var
3305 // var - incr
3306 //
3307 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003308 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003309 if (BO->isAdditiveOp()) {
3310 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003311 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003312 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003313 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003314 return SetStep(BO->getLHS(), false);
3315 }
David Majnemer9d168222016-08-05 17:44:54 +00003316 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003317 bool IsAdd = CE->getOperator() == OO_Plus;
3318 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003319 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003320 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003321 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003322 return SetStep(CE->getArg(0), false);
3323 }
3324 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003325 if (Dependent() || SemaRef.CurContext->isDependentContext())
3326 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003327 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003328 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003329 return true;
3330}
3331
3332bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3333 // Check incr-expr for canonical loop form and return true if it
3334 // does not conform.
3335 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3336 // ++var
3337 // var++
3338 // --var
3339 // var--
3340 // var += incr
3341 // var -= incr
3342 // var = var + incr
3343 // var = incr + var
3344 // var = var - incr
3345 //
3346 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003347 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003348 return true;
3349 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003350 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3351 if (!ExprTemp->cleanupsHaveSideEffects())
3352 S = ExprTemp->getSubExpr();
3353
Alexander Musmana5f070a2014-10-01 06:03:56 +00003354 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003355 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003356 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003357 if (UO->isIncrementDecrementOp() &&
3358 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003359 return SetStep(SemaRef
3360 .ActOnIntegerConstant(UO->getLocStart(),
3361 (UO->isDecrementOp() ? -1 : 1))
3362 .get(),
3363 false);
3364 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003365 switch (BO->getOpcode()) {
3366 case BO_AddAssign:
3367 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003368 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003369 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3370 break;
3371 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003372 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003373 return CheckIncRHS(BO->getRHS());
3374 break;
3375 default:
3376 break;
3377 }
David Majnemer9d168222016-08-05 17:44:54 +00003378 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003379 switch (CE->getOperator()) {
3380 case OO_PlusPlus:
3381 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003382 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003383 return SetStep(SemaRef
3384 .ActOnIntegerConstant(
3385 CE->getLocStart(),
3386 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3387 .get(),
3388 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003389 break;
3390 case OO_PlusEqual:
3391 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003392 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003393 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3394 break;
3395 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003396 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003397 return CheckIncRHS(CE->getArg(1));
3398 break;
3399 default:
3400 break;
3401 }
3402 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003403 if (Dependent() || SemaRef.CurContext->isDependentContext())
3404 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003405 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003406 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003407 return true;
3408}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003409
Alexey Bataev5a3af132016-03-29 08:58:54 +00003410static ExprResult
3411tryBuildCapture(Sema &SemaRef, Expr *Capture,
3412 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003413 if (SemaRef.CurContext->isDependentContext())
3414 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003415 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3416 return SemaRef.PerformImplicitConversion(
3417 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3418 /*AllowExplicit=*/true);
3419 auto I = Captures.find(Capture);
3420 if (I != Captures.end())
3421 return buildCapture(SemaRef, Capture, I->second);
3422 DeclRefExpr *Ref = nullptr;
3423 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3424 Captures[Capture] = Ref;
3425 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003426}
3427
Alexander Musmana5f070a2014-10-01 06:03:56 +00003428/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003429Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3430 Scope *S, const bool LimitedType,
3431 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003432 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003433 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003434 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003435 SemaRef.getLangOpts().CPlusPlus) {
3436 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003437 auto *UBExpr = TestIsLessOp ? UB : LB;
3438 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003439 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3440 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003441 if (!Upper || !Lower)
3442 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003443
3444 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3445
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003446 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003447 // BuildBinOp already emitted error, this one is to point user to upper
3448 // and lower bound, and to tell what is passed to 'operator-'.
3449 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3450 << Upper->getSourceRange() << Lower->getSourceRange();
3451 return nullptr;
3452 }
3453 }
3454
3455 if (!Diff.isUsable())
3456 return nullptr;
3457
3458 // Upper - Lower [- 1]
3459 if (TestIsStrictOp)
3460 Diff = SemaRef.BuildBinOp(
3461 S, DefaultLoc, BO_Sub, Diff.get(),
3462 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3463 if (!Diff.isUsable())
3464 return nullptr;
3465
3466 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003467 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3468 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003469 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003470 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003471 if (!Diff.isUsable())
3472 return nullptr;
3473
3474 // Parentheses (for dumping/debugging purposes only).
3475 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3476 if (!Diff.isUsable())
3477 return nullptr;
3478
3479 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003480 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003481 if (!Diff.isUsable())
3482 return nullptr;
3483
Alexander Musman174b3ca2014-10-06 11:16:29 +00003484 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003485 QualType Type = Diff.get()->getType();
3486 auto &C = SemaRef.Context;
3487 bool UseVarType = VarType->hasIntegerRepresentation() &&
3488 C.getTypeSize(Type) > C.getTypeSize(VarType);
3489 if (!Type->isIntegerType() || UseVarType) {
3490 unsigned NewSize =
3491 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3492 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3493 : Type->hasSignedIntegerRepresentation();
3494 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003495 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3496 Diff = SemaRef.PerformImplicitConversion(
3497 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3498 if (!Diff.isUsable())
3499 return nullptr;
3500 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003501 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003502 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003503 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3504 if (NewSize != C.getTypeSize(Type)) {
3505 if (NewSize < C.getTypeSize(Type)) {
3506 assert(NewSize == 64 && "incorrect loop var size");
3507 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3508 << InitSrcRange << ConditionSrcRange;
3509 }
3510 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003511 NewSize, Type->hasSignedIntegerRepresentation() ||
3512 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003513 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3514 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3515 Sema::AA_Converting, true);
3516 if (!Diff.isUsable())
3517 return nullptr;
3518 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003519 }
3520 }
3521
Alexander Musmana5f070a2014-10-01 06:03:56 +00003522 return Diff.get();
3523}
3524
Alexey Bataev5a3af132016-03-29 08:58:54 +00003525Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3526 Scope *S, Expr *Cond,
3527 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003528 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3529 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3530 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003531
Alexey Bataev5a3af132016-03-29 08:58:54 +00003532 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3533 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3534 if (!NewLB.isUsable() || !NewUB.isUsable())
3535 return nullptr;
3536
Alexey Bataev62dbb972015-04-22 11:59:37 +00003537 auto CondExpr = SemaRef.BuildBinOp(
3538 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3539 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003540 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003541 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003542 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3543 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003544 CondExpr = SemaRef.PerformImplicitConversion(
3545 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3546 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003547 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003548 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3549 // Otherwise use original loop conditon and evaluate it in runtime.
3550 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3551}
3552
Alexander Musmana5f070a2014-10-01 06:03:56 +00003553/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003554DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003555 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003556 auto *VD = dyn_cast<VarDecl>(LCDecl);
3557 if (!VD) {
3558 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3559 auto *Ref = buildDeclRefExpr(
3560 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003561 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3562 // If the loop control decl is explicitly marked as private, do not mark it
3563 // as captured again.
3564 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3565 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003566 return Ref;
3567 }
3568 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003569 DefaultLoc);
3570}
3571
3572Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003573 if (LCDecl && !LCDecl->isInvalidDecl()) {
3574 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003575 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003576 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3577 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003578 if (PrivateVar->isInvalidDecl())
3579 return nullptr;
3580 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3581 }
3582 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003583}
3584
Samuel Antao4c8035b2016-12-12 18:00:20 +00003585/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3587
3588/// \brief Build step of the counter be used for codegen.
3589Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3590
3591/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003592struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003593 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003594 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003595 /// \brief This expression calculates the number of iterations in the loop.
3596 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003597 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003598 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003599 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003600 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003601 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003602 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003603 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003604 /// \brief This is step for the #CounterVar used to generate its update:
3605 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003606 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003607 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003608 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003609 /// \brief Source range of the loop init.
3610 SourceRange InitSrcRange;
3611 /// \brief Source range of the loop condition.
3612 SourceRange CondSrcRange;
3613 /// \brief Source range of the loop increment.
3614 SourceRange IncSrcRange;
3615};
3616
Alexey Bataev23b69422014-06-18 07:08:49 +00003617} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003618
Alexey Bataev9c821032015-04-30 04:23:23 +00003619void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3620 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3621 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003622 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3623 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003624 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3625 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003626 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3627 if (auto *D = ISC.GetLoopDecl()) {
3628 auto *VD = dyn_cast<VarDecl>(D);
3629 if (!VD) {
3630 if (auto *Private = IsOpenMPCapturedDecl(D))
3631 VD = Private;
3632 else {
3633 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3634 /*WithInit=*/false);
3635 VD = cast<VarDecl>(Ref->getDecl());
3636 }
3637 }
3638 DSAStack->addLoopControlVariable(D, VD);
3639 }
3640 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003641 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003642 }
3643}
3644
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003645/// \brief Called on a for stmt to check and extract its iteration space
3646/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003647static bool CheckOpenMPIterationSpace(
3648 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3649 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003650 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003651 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003652 LoopIterationSpace &ResultIterSpace,
3653 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003654 // OpenMP [2.6, Canonical Loop Form]
3655 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003656 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003657 if (!For) {
3658 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003659 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3660 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3661 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3662 if (NestedLoopCount > 1) {
3663 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3664 SemaRef.Diag(DSA.getConstructLoc(),
3665 diag::note_omp_collapse_ordered_expr)
3666 << 2 << CollapseLoopCountExpr->getSourceRange()
3667 << OrderedLoopCountExpr->getSourceRange();
3668 else if (CollapseLoopCountExpr)
3669 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3670 diag::note_omp_collapse_ordered_expr)
3671 << 0 << CollapseLoopCountExpr->getSourceRange();
3672 else
3673 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3674 diag::note_omp_collapse_ordered_expr)
3675 << 1 << OrderedLoopCountExpr->getSourceRange();
3676 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003677 return true;
3678 }
3679 assert(For->getBody());
3680
3681 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3682
3683 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003684 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003685 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003686 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003687
3688 bool HasErrors = false;
3689
3690 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003691 if (auto *LCDecl = ISC.GetLoopDecl()) {
3692 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003693
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003694 // OpenMP [2.6, Canonical Loop Form]
3695 // Var is one of the following:
3696 // A variable of signed or unsigned integer type.
3697 // For C++, a variable of a random access iterator type.
3698 // For C, a variable of a pointer type.
3699 auto VarType = LCDecl->getType().getNonReferenceType();
3700 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3701 !VarType->isPointerType() &&
3702 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3703 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3704 << SemaRef.getLangOpts().CPlusPlus;
3705 HasErrors = true;
3706 }
3707
3708 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3709 // a Construct
3710 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3711 // parallel for construct is (are) private.
3712 // The loop iteration variable in the associated for-loop of a simd
3713 // construct with just one associated for-loop is linear with a
3714 // constant-linear-step that is the increment of the associated for-loop.
3715 // Exclude loop var from the list of variables with implicitly defined data
3716 // sharing attributes.
3717 VarsWithImplicitDSA.erase(LCDecl);
3718
3719 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3720 // in a Construct, C/C++].
3721 // The loop iteration variable in the associated for-loop of a simd
3722 // construct with just one associated for-loop may be listed in a linear
3723 // clause with a constant-linear-step that is the increment of the
3724 // associated for-loop.
3725 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3726 // parallel for construct may be listed in a private or lastprivate clause.
3727 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3728 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3729 // declared in the loop and it is predetermined as a private.
3730 auto PredeterminedCKind =
3731 isOpenMPSimdDirective(DKind)
3732 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3733 : OMPC_private;
3734 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3735 DVar.CKind != PredeterminedCKind) ||
3736 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3737 isOpenMPDistributeDirective(DKind)) &&
3738 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3739 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3740 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3741 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3742 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3743 << getOpenMPClauseName(PredeterminedCKind);
3744 if (DVar.RefExpr == nullptr)
3745 DVar.CKind = PredeterminedCKind;
3746 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3747 HasErrors = true;
3748 } else if (LoopDeclRefExpr != nullptr) {
3749 // Make the loop iteration variable private (for worksharing constructs),
3750 // linear (for simd directives with the only one associated loop) or
3751 // lastprivate (for simd directives with several collapsed or ordered
3752 // loops).
3753 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003754 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3755 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003756 /*FromParent=*/false);
3757 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3758 }
3759
3760 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3761
3762 // Check test-expr.
3763 HasErrors |= ISC.CheckCond(For->getCond());
3764
3765 // Check incr-expr.
3766 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003767 }
3768
Alexander Musmana5f070a2014-10-01 06:03:56 +00003769 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003770 return HasErrors;
3771
Alexander Musmana5f070a2014-10-01 06:03:56 +00003772 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003773 ResultIterSpace.PreCond =
3774 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003775 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003776 DSA.getCurScope(),
3777 (isOpenMPWorksharingDirective(DKind) ||
3778 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3779 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003780 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003781 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003782 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3783 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3784 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3785 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3786 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3787 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3788
Alexey Bataev62dbb972015-04-22 11:59:37 +00003789 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3790 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003792 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003793 ResultIterSpace.CounterInit == nullptr ||
3794 ResultIterSpace.CounterStep == nullptr);
3795
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003796 return HasErrors;
3797}
3798
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003799/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003800static ExprResult
3801BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3802 ExprResult Start,
3803 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003804 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003805 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3806 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003807 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003808 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003809 VarRef.get()->getType())) {
3810 NewStart = SemaRef.PerformImplicitConversion(
3811 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3812 /*AllowExplicit=*/true);
3813 if (!NewStart.isUsable())
3814 return ExprError();
3815 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003816
3817 auto Init =
3818 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3819 return Init;
3820}
3821
Alexander Musmana5f070a2014-10-01 06:03:56 +00003822/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003823static ExprResult
3824BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3825 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3826 ExprResult Step, bool Subtract,
3827 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003828 // Add parentheses (for debugging purposes only).
3829 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3830 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3831 !Step.isUsable())
3832 return ExprError();
3833
Alexey Bataev5a3af132016-03-29 08:58:54 +00003834 ExprResult NewStep = Step;
3835 if (Captures)
3836 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003837 if (NewStep.isInvalid())
3838 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003839 ExprResult Update =
3840 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003841 if (!Update.isUsable())
3842 return ExprError();
3843
Alexey Bataevc0214e02016-02-16 12:13:49 +00003844 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3845 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003846 ExprResult NewStart = Start;
3847 if (Captures)
3848 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003849 if (NewStart.isInvalid())
3850 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003851
Alexey Bataevc0214e02016-02-16 12:13:49 +00003852 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3853 ExprResult SavedUpdate = Update;
3854 ExprResult UpdateVal;
3855 if (VarRef.get()->getType()->isOverloadableType() ||
3856 NewStart.get()->getType()->isOverloadableType() ||
3857 Update.get()->getType()->isOverloadableType()) {
3858 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3859 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3860 Update =
3861 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3862 if (Update.isUsable()) {
3863 UpdateVal =
3864 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3865 VarRef.get(), SavedUpdate.get());
3866 if (UpdateVal.isUsable()) {
3867 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3868 UpdateVal.get());
3869 }
3870 }
3871 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3872 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003873
Alexey Bataevc0214e02016-02-16 12:13:49 +00003874 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3875 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3876 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3877 NewStart.get(), SavedUpdate.get());
3878 if (!Update.isUsable())
3879 return ExprError();
3880
Alexey Bataev11481f52016-02-17 10:29:05 +00003881 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3882 VarRef.get()->getType())) {
3883 Update = SemaRef.PerformImplicitConversion(
3884 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3885 if (!Update.isUsable())
3886 return ExprError();
3887 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003888
3889 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3890 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003891 return Update;
3892}
3893
3894/// \brief Convert integer expression \a E to make it have at least \a Bits
3895/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003896static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003897 if (E == nullptr)
3898 return ExprError();
3899 auto &C = SemaRef.Context;
3900 QualType OldType = E->getType();
3901 unsigned HasBits = C.getTypeSize(OldType);
3902 if (HasBits >= Bits)
3903 return ExprResult(E);
3904 // OK to convert to signed, because new type has more bits than old.
3905 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3906 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3907 true);
3908}
3909
3910/// \brief Check if the given expression \a E is a constant integer that fits
3911/// into \a Bits bits.
3912static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3913 if (E == nullptr)
3914 return false;
3915 llvm::APSInt Result;
3916 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3917 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3918 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003919}
3920
Alexey Bataev5a3af132016-03-29 08:58:54 +00003921/// Build preinits statement for the given declarations.
3922static Stmt *buildPreInits(ASTContext &Context,
3923 SmallVectorImpl<Decl *> &PreInits) {
3924 if (!PreInits.empty()) {
3925 return new (Context) DeclStmt(
3926 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3927 SourceLocation(), SourceLocation());
3928 }
3929 return nullptr;
3930}
3931
3932/// Build preinits statement for the given declarations.
3933static Stmt *buildPreInits(ASTContext &Context,
3934 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3935 if (!Captures.empty()) {
3936 SmallVector<Decl *, 16> PreInits;
3937 for (auto &Pair : Captures)
3938 PreInits.push_back(Pair.second->getDecl());
3939 return buildPreInits(Context, PreInits);
3940 }
3941 return nullptr;
3942}
3943
3944/// Build postupdate expression for the given list of postupdates expressions.
3945static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3946 Expr *PostUpdate = nullptr;
3947 if (!PostUpdates.empty()) {
3948 for (auto *E : PostUpdates) {
3949 Expr *ConvE = S.BuildCStyleCastExpr(
3950 E->getExprLoc(),
3951 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3952 E->getExprLoc(), E)
3953 .get();
3954 PostUpdate = PostUpdate
3955 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3956 PostUpdate, ConvE)
3957 .get()
3958 : ConvE;
3959 }
3960 }
3961 return PostUpdate;
3962}
3963
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003964/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003965/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3966/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003967static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003968CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3969 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3970 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003971 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003972 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003973 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003974 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003975 // Found 'collapse' clause - calculate collapse number.
3976 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003977 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003978 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003979 }
3980 if (OrderedLoopCountExpr) {
3981 // Found 'ordered' clause - calculate collapse number.
3982 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003983 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3984 if (Result.getLimitedValue() < NestedLoopCount) {
3985 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3986 diag::err_omp_wrong_ordered_loop_count)
3987 << OrderedLoopCountExpr->getSourceRange();
3988 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3989 diag::note_collapse_loop_count)
3990 << CollapseLoopCountExpr->getSourceRange();
3991 }
3992 NestedLoopCount = Result.getLimitedValue();
3993 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003994 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003995 // This is helper routine for loop directives (e.g., 'for', 'simd',
3996 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003997 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003998 SmallVector<LoopIterationSpace, 4> IterSpaces;
3999 IterSpaces.resize(NestedLoopCount);
4000 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004001 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004002 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004003 NestedLoopCount, CollapseLoopCountExpr,
4004 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004005 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004006 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004007 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004008 // OpenMP [2.8.1, simd construct, Restrictions]
4009 // All loops associated with the construct must be perfectly nested; that
4010 // is, there must be no intervening code nor any OpenMP directive between
4011 // any two loops.
4012 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004013 }
4014
Alexander Musmana5f070a2014-10-01 06:03:56 +00004015 Built.clear(/* size */ NestedLoopCount);
4016
4017 if (SemaRef.CurContext->isDependentContext())
4018 return NestedLoopCount;
4019
4020 // An example of what is generated for the following code:
4021 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004022 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004023 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004024 // for (k = 0; k < NK; ++k)
4025 // for (j = J0; j < NJ; j+=2) {
4026 // <loop body>
4027 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004028 //
4029 // We generate the code below.
4030 // Note: the loop body may be outlined in CodeGen.
4031 // Note: some counters may be C++ classes, operator- is used to find number of
4032 // iterations and operator+= to calculate counter value.
4033 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4034 // or i64 is currently supported).
4035 //
4036 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4037 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4038 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4039 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4040 // // similar updates for vars in clauses (e.g. 'linear')
4041 // <loop body (using local i and j)>
4042 // }
4043 // i = NI; // assign final values of counters
4044 // j = NJ;
4045 //
4046
4047 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4048 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004049 // Precondition tests if there is at least one iteration (all conditions are
4050 // true).
4051 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004052 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004053 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004054 32 /* Bits */, SemaRef
4055 .PerformImplicitConversion(
4056 N0->IgnoreImpCasts(), N0->getType(),
4057 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004058 .get(),
4059 SemaRef);
4060 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004061 64 /* Bits */, SemaRef
4062 .PerformImplicitConversion(
4063 N0->IgnoreImpCasts(), N0->getType(),
4064 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004065 .get(),
4066 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004067
4068 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4069 return NestedLoopCount;
4070
4071 auto &C = SemaRef.Context;
4072 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4073
4074 Scope *CurScope = DSA.getCurScope();
4075 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004076 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004077 PreCond =
4078 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4079 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004080 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004081 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004082 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004083 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4084 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004085 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004086 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004087 SemaRef
4088 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4089 Sema::AA_Converting,
4090 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004091 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004092 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004093 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004094 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004095 SemaRef
4096 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4097 Sema::AA_Converting,
4098 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004099 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004100 }
4101
4102 // Choose either the 32-bit or 64-bit version.
4103 ExprResult LastIteration = LastIteration64;
4104 if (LastIteration32.isUsable() &&
4105 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4106 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4107 FitsInto(
4108 32 /* Bits */,
4109 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4110 LastIteration64.get(), SemaRef)))
4111 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004112 QualType VType = LastIteration.get()->getType();
4113 QualType RealVType = VType;
4114 QualType StrideVType = VType;
4115 if (isOpenMPTaskLoopDirective(DKind)) {
4116 VType =
4117 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4118 StrideVType =
4119 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4120 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004121
4122 if (!LastIteration.isUsable())
4123 return 0;
4124
4125 // Save the number of iterations.
4126 ExprResult NumIterations = LastIteration;
4127 {
4128 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004129 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4130 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004131 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4132 if (!LastIteration.isUsable())
4133 return 0;
4134 }
4135
4136 // Calculate the last iteration number beforehand instead of doing this on
4137 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4138 llvm::APSInt Result;
4139 bool IsConstant =
4140 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4141 ExprResult CalcLastIteration;
4142 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004143 ExprResult SaveRef =
4144 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004145 LastIteration = SaveRef;
4146
4147 // Prepare SaveRef + 1.
4148 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004149 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004150 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4151 if (!NumIterations.isUsable())
4152 return 0;
4153 }
4154
4155 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4156
David Majnemer9d168222016-08-05 17:44:54 +00004157 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004158 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004159 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4160 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004161 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004162 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4163 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004164 SemaRef.AddInitializerToDecl(LBDecl,
4165 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4166 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004167
4168 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004169 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4170 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004171 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004172 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004173
4174 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4175 // This will be used to implement clause 'lastprivate'.
4176 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004177 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4178 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004179 SemaRef.AddInitializerToDecl(ILDecl,
4180 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4181 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004182
4183 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004184 VarDecl *STDecl =
4185 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4186 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004187 SemaRef.AddInitializerToDecl(STDecl,
4188 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4189 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004190
4191 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004192 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004193 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4194 UB.get(), LastIteration.get());
4195 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4196 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4197 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4198 CondOp.get());
4199 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004200
4201 // If we have a combined directive that combines 'distribute', 'for' or
4202 // 'simd' we need to be able to access the bounds of the schedule of the
4203 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4204 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4205 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004206
Carlo Bertolliffafe102017-04-20 00:39:39 +00004207 // Lower bound variable, initialized with zero.
4208 VarDecl *CombLBDecl =
4209 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4210 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4211 SemaRef.AddInitializerToDecl(
4212 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4213 /*DirectInit*/ false);
4214
4215 // Upper bound variable, initialized with last iteration number.
4216 VarDecl *CombUBDecl =
4217 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4218 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4219 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4220 /*DirectInit*/ false);
4221
4222 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4223 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4224 ExprResult CombCondOp =
4225 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4226 LastIteration.get(), CombUB.get());
4227 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4228 CombCondOp.get());
4229 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4230
4231 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004232 // We expect to have at least 2 more parameters than the 'parallel'
4233 // directive does - the lower and upper bounds of the previous schedule.
4234 assert(CD->getNumParams() >= 4 &&
4235 "Unexpected number of parameters in loop combined directive");
4236
4237 // Set the proper type for the bounds given what we learned from the
4238 // enclosed loops.
4239 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4240 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4241
4242 // Previous lower and upper bounds are obtained from the region
4243 // parameters.
4244 PrevLB =
4245 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4246 PrevUB =
4247 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4248 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004249 }
4250
4251 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004252 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004253 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004254 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004255 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4256 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004257 Expr *RHS =
4258 (isOpenMPWorksharingDirective(DKind) ||
4259 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4260 ? LB.get()
4261 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004262 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4263 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004264
4265 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4266 Expr *CombRHS =
4267 (isOpenMPWorksharingDirective(DKind) ||
4268 isOpenMPTaskLoopDirective(DKind) ||
4269 isOpenMPDistributeDirective(DKind))
4270 ? CombLB.get()
4271 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4272 CombInit =
4273 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4274 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4275 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004276 }
4277
Alexander Musmanc6388682014-12-15 07:07:06 +00004278 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004279 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004280 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004281 (isOpenMPWorksharingDirective(DKind) ||
4282 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004283 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4284 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4285 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004286 ExprResult CombCond;
4287 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4288 CombCond =
4289 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4290 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004291 // Loop increment (IV = IV + 1)
4292 SourceLocation IncLoc;
4293 ExprResult Inc =
4294 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4295 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4296 if (!Inc.isUsable())
4297 return 0;
4298 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004299 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4300 if (!Inc.isUsable())
4301 return 0;
4302
4303 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4304 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004305 // In combined construct, add combined version that use CombLB and CombUB
4306 // base variables for the update
4307 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004308 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4309 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004310 // LB + ST
4311 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4312 if (!NextLB.isUsable())
4313 return 0;
4314 // LB = LB + ST
4315 NextLB =
4316 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4317 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4318 if (!NextLB.isUsable())
4319 return 0;
4320 // UB + ST
4321 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4322 if (!NextUB.isUsable())
4323 return 0;
4324 // UB = UB + ST
4325 NextUB =
4326 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4327 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4328 if (!NextUB.isUsable())
4329 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004330 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4331 CombNextLB =
4332 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4333 if (!NextLB.isUsable())
4334 return 0;
4335 // LB = LB + ST
4336 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4337 CombNextLB.get());
4338 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4339 if (!CombNextLB.isUsable())
4340 return 0;
4341 // UB + ST
4342 CombNextUB =
4343 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4344 if (!CombNextUB.isUsable())
4345 return 0;
4346 // UB = UB + ST
4347 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4348 CombNextUB.get());
4349 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4350 if (!CombNextUB.isUsable())
4351 return 0;
4352 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004353 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004354
Carlo Bertolliffafe102017-04-20 00:39:39 +00004355 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004356 // directive with for as IV = IV + ST; ensure upper bound expression based
4357 // on PrevUB instead of NumIterations - used to implement 'for' when found
4358 // in combination with 'distribute', like in 'distribute parallel for'
4359 SourceLocation DistIncLoc;
4360 ExprResult DistCond, DistInc, PrevEUB;
4361 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4362 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4363 assert(DistCond.isUsable() && "distribute cond expr was not built");
4364
4365 DistInc =
4366 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4367 assert(DistInc.isUsable() && "distribute inc expr was not built");
4368 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4369 DistInc.get());
4370 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4371 assert(DistInc.isUsable() && "distribute inc expr was not built");
4372
4373 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4374 // construct
4375 SourceLocation DistEUBLoc;
4376 ExprResult IsUBGreater =
4377 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4378 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4379 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4380 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4381 CondOp.get());
4382 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4383 }
4384
Alexander Musmana5f070a2014-10-01 06:03:56 +00004385 // Build updates and final values of the loop counters.
4386 bool HasErrors = false;
4387 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004388 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004389 Built.Updates.resize(NestedLoopCount);
4390 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004391 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004392 {
4393 ExprResult Div;
4394 // Go from inner nested loop to outer.
4395 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4396 LoopIterationSpace &IS = IterSpaces[Cnt];
4397 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4398 // Build: Iter = (IV / Div) % IS.NumIters
4399 // where Div is product of previous iterations' IS.NumIters.
4400 ExprResult Iter;
4401 if (Div.isUsable()) {
4402 Iter =
4403 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4404 } else {
4405 Iter = IV;
4406 assert((Cnt == (int)NestedLoopCount - 1) &&
4407 "unusable div expected on first iteration only");
4408 }
4409
4410 if (Cnt != 0 && Iter.isUsable())
4411 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4412 IS.NumIterations);
4413 if (!Iter.isUsable()) {
4414 HasErrors = true;
4415 break;
4416 }
4417
Alexey Bataev39f915b82015-05-08 10:41:21 +00004418 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004419 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4420 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4421 IS.CounterVar->getExprLoc(),
4422 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004423 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004424 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004425 if (!Init.isUsable()) {
4426 HasErrors = true;
4427 break;
4428 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004429 ExprResult Update = BuildCounterUpdate(
4430 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4431 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004432 if (!Update.isUsable()) {
4433 HasErrors = true;
4434 break;
4435 }
4436
4437 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4438 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004439 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004440 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004441 if (!Final.isUsable()) {
4442 HasErrors = true;
4443 break;
4444 }
4445
4446 // Build Div for the next iteration: Div <- Div * IS.NumIters
4447 if (Cnt != 0) {
4448 if (Div.isUnset())
4449 Div = IS.NumIterations;
4450 else
4451 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4452 IS.NumIterations);
4453
4454 // Add parentheses (for debugging purposes only).
4455 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004456 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004457 if (!Div.isUsable()) {
4458 HasErrors = true;
4459 break;
4460 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004461 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004462 }
4463 if (!Update.isUsable() || !Final.isUsable()) {
4464 HasErrors = true;
4465 break;
4466 }
4467 // Save results
4468 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004469 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004470 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004471 Built.Updates[Cnt] = Update.get();
4472 Built.Finals[Cnt] = Final.get();
4473 }
4474 }
4475
4476 if (HasErrors)
4477 return 0;
4478
4479 // Save results
4480 Built.IterationVarRef = IV.get();
4481 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004482 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004483 Built.CalcLastIteration =
4484 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004485 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004486 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004487 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004488 Built.Init = Init.get();
4489 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004490 Built.LB = LB.get();
4491 Built.UB = UB.get();
4492 Built.IL = IL.get();
4493 Built.ST = ST.get();
4494 Built.EUB = EUB.get();
4495 Built.NLB = NextLB.get();
4496 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004497 Built.PrevLB = PrevLB.get();
4498 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004499 Built.DistInc = DistInc.get();
4500 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004501 Built.DistCombinedFields.LB = CombLB.get();
4502 Built.DistCombinedFields.UB = CombUB.get();
4503 Built.DistCombinedFields.EUB = CombEUB.get();
4504 Built.DistCombinedFields.Init = CombInit.get();
4505 Built.DistCombinedFields.Cond = CombCond.get();
4506 Built.DistCombinedFields.NLB = CombNextLB.get();
4507 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004508
Alexey Bataev8b427062016-05-25 12:36:08 +00004509 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4510 // Fill data for doacross depend clauses.
4511 for (auto Pair : DSA.getDoacrossDependClauses()) {
4512 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4513 Pair.first->setCounterValue(CounterVal);
4514 else {
4515 if (NestedLoopCount != Pair.second.size() ||
4516 NestedLoopCount != LoopMultipliers.size() + 1) {
4517 // Erroneous case - clause has some problems.
4518 Pair.first->setCounterValue(CounterVal);
4519 continue;
4520 }
4521 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4522 auto I = Pair.second.rbegin();
4523 auto IS = IterSpaces.rbegin();
4524 auto ILM = LoopMultipliers.rbegin();
4525 Expr *UpCounterVal = CounterVal;
4526 Expr *Multiplier = nullptr;
4527 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4528 if (I->first) {
4529 assert(IS->CounterStep);
4530 Expr *NormalizedOffset =
4531 SemaRef
4532 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4533 I->first, IS->CounterStep)
4534 .get();
4535 if (Multiplier) {
4536 NormalizedOffset =
4537 SemaRef
4538 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4539 NormalizedOffset, Multiplier)
4540 .get();
4541 }
4542 assert(I->second == OO_Plus || I->second == OO_Minus);
4543 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004544 UpCounterVal = SemaRef
4545 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4546 UpCounterVal, NormalizedOffset)
4547 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004548 }
4549 Multiplier = *ILM;
4550 ++I;
4551 ++IS;
4552 ++ILM;
4553 }
4554 Pair.first->setCounterValue(UpCounterVal);
4555 }
4556 }
4557
Alexey Bataevabfc0692014-06-25 06:52:00 +00004558 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004559}
4560
Alexey Bataev10e775f2015-07-30 11:36:16 +00004561static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004562 auto CollapseClauses =
4563 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4564 if (CollapseClauses.begin() != CollapseClauses.end())
4565 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004566 return nullptr;
4567}
4568
Alexey Bataev10e775f2015-07-30 11:36:16 +00004569static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004570 auto OrderedClauses =
4571 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4572 if (OrderedClauses.begin() != OrderedClauses.end())
4573 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004574 return nullptr;
4575}
4576
Kelvin Lic5609492016-07-15 04:39:07 +00004577static bool checkSimdlenSafelenSpecified(Sema &S,
4578 const ArrayRef<OMPClause *> Clauses) {
4579 OMPSafelenClause *Safelen = nullptr;
4580 OMPSimdlenClause *Simdlen = nullptr;
4581
4582 for (auto *Clause : Clauses) {
4583 if (Clause->getClauseKind() == OMPC_safelen)
4584 Safelen = cast<OMPSafelenClause>(Clause);
4585 else if (Clause->getClauseKind() == OMPC_simdlen)
4586 Simdlen = cast<OMPSimdlenClause>(Clause);
4587 if (Safelen && Simdlen)
4588 break;
4589 }
4590
4591 if (Simdlen && Safelen) {
4592 llvm::APSInt SimdlenRes, SafelenRes;
4593 auto SimdlenLength = Simdlen->getSimdlen();
4594 auto SafelenLength = Safelen->getSafelen();
4595 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4596 SimdlenLength->isInstantiationDependent() ||
4597 SimdlenLength->containsUnexpandedParameterPack())
4598 return false;
4599 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4600 SafelenLength->isInstantiationDependent() ||
4601 SafelenLength->containsUnexpandedParameterPack())
4602 return false;
4603 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4604 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4605 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4606 // If both simdlen and safelen clauses are specified, the value of the
4607 // simdlen parameter must be less than or equal to the value of the safelen
4608 // parameter.
4609 if (SimdlenRes > SafelenRes) {
4610 S.Diag(SimdlenLength->getExprLoc(),
4611 diag::err_omp_wrong_simdlen_safelen_values)
4612 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4613 return true;
4614 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004615 }
4616 return false;
4617}
4618
Alexey Bataev4acb8592014-07-07 13:01:15 +00004619StmtResult Sema::ActOnOpenMPSimdDirective(
4620 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4621 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004622 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004623 if (!AStmt)
4624 return StmtError();
4625
4626 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004627 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004628 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4629 // define the nested loops number.
4630 unsigned NestedLoopCount = CheckOpenMPLoop(
4631 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4632 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004633 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004634 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004635
Alexander Musmana5f070a2014-10-01 06:03:56 +00004636 assert((CurContext->isDependentContext() || B.builtAll()) &&
4637 "omp simd loop exprs were not built");
4638
Alexander Musman3276a272015-03-21 10:12:56 +00004639 if (!CurContext->isDependentContext()) {
4640 // Finalize the clauses that need pre-built expressions for CodeGen.
4641 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004642 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004643 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004644 B.NumIterations, *this, CurScope,
4645 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004646 return StmtError();
4647 }
4648 }
4649
Kelvin Lic5609492016-07-15 04:39:07 +00004650 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004651 return StmtError();
4652
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004653 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004654 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4655 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004656}
4657
Alexey Bataev4acb8592014-07-07 13:01:15 +00004658StmtResult Sema::ActOnOpenMPForDirective(
4659 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4660 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004661 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004662 if (!AStmt)
4663 return StmtError();
4664
4665 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004666 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004667 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4668 // define the nested loops number.
4669 unsigned NestedLoopCount = CheckOpenMPLoop(
4670 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4671 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004672 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004673 return StmtError();
4674
Alexander Musmana5f070a2014-10-01 06:03:56 +00004675 assert((CurContext->isDependentContext() || B.builtAll()) &&
4676 "omp for loop exprs were not built");
4677
Alexey Bataev54acd402015-08-04 11:18:19 +00004678 if (!CurContext->isDependentContext()) {
4679 // Finalize the clauses that need pre-built expressions for CodeGen.
4680 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004681 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004682 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004683 B.NumIterations, *this, CurScope,
4684 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004685 return StmtError();
4686 }
4687 }
4688
Alexey Bataevf29276e2014-06-18 04:14:57 +00004689 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004690 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004691 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004692}
4693
Alexander Musmanf82886e2014-09-18 05:12:34 +00004694StmtResult Sema::ActOnOpenMPForSimdDirective(
4695 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4696 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004697 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004698 if (!AStmt)
4699 return StmtError();
4700
4701 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004702 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004703 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4704 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004705 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004706 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4707 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4708 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004709 if (NestedLoopCount == 0)
4710 return StmtError();
4711
Alexander Musmanc6388682014-12-15 07:07:06 +00004712 assert((CurContext->isDependentContext() || B.builtAll()) &&
4713 "omp for simd loop exprs were not built");
4714
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004715 if (!CurContext->isDependentContext()) {
4716 // Finalize the clauses that need pre-built expressions for CodeGen.
4717 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004718 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004719 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004720 B.NumIterations, *this, CurScope,
4721 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004722 return StmtError();
4723 }
4724 }
4725
Kelvin Lic5609492016-07-15 04:39:07 +00004726 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004727 return StmtError();
4728
Alexander Musmanf82886e2014-09-18 05:12:34 +00004729 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004730 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4731 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004732}
4733
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004734StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4735 Stmt *AStmt,
4736 SourceLocation StartLoc,
4737 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004738 if (!AStmt)
4739 return StmtError();
4740
4741 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004742 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004743 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004744 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004745 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004746 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004747 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004748 return StmtError();
4749 // All associated statements must be '#pragma omp section' except for
4750 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004751 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004752 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4753 if (SectionStmt)
4754 Diag(SectionStmt->getLocStart(),
4755 diag::err_omp_sections_substmt_not_section);
4756 return StmtError();
4757 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004758 cast<OMPSectionDirective>(SectionStmt)
4759 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004760 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004761 } else {
4762 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4763 return StmtError();
4764 }
4765
4766 getCurFunction()->setHasBranchProtectedScope();
4767
Alexey Bataev25e5b442015-09-15 12:52:43 +00004768 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4769 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004770}
4771
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004772StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4773 SourceLocation StartLoc,
4774 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004775 if (!AStmt)
4776 return StmtError();
4777
4778 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004779
4780 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004781 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004782
Alexey Bataev25e5b442015-09-15 12:52:43 +00004783 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4784 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004785}
4786
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004787StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4788 Stmt *AStmt,
4789 SourceLocation StartLoc,
4790 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004791 if (!AStmt)
4792 return StmtError();
4793
4794 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004795
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004796 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004797
Alexey Bataev3255bf32015-01-19 05:20:46 +00004798 // OpenMP [2.7.3, single Construct, Restrictions]
4799 // The copyprivate clause must not be used with the nowait clause.
4800 OMPClause *Nowait = nullptr;
4801 OMPClause *Copyprivate = nullptr;
4802 for (auto *Clause : Clauses) {
4803 if (Clause->getClauseKind() == OMPC_nowait)
4804 Nowait = Clause;
4805 else if (Clause->getClauseKind() == OMPC_copyprivate)
4806 Copyprivate = Clause;
4807 if (Copyprivate && Nowait) {
4808 Diag(Copyprivate->getLocStart(),
4809 diag::err_omp_single_copyprivate_with_nowait);
4810 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4811 return StmtError();
4812 }
4813 }
4814
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004815 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4816}
4817
Alexander Musman80c22892014-07-17 08:54:58 +00004818StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4819 SourceLocation StartLoc,
4820 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004821 if (!AStmt)
4822 return StmtError();
4823
4824 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004825
4826 getCurFunction()->setHasBranchProtectedScope();
4827
4828 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4829}
4830
Alexey Bataev28c75412015-12-15 08:19:24 +00004831StmtResult Sema::ActOnOpenMPCriticalDirective(
4832 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4833 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004834 if (!AStmt)
4835 return StmtError();
4836
4837 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004838
Alexey Bataev28c75412015-12-15 08:19:24 +00004839 bool ErrorFound = false;
4840 llvm::APSInt Hint;
4841 SourceLocation HintLoc;
4842 bool DependentHint = false;
4843 for (auto *C : Clauses) {
4844 if (C->getClauseKind() == OMPC_hint) {
4845 if (!DirName.getName()) {
4846 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4847 ErrorFound = true;
4848 }
4849 Expr *E = cast<OMPHintClause>(C)->getHint();
4850 if (E->isTypeDependent() || E->isValueDependent() ||
4851 E->isInstantiationDependent())
4852 DependentHint = true;
4853 else {
4854 Hint = E->EvaluateKnownConstInt(Context);
4855 HintLoc = C->getLocStart();
4856 }
4857 }
4858 }
4859 if (ErrorFound)
4860 return StmtError();
4861 auto Pair = DSAStack->getCriticalWithHint(DirName);
4862 if (Pair.first && DirName.getName() && !DependentHint) {
4863 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4864 Diag(StartLoc, diag::err_omp_critical_with_hint);
4865 if (HintLoc.isValid()) {
4866 Diag(HintLoc, diag::note_omp_critical_hint_here)
4867 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4868 } else
4869 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4870 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4871 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4872 << 1
4873 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4874 /*Radix=*/10, /*Signed=*/false);
4875 } else
4876 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4877 }
4878 }
4879
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004880 getCurFunction()->setHasBranchProtectedScope();
4881
Alexey Bataev28c75412015-12-15 08:19:24 +00004882 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4883 Clauses, AStmt);
4884 if (!Pair.first && DirName.getName() && !DependentHint)
4885 DSAStack->addCriticalWithHint(Dir, Hint);
4886 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004887}
4888
Alexey Bataev4acb8592014-07-07 13:01:15 +00004889StmtResult Sema::ActOnOpenMPParallelForDirective(
4890 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4891 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004892 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004893 if (!AStmt)
4894 return StmtError();
4895
Alexey Bataev4acb8592014-07-07 13:01:15 +00004896 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4897 // 1.2.2 OpenMP Language Terminology
4898 // Structured block - An executable statement with a single entry at the
4899 // top and a single exit at the bottom.
4900 // The point of exit cannot be a branch out of the structured block.
4901 // longjmp() and throw() must not violate the entry/exit criteria.
4902 CS->getCapturedDecl()->setNothrow();
4903
Alexander Musmanc6388682014-12-15 07:07:06 +00004904 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004905 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4906 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004907 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004908 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4909 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4910 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004911 if (NestedLoopCount == 0)
4912 return StmtError();
4913
Alexander Musmana5f070a2014-10-01 06:03:56 +00004914 assert((CurContext->isDependentContext() || B.builtAll()) &&
4915 "omp parallel for loop exprs were not built");
4916
Alexey Bataev54acd402015-08-04 11:18:19 +00004917 if (!CurContext->isDependentContext()) {
4918 // Finalize the clauses that need pre-built expressions for CodeGen.
4919 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004920 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004921 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004922 B.NumIterations, *this, CurScope,
4923 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004924 return StmtError();
4925 }
4926 }
4927
Alexey Bataev4acb8592014-07-07 13:01:15 +00004928 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004929 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004930 NestedLoopCount, Clauses, AStmt, B,
4931 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004932}
4933
Alexander Musmane4e893b2014-09-23 09:33:00 +00004934StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4935 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4936 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004937 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004938 if (!AStmt)
4939 return StmtError();
4940
Alexander Musmane4e893b2014-09-23 09:33:00 +00004941 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4942 // 1.2.2 OpenMP Language Terminology
4943 // Structured block - An executable statement with a single entry at the
4944 // top and a single exit at the bottom.
4945 // The point of exit cannot be a branch out of the structured block.
4946 // longjmp() and throw() must not violate the entry/exit criteria.
4947 CS->getCapturedDecl()->setNothrow();
4948
Alexander Musmanc6388682014-12-15 07:07:06 +00004949 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004950 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4951 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004952 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004953 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4954 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4955 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004956 if (NestedLoopCount == 0)
4957 return StmtError();
4958
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004959 if (!CurContext->isDependentContext()) {
4960 // Finalize the clauses that need pre-built expressions for CodeGen.
4961 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004962 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004963 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004964 B.NumIterations, *this, CurScope,
4965 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004966 return StmtError();
4967 }
4968 }
4969
Kelvin Lic5609492016-07-15 04:39:07 +00004970 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004971 return StmtError();
4972
Alexander Musmane4e893b2014-09-23 09:33:00 +00004973 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004974 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004975 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004976}
4977
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004978StmtResult
4979Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4980 Stmt *AStmt, SourceLocation StartLoc,
4981 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004982 if (!AStmt)
4983 return StmtError();
4984
4985 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004986 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004987 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004988 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004989 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004990 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004991 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004992 return StmtError();
4993 // All associated statements must be '#pragma omp section' except for
4994 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004995 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004996 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4997 if (SectionStmt)
4998 Diag(SectionStmt->getLocStart(),
4999 diag::err_omp_parallel_sections_substmt_not_section);
5000 return StmtError();
5001 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005002 cast<OMPSectionDirective>(SectionStmt)
5003 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005004 }
5005 } else {
5006 Diag(AStmt->getLocStart(),
5007 diag::err_omp_parallel_sections_not_compound_stmt);
5008 return StmtError();
5009 }
5010
5011 getCurFunction()->setHasBranchProtectedScope();
5012
Alexey Bataev25e5b442015-09-15 12:52:43 +00005013 return OMPParallelSectionsDirective::Create(
5014 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005015}
5016
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005017StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5018 Stmt *AStmt, SourceLocation StartLoc,
5019 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005020 if (!AStmt)
5021 return StmtError();
5022
David Majnemer9d168222016-08-05 17:44:54 +00005023 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005024 // 1.2.2 OpenMP Language Terminology
5025 // Structured block - An executable statement with a single entry at the
5026 // top and a single exit at the bottom.
5027 // The point of exit cannot be a branch out of the structured block.
5028 // longjmp() and throw() must not violate the entry/exit criteria.
5029 CS->getCapturedDecl()->setNothrow();
5030
5031 getCurFunction()->setHasBranchProtectedScope();
5032
Alexey Bataev25e5b442015-09-15 12:52:43 +00005033 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5034 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005035}
5036
Alexey Bataev68446b72014-07-18 07:47:19 +00005037StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5038 SourceLocation EndLoc) {
5039 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5040}
5041
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005042StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5043 SourceLocation EndLoc) {
5044 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5045}
5046
Alexey Bataev2df347a2014-07-18 10:17:07 +00005047StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5048 SourceLocation EndLoc) {
5049 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5050}
5051
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005052StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5053 SourceLocation StartLoc,
5054 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005055 if (!AStmt)
5056 return StmtError();
5057
5058 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005059
5060 getCurFunction()->setHasBranchProtectedScope();
5061
5062 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5063}
5064
Alexey Bataev6125da92014-07-21 11:26:11 +00005065StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5066 SourceLocation StartLoc,
5067 SourceLocation EndLoc) {
5068 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5069 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5070}
5071
Alexey Bataev346265e2015-09-25 10:37:12 +00005072StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5073 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005074 SourceLocation StartLoc,
5075 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005076 OMPClause *DependFound = nullptr;
5077 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005078 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005079 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005080 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005081 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005082 for (auto *C : Clauses) {
5083 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5084 DependFound = C;
5085 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5086 if (DependSourceClause) {
5087 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5088 << getOpenMPDirectiveName(OMPD_ordered)
5089 << getOpenMPClauseName(OMPC_depend) << 2;
5090 ErrorFound = true;
5091 } else
5092 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005093 if (DependSinkClause) {
5094 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5095 << 0;
5096 ErrorFound = true;
5097 }
5098 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5099 if (DependSourceClause) {
5100 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5101 << 1;
5102 ErrorFound = true;
5103 }
5104 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005105 }
5106 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005107 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005108 else if (C->getClauseKind() == OMPC_simd)
5109 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005110 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005111 if (!ErrorFound && !SC &&
5112 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005113 // OpenMP [2.8.1,simd Construct, Restrictions]
5114 // An ordered construct with the simd clause is the only OpenMP construct
5115 // that can appear in the simd region.
5116 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005117 ErrorFound = true;
5118 } else if (DependFound && (TC || SC)) {
5119 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5120 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5121 ErrorFound = true;
5122 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5123 Diag(DependFound->getLocStart(),
5124 diag::err_omp_ordered_directive_without_param);
5125 ErrorFound = true;
5126 } else if (TC || Clauses.empty()) {
5127 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5128 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5129 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5130 << (TC != nullptr);
5131 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5132 ErrorFound = true;
5133 }
5134 }
5135 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005136 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005137
5138 if (AStmt) {
5139 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5140
5141 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005142 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005143
5144 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005145}
5146
Alexey Bataev1d160b12015-03-13 12:27:31 +00005147namespace {
5148/// \brief Helper class for checking expression in 'omp atomic [update]'
5149/// construct.
5150class OpenMPAtomicUpdateChecker {
5151 /// \brief Error results for atomic update expressions.
5152 enum ExprAnalysisErrorCode {
5153 /// \brief A statement is not an expression statement.
5154 NotAnExpression,
5155 /// \brief Expression is not builtin binary or unary operation.
5156 NotABinaryOrUnaryExpression,
5157 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5158 NotAnUnaryIncDecExpression,
5159 /// \brief An expression is not of scalar type.
5160 NotAScalarType,
5161 /// \brief A binary operation is not an assignment operation.
5162 NotAnAssignmentOp,
5163 /// \brief RHS part of the binary operation is not a binary expression.
5164 NotABinaryExpression,
5165 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5166 /// expression.
5167 NotABinaryOperator,
5168 /// \brief RHS binary operation does not have reference to the updated LHS
5169 /// part.
5170 NotAnUpdateExpression,
5171 /// \brief No errors is found.
5172 NoError
5173 };
5174 /// \brief Reference to Sema.
5175 Sema &SemaRef;
5176 /// \brief A location for note diagnostics (when error is found).
5177 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005178 /// \brief 'x' lvalue part of the source atomic expression.
5179 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005180 /// \brief 'expr' rvalue part of the source atomic expression.
5181 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005182 /// \brief Helper expression of the form
5183 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5184 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5185 Expr *UpdateExpr;
5186 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5187 /// important for non-associative operations.
5188 bool IsXLHSInRHSPart;
5189 BinaryOperatorKind Op;
5190 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005191 /// \brief true if the source expression is a postfix unary operation, false
5192 /// if it is a prefix unary operation.
5193 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005194
5195public:
5196 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005197 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005198 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005199 /// \brief Check specified statement that it is suitable for 'atomic update'
5200 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005201 /// expression. If DiagId and NoteId == 0, then only check is performed
5202 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005203 /// \param DiagId Diagnostic which should be emitted if error is found.
5204 /// \param NoteId Diagnostic note for the main error message.
5205 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005206 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005207 /// \brief Return the 'x' lvalue part of the source atomic expression.
5208 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005209 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5210 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005211 /// \brief Return the update expression used in calculation of the updated
5212 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5213 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5214 Expr *getUpdateExpr() const { return UpdateExpr; }
5215 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5216 /// false otherwise.
5217 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5218
Alexey Bataevb78ca832015-04-01 03:33:17 +00005219 /// \brief true if the source expression is a postfix unary operation, false
5220 /// if it is a prefix unary operation.
5221 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5222
Alexey Bataev1d160b12015-03-13 12:27:31 +00005223private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005224 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5225 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005226};
5227} // namespace
5228
5229bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5230 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5231 ExprAnalysisErrorCode ErrorFound = NoError;
5232 SourceLocation ErrorLoc, NoteLoc;
5233 SourceRange ErrorRange, NoteRange;
5234 // Allowed constructs are:
5235 // x = x binop expr;
5236 // x = expr binop x;
5237 if (AtomicBinOp->getOpcode() == BO_Assign) {
5238 X = AtomicBinOp->getLHS();
5239 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5240 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5241 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5242 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5243 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005244 Op = AtomicInnerBinOp->getOpcode();
5245 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005246 auto *LHS = AtomicInnerBinOp->getLHS();
5247 auto *RHS = AtomicInnerBinOp->getRHS();
5248 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5249 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5250 /*Canonical=*/true);
5251 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5252 /*Canonical=*/true);
5253 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5254 /*Canonical=*/true);
5255 if (XId == LHSId) {
5256 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005257 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005258 } else if (XId == RHSId) {
5259 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005260 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005261 } else {
5262 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5263 ErrorRange = AtomicInnerBinOp->getSourceRange();
5264 NoteLoc = X->getExprLoc();
5265 NoteRange = X->getSourceRange();
5266 ErrorFound = NotAnUpdateExpression;
5267 }
5268 } else {
5269 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5270 ErrorRange = AtomicInnerBinOp->getSourceRange();
5271 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5272 NoteRange = SourceRange(NoteLoc, NoteLoc);
5273 ErrorFound = NotABinaryOperator;
5274 }
5275 } else {
5276 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5277 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5278 ErrorFound = NotABinaryExpression;
5279 }
5280 } else {
5281 ErrorLoc = AtomicBinOp->getExprLoc();
5282 ErrorRange = AtomicBinOp->getSourceRange();
5283 NoteLoc = AtomicBinOp->getOperatorLoc();
5284 NoteRange = SourceRange(NoteLoc, NoteLoc);
5285 ErrorFound = NotAnAssignmentOp;
5286 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005287 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005288 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5289 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5290 return true;
5291 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005292 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005293 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005294}
5295
5296bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5297 unsigned NoteId) {
5298 ExprAnalysisErrorCode ErrorFound = NoError;
5299 SourceLocation ErrorLoc, NoteLoc;
5300 SourceRange ErrorRange, NoteRange;
5301 // Allowed constructs are:
5302 // x++;
5303 // x--;
5304 // ++x;
5305 // --x;
5306 // x binop= expr;
5307 // x = x binop expr;
5308 // x = expr binop x;
5309 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5310 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5311 if (AtomicBody->getType()->isScalarType() ||
5312 AtomicBody->isInstantiationDependent()) {
5313 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5314 AtomicBody->IgnoreParenImpCasts())) {
5315 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005316 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005317 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005318 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005319 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005320 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005321 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005322 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5323 AtomicBody->IgnoreParenImpCasts())) {
5324 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005325 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005326 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005327 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5328 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005329 // Check for Unary Operation
5330 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005331 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005332 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5333 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005334 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005335 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5336 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005337 } else {
5338 ErrorFound = NotAnUnaryIncDecExpression;
5339 ErrorLoc = AtomicUnaryOp->getExprLoc();
5340 ErrorRange = AtomicUnaryOp->getSourceRange();
5341 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5342 NoteRange = SourceRange(NoteLoc, NoteLoc);
5343 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005344 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005345 ErrorFound = NotABinaryOrUnaryExpression;
5346 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5347 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5348 }
5349 } else {
5350 ErrorFound = NotAScalarType;
5351 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5352 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5353 }
5354 } else {
5355 ErrorFound = NotAnExpression;
5356 NoteLoc = ErrorLoc = S->getLocStart();
5357 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5358 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005359 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005360 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5361 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5362 return true;
5363 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005364 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005365 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005366 // Build an update expression of form 'OpaqueValueExpr(x) binop
5367 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5368 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5369 auto *OVEX = new (SemaRef.getASTContext())
5370 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5371 auto *OVEExpr = new (SemaRef.getASTContext())
5372 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5373 auto Update =
5374 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5375 IsXLHSInRHSPart ? OVEExpr : OVEX);
5376 if (Update.isInvalid())
5377 return true;
5378 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5379 Sema::AA_Casting);
5380 if (Update.isInvalid())
5381 return true;
5382 UpdateExpr = Update.get();
5383 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005384 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005385}
5386
Alexey Bataev0162e452014-07-22 10:10:35 +00005387StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5388 Stmt *AStmt,
5389 SourceLocation StartLoc,
5390 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005391 if (!AStmt)
5392 return StmtError();
5393
David Majnemer9d168222016-08-05 17:44:54 +00005394 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005395 // 1.2.2 OpenMP Language Terminology
5396 // Structured block - An executable statement with a single entry at the
5397 // top and a single exit at the bottom.
5398 // The point of exit cannot be a branch out of the structured block.
5399 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005400 OpenMPClauseKind AtomicKind = OMPC_unknown;
5401 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005402 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005403 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005404 C->getClauseKind() == OMPC_update ||
5405 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005406 if (AtomicKind != OMPC_unknown) {
5407 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5408 << SourceRange(C->getLocStart(), C->getLocEnd());
5409 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5410 << getOpenMPClauseName(AtomicKind);
5411 } else {
5412 AtomicKind = C->getClauseKind();
5413 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005414 }
5415 }
5416 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005417
Alexey Bataev459dec02014-07-24 06:46:57 +00005418 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005419 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5420 Body = EWC->getSubExpr();
5421
Alexey Bataev62cec442014-11-18 10:14:22 +00005422 Expr *X = nullptr;
5423 Expr *V = nullptr;
5424 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005425 Expr *UE = nullptr;
5426 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005427 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005428 // OpenMP [2.12.6, atomic Construct]
5429 // In the next expressions:
5430 // * x and v (as applicable) are both l-value expressions with scalar type.
5431 // * During the execution of an atomic region, multiple syntactic
5432 // occurrences of x must designate the same storage location.
5433 // * Neither of v and expr (as applicable) may access the storage location
5434 // designated by x.
5435 // * Neither of x and expr (as applicable) may access the storage location
5436 // designated by v.
5437 // * expr is an expression with scalar type.
5438 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5439 // * binop, binop=, ++, and -- are not overloaded operators.
5440 // * The expression x binop expr must be numerically equivalent to x binop
5441 // (expr). This requirement is satisfied if the operators in expr have
5442 // precedence greater than binop, or by using parentheses around expr or
5443 // subexpressions of expr.
5444 // * The expression expr binop x must be numerically equivalent to (expr)
5445 // binop x. This requirement is satisfied if the operators in expr have
5446 // precedence equal to or greater than binop, or by using parentheses around
5447 // expr or subexpressions of expr.
5448 // * For forms that allow multiple occurrences of x, the number of times
5449 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005450 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005451 enum {
5452 NotAnExpression,
5453 NotAnAssignmentOp,
5454 NotAScalarType,
5455 NotAnLValue,
5456 NoError
5457 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005458 SourceLocation ErrorLoc, NoteLoc;
5459 SourceRange ErrorRange, NoteRange;
5460 // If clause is read:
5461 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005462 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5463 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005464 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5465 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5466 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5467 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5468 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5469 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5470 if (!X->isLValue() || !V->isLValue()) {
5471 auto NotLValueExpr = X->isLValue() ? V : X;
5472 ErrorFound = NotAnLValue;
5473 ErrorLoc = AtomicBinOp->getExprLoc();
5474 ErrorRange = AtomicBinOp->getSourceRange();
5475 NoteLoc = NotLValueExpr->getExprLoc();
5476 NoteRange = NotLValueExpr->getSourceRange();
5477 }
5478 } else if (!X->isInstantiationDependent() ||
5479 !V->isInstantiationDependent()) {
5480 auto NotScalarExpr =
5481 (X->isInstantiationDependent() || X->getType()->isScalarType())
5482 ? V
5483 : X;
5484 ErrorFound = NotAScalarType;
5485 ErrorLoc = AtomicBinOp->getExprLoc();
5486 ErrorRange = AtomicBinOp->getSourceRange();
5487 NoteLoc = NotScalarExpr->getExprLoc();
5488 NoteRange = NotScalarExpr->getSourceRange();
5489 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005490 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005491 ErrorFound = NotAnAssignmentOp;
5492 ErrorLoc = AtomicBody->getExprLoc();
5493 ErrorRange = AtomicBody->getSourceRange();
5494 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5495 : AtomicBody->getExprLoc();
5496 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5497 : AtomicBody->getSourceRange();
5498 }
5499 } else {
5500 ErrorFound = NotAnExpression;
5501 NoteLoc = ErrorLoc = Body->getLocStart();
5502 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005503 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005504 if (ErrorFound != NoError) {
5505 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5506 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005507 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5508 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005509 return StmtError();
5510 } else if (CurContext->isDependentContext())
5511 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005512 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005513 enum {
5514 NotAnExpression,
5515 NotAnAssignmentOp,
5516 NotAScalarType,
5517 NotAnLValue,
5518 NoError
5519 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005520 SourceLocation ErrorLoc, NoteLoc;
5521 SourceRange ErrorRange, NoteRange;
5522 // If clause is write:
5523 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005524 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5525 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005526 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5527 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005528 X = AtomicBinOp->getLHS();
5529 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005530 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5531 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5532 if (!X->isLValue()) {
5533 ErrorFound = NotAnLValue;
5534 ErrorLoc = AtomicBinOp->getExprLoc();
5535 ErrorRange = AtomicBinOp->getSourceRange();
5536 NoteLoc = X->getExprLoc();
5537 NoteRange = X->getSourceRange();
5538 }
5539 } else if (!X->isInstantiationDependent() ||
5540 !E->isInstantiationDependent()) {
5541 auto NotScalarExpr =
5542 (X->isInstantiationDependent() || X->getType()->isScalarType())
5543 ? E
5544 : X;
5545 ErrorFound = NotAScalarType;
5546 ErrorLoc = AtomicBinOp->getExprLoc();
5547 ErrorRange = AtomicBinOp->getSourceRange();
5548 NoteLoc = NotScalarExpr->getExprLoc();
5549 NoteRange = NotScalarExpr->getSourceRange();
5550 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005551 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005552 ErrorFound = NotAnAssignmentOp;
5553 ErrorLoc = AtomicBody->getExprLoc();
5554 ErrorRange = AtomicBody->getSourceRange();
5555 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5556 : AtomicBody->getExprLoc();
5557 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5558 : AtomicBody->getSourceRange();
5559 }
5560 } else {
5561 ErrorFound = NotAnExpression;
5562 NoteLoc = ErrorLoc = Body->getLocStart();
5563 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005564 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005565 if (ErrorFound != NoError) {
5566 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5567 << ErrorRange;
5568 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5569 << NoteRange;
5570 return StmtError();
5571 } else if (CurContext->isDependentContext())
5572 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005573 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005574 // If clause is update:
5575 // x++;
5576 // x--;
5577 // ++x;
5578 // --x;
5579 // x binop= expr;
5580 // x = x binop expr;
5581 // x = expr binop x;
5582 OpenMPAtomicUpdateChecker Checker(*this);
5583 if (Checker.checkStatement(
5584 Body, (AtomicKind == OMPC_update)
5585 ? diag::err_omp_atomic_update_not_expression_statement
5586 : diag::err_omp_atomic_not_expression_statement,
5587 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005588 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005589 if (!CurContext->isDependentContext()) {
5590 E = Checker.getExpr();
5591 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005592 UE = Checker.getUpdateExpr();
5593 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005594 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005595 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005596 enum {
5597 NotAnAssignmentOp,
5598 NotACompoundStatement,
5599 NotTwoSubstatements,
5600 NotASpecificExpression,
5601 NoError
5602 } ErrorFound = NoError;
5603 SourceLocation ErrorLoc, NoteLoc;
5604 SourceRange ErrorRange, NoteRange;
5605 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5606 // If clause is a capture:
5607 // v = x++;
5608 // v = x--;
5609 // v = ++x;
5610 // v = --x;
5611 // v = x binop= expr;
5612 // v = x = x binop expr;
5613 // v = x = expr binop x;
5614 auto *AtomicBinOp =
5615 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5616 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5617 V = AtomicBinOp->getLHS();
5618 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5619 OpenMPAtomicUpdateChecker Checker(*this);
5620 if (Checker.checkStatement(
5621 Body, diag::err_omp_atomic_capture_not_expression_statement,
5622 diag::note_omp_atomic_update))
5623 return StmtError();
5624 E = Checker.getExpr();
5625 X = Checker.getX();
5626 UE = Checker.getUpdateExpr();
5627 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5628 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005629 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005630 ErrorLoc = AtomicBody->getExprLoc();
5631 ErrorRange = AtomicBody->getSourceRange();
5632 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5633 : AtomicBody->getExprLoc();
5634 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5635 : AtomicBody->getSourceRange();
5636 ErrorFound = NotAnAssignmentOp;
5637 }
5638 if (ErrorFound != NoError) {
5639 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5640 << ErrorRange;
5641 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5642 return StmtError();
5643 } else if (CurContext->isDependentContext()) {
5644 UE = V = E = X = nullptr;
5645 }
5646 } else {
5647 // If clause is a capture:
5648 // { v = x; x = expr; }
5649 // { v = x; x++; }
5650 // { v = x; x--; }
5651 // { v = x; ++x; }
5652 // { v = x; --x; }
5653 // { v = x; x binop= expr; }
5654 // { v = x; x = x binop expr; }
5655 // { v = x; x = expr binop x; }
5656 // { x++; v = x; }
5657 // { x--; v = x; }
5658 // { ++x; v = x; }
5659 // { --x; v = x; }
5660 // { x binop= expr; v = x; }
5661 // { x = x binop expr; v = x; }
5662 // { x = expr binop x; v = x; }
5663 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5664 // Check that this is { expr1; expr2; }
5665 if (CS->size() == 2) {
5666 auto *First = CS->body_front();
5667 auto *Second = CS->body_back();
5668 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5669 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5670 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5671 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5672 // Need to find what subexpression is 'v' and what is 'x'.
5673 OpenMPAtomicUpdateChecker Checker(*this);
5674 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5675 BinaryOperator *BinOp = nullptr;
5676 if (IsUpdateExprFound) {
5677 BinOp = dyn_cast<BinaryOperator>(First);
5678 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5679 }
5680 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5681 // { v = x; x++; }
5682 // { v = x; x--; }
5683 // { v = x; ++x; }
5684 // { v = x; --x; }
5685 // { v = x; x binop= expr; }
5686 // { v = x; x = x binop expr; }
5687 // { v = x; x = expr binop x; }
5688 // Check that the first expression has form v = x.
5689 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5690 llvm::FoldingSetNodeID XId, PossibleXId;
5691 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5692 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5693 IsUpdateExprFound = XId == PossibleXId;
5694 if (IsUpdateExprFound) {
5695 V = BinOp->getLHS();
5696 X = Checker.getX();
5697 E = Checker.getExpr();
5698 UE = Checker.getUpdateExpr();
5699 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005700 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005701 }
5702 }
5703 if (!IsUpdateExprFound) {
5704 IsUpdateExprFound = !Checker.checkStatement(First);
5705 BinOp = nullptr;
5706 if (IsUpdateExprFound) {
5707 BinOp = dyn_cast<BinaryOperator>(Second);
5708 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5709 }
5710 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5711 // { x++; v = x; }
5712 // { x--; v = x; }
5713 // { ++x; v = x; }
5714 // { --x; v = x; }
5715 // { x binop= expr; v = x; }
5716 // { x = x binop expr; v = x; }
5717 // { x = expr binop x; v = x; }
5718 // Check that the second expression has form v = x.
5719 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5720 llvm::FoldingSetNodeID XId, PossibleXId;
5721 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5722 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5723 IsUpdateExprFound = XId == PossibleXId;
5724 if (IsUpdateExprFound) {
5725 V = BinOp->getLHS();
5726 X = Checker.getX();
5727 E = Checker.getExpr();
5728 UE = Checker.getUpdateExpr();
5729 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005730 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005731 }
5732 }
5733 }
5734 if (!IsUpdateExprFound) {
5735 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005736 auto *FirstExpr = dyn_cast<Expr>(First);
5737 auto *SecondExpr = dyn_cast<Expr>(Second);
5738 if (!FirstExpr || !SecondExpr ||
5739 !(FirstExpr->isInstantiationDependent() ||
5740 SecondExpr->isInstantiationDependent())) {
5741 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5742 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005743 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005744 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5745 : First->getLocStart();
5746 NoteRange = ErrorRange = FirstBinOp
5747 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005748 : SourceRange(ErrorLoc, ErrorLoc);
5749 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005750 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5751 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5752 ErrorFound = NotAnAssignmentOp;
5753 NoteLoc = ErrorLoc = SecondBinOp
5754 ? SecondBinOp->getOperatorLoc()
5755 : Second->getLocStart();
5756 NoteRange = ErrorRange =
5757 SecondBinOp ? SecondBinOp->getSourceRange()
5758 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005759 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005760 auto *PossibleXRHSInFirst =
5761 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5762 auto *PossibleXLHSInSecond =
5763 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5764 llvm::FoldingSetNodeID X1Id, X2Id;
5765 PossibleXRHSInFirst->Profile(X1Id, Context,
5766 /*Canonical=*/true);
5767 PossibleXLHSInSecond->Profile(X2Id, Context,
5768 /*Canonical=*/true);
5769 IsUpdateExprFound = X1Id == X2Id;
5770 if (IsUpdateExprFound) {
5771 V = FirstBinOp->getLHS();
5772 X = SecondBinOp->getLHS();
5773 E = SecondBinOp->getRHS();
5774 UE = nullptr;
5775 IsXLHSInRHSPart = false;
5776 IsPostfixUpdate = true;
5777 } else {
5778 ErrorFound = NotASpecificExpression;
5779 ErrorLoc = FirstBinOp->getExprLoc();
5780 ErrorRange = FirstBinOp->getSourceRange();
5781 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5782 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5783 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005784 }
5785 }
5786 }
5787 }
5788 } else {
5789 NoteLoc = ErrorLoc = Body->getLocStart();
5790 NoteRange = ErrorRange =
5791 SourceRange(Body->getLocStart(), Body->getLocStart());
5792 ErrorFound = NotTwoSubstatements;
5793 }
5794 } else {
5795 NoteLoc = ErrorLoc = Body->getLocStart();
5796 NoteRange = ErrorRange =
5797 SourceRange(Body->getLocStart(), Body->getLocStart());
5798 ErrorFound = NotACompoundStatement;
5799 }
5800 if (ErrorFound != NoError) {
5801 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5802 << ErrorRange;
5803 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5804 return StmtError();
5805 } else if (CurContext->isDependentContext()) {
5806 UE = V = E = X = nullptr;
5807 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005808 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005809 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005810
5811 getCurFunction()->setHasBranchProtectedScope();
5812
Alexey Bataev62cec442014-11-18 10:14:22 +00005813 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005814 X, V, E, UE, IsXLHSInRHSPart,
5815 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005816}
5817
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005818StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5819 Stmt *AStmt,
5820 SourceLocation StartLoc,
5821 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005822 if (!AStmt)
5823 return StmtError();
5824
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005825 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5826 // 1.2.2 OpenMP Language Terminology
5827 // Structured block - An executable statement with a single entry at the
5828 // top and a single exit at the bottom.
5829 // The point of exit cannot be a branch out of the structured block.
5830 // longjmp() and throw() must not violate the entry/exit criteria.
5831 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005832
Alexey Bataev13314bf2014-10-09 04:18:56 +00005833 // OpenMP [2.16, Nesting of Regions]
5834 // If specified, a teams construct must be contained within a target
5835 // construct. That target construct must contain no statements or directives
5836 // outside of the teams construct.
5837 if (DSAStack->hasInnerTeamsRegion()) {
5838 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5839 bool OMPTeamsFound = true;
5840 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5841 auto I = CS->body_begin();
5842 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005843 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005844 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5845 OMPTeamsFound = false;
5846 break;
5847 }
5848 ++I;
5849 }
5850 assert(I != CS->body_end() && "Not found statement");
5851 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005852 } else {
5853 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5854 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005855 }
5856 if (!OMPTeamsFound) {
5857 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5858 Diag(DSAStack->getInnerTeamsRegionLoc(),
5859 diag::note_omp_nested_teams_construct_here);
5860 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5861 << isa<OMPExecutableDirective>(S);
5862 return StmtError();
5863 }
5864 }
5865
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005866 getCurFunction()->setHasBranchProtectedScope();
5867
5868 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5869}
5870
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005871StmtResult
5872Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5873 Stmt *AStmt, SourceLocation StartLoc,
5874 SourceLocation EndLoc) {
5875 if (!AStmt)
5876 return StmtError();
5877
5878 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5879 // 1.2.2 OpenMP Language Terminology
5880 // Structured block - An executable statement with a single entry at the
5881 // top and a single exit at the bottom.
5882 // The point of exit cannot be a branch out of the structured block.
5883 // longjmp() and throw() must not violate the entry/exit criteria.
5884 CS->getCapturedDecl()->setNothrow();
5885
5886 getCurFunction()->setHasBranchProtectedScope();
5887
5888 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5889 AStmt);
5890}
5891
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005892StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5893 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5894 SourceLocation EndLoc,
5895 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5896 if (!AStmt)
5897 return StmtError();
5898
5899 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5900 // 1.2.2 OpenMP Language Terminology
5901 // Structured block - An executable statement with a single entry at the
5902 // top and a single exit at the bottom.
5903 // The point of exit cannot be a branch out of the structured block.
5904 // longjmp() and throw() must not violate the entry/exit criteria.
5905 CS->getCapturedDecl()->setNothrow();
5906
5907 OMPLoopDirective::HelperExprs B;
5908 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5909 // define the nested loops number.
5910 unsigned NestedLoopCount =
5911 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5912 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5913 VarsWithImplicitDSA, B);
5914 if (NestedLoopCount == 0)
5915 return StmtError();
5916
5917 assert((CurContext->isDependentContext() || B.builtAll()) &&
5918 "omp target parallel for loop exprs were not built");
5919
5920 if (!CurContext->isDependentContext()) {
5921 // Finalize the clauses that need pre-built expressions for CodeGen.
5922 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005923 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005924 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005925 B.NumIterations, *this, CurScope,
5926 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005927 return StmtError();
5928 }
5929 }
5930
5931 getCurFunction()->setHasBranchProtectedScope();
5932 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5933 NestedLoopCount, Clauses, AStmt,
5934 B, DSAStack->isCancelRegion());
5935}
5936
Samuel Antaodf67fc42016-01-19 19:15:56 +00005937/// \brief Check for existence of a map clause in the list of clauses.
5938static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5939 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5940 I != E; ++I) {
5941 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5942 return true;
5943 }
5944 }
5945
5946 return false;
5947}
5948
Michael Wong65f367f2015-07-21 13:44:28 +00005949StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5950 Stmt *AStmt,
5951 SourceLocation StartLoc,
5952 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005953 if (!AStmt)
5954 return StmtError();
5955
5956 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5957
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005958 // OpenMP [2.10.1, Restrictions, p. 97]
5959 // At least one map clause must appear on the directive.
5960 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005961 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5962 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005963 return StmtError();
5964 }
5965
Michael Wong65f367f2015-07-21 13:44:28 +00005966 getCurFunction()->setHasBranchProtectedScope();
5967
5968 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5969 AStmt);
5970}
5971
Samuel Antaodf67fc42016-01-19 19:15:56 +00005972StmtResult
5973Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5974 SourceLocation StartLoc,
5975 SourceLocation EndLoc) {
5976 // OpenMP [2.10.2, Restrictions, p. 99]
5977 // At least one map clause must appear on the directive.
5978 if (!HasMapClause(Clauses)) {
5979 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5980 << getOpenMPDirectiveName(OMPD_target_enter_data);
5981 return StmtError();
5982 }
5983
5984 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5985 Clauses);
5986}
5987
Samuel Antao72590762016-01-19 20:04:50 +00005988StmtResult
5989Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5990 SourceLocation StartLoc,
5991 SourceLocation EndLoc) {
5992 // OpenMP [2.10.3, Restrictions, p. 102]
5993 // At least one map clause must appear on the directive.
5994 if (!HasMapClause(Clauses)) {
5995 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5996 << getOpenMPDirectiveName(OMPD_target_exit_data);
5997 return StmtError();
5998 }
5999
6000 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6001}
6002
Samuel Antao686c70c2016-05-26 17:30:50 +00006003StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6004 SourceLocation StartLoc,
6005 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006006 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00006007 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00006008 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00006009 seenMotionClause = true;
6010 }
Samuel Antao686c70c2016-05-26 17:30:50 +00006011 if (!seenMotionClause) {
6012 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6013 return StmtError();
6014 }
6015 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6016}
6017
Alexey Bataev13314bf2014-10-09 04:18:56 +00006018StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6019 Stmt *AStmt, SourceLocation StartLoc,
6020 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006021 if (!AStmt)
6022 return StmtError();
6023
Alexey Bataev13314bf2014-10-09 04:18:56 +00006024 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6025 // 1.2.2 OpenMP Language Terminology
6026 // Structured block - An executable statement with a single entry at the
6027 // top and a single exit at the bottom.
6028 // The point of exit cannot be a branch out of the structured block.
6029 // longjmp() and throw() must not violate the entry/exit criteria.
6030 CS->getCapturedDecl()->setNothrow();
6031
6032 getCurFunction()->setHasBranchProtectedScope();
6033
6034 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6035}
6036
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006037StmtResult
6038Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6039 SourceLocation EndLoc,
6040 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006041 if (DSAStack->isParentNowaitRegion()) {
6042 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6043 return StmtError();
6044 }
6045 if (DSAStack->isParentOrderedRegion()) {
6046 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6047 return StmtError();
6048 }
6049 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6050 CancelRegion);
6051}
6052
Alexey Bataev87933c72015-09-18 08:07:34 +00006053StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6054 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006055 SourceLocation EndLoc,
6056 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006057 if (DSAStack->isParentNowaitRegion()) {
6058 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6059 return StmtError();
6060 }
6061 if (DSAStack->isParentOrderedRegion()) {
6062 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6063 return StmtError();
6064 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006065 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006066 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6067 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006068}
6069
Alexey Bataev382967a2015-12-08 12:06:20 +00006070static bool checkGrainsizeNumTasksClauses(Sema &S,
6071 ArrayRef<OMPClause *> Clauses) {
6072 OMPClause *PrevClause = nullptr;
6073 bool ErrorFound = false;
6074 for (auto *C : Clauses) {
6075 if (C->getClauseKind() == OMPC_grainsize ||
6076 C->getClauseKind() == OMPC_num_tasks) {
6077 if (!PrevClause)
6078 PrevClause = C;
6079 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6080 S.Diag(C->getLocStart(),
6081 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6082 << getOpenMPClauseName(C->getClauseKind())
6083 << getOpenMPClauseName(PrevClause->getClauseKind());
6084 S.Diag(PrevClause->getLocStart(),
6085 diag::note_omp_previous_grainsize_num_tasks)
6086 << getOpenMPClauseName(PrevClause->getClauseKind());
6087 ErrorFound = true;
6088 }
6089 }
6090 }
6091 return ErrorFound;
6092}
6093
Alexey Bataev49f6e782015-12-01 04:18:41 +00006094StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6095 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6096 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006097 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006098 if (!AStmt)
6099 return StmtError();
6100
6101 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6102 OMPLoopDirective::HelperExprs B;
6103 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6104 // define the nested loops number.
6105 unsigned NestedLoopCount =
6106 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006107 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006108 VarsWithImplicitDSA, B);
6109 if (NestedLoopCount == 0)
6110 return StmtError();
6111
6112 assert((CurContext->isDependentContext() || B.builtAll()) &&
6113 "omp for loop exprs were not built");
6114
Alexey Bataev382967a2015-12-08 12:06:20 +00006115 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6116 // The grainsize clause and num_tasks clause are mutually exclusive and may
6117 // not appear on the same taskloop directive.
6118 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6119 return StmtError();
6120
Alexey Bataev49f6e782015-12-01 04:18:41 +00006121 getCurFunction()->setHasBranchProtectedScope();
6122 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6123 NestedLoopCount, Clauses, AStmt, B);
6124}
6125
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006126StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6127 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6128 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006129 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006130 if (!AStmt)
6131 return StmtError();
6132
6133 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6134 OMPLoopDirective::HelperExprs B;
6135 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6136 // define the nested loops number.
6137 unsigned NestedLoopCount =
6138 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6139 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6140 VarsWithImplicitDSA, B);
6141 if (NestedLoopCount == 0)
6142 return StmtError();
6143
6144 assert((CurContext->isDependentContext() || B.builtAll()) &&
6145 "omp for loop exprs were not built");
6146
Alexey Bataev5a3af132016-03-29 08:58:54 +00006147 if (!CurContext->isDependentContext()) {
6148 // Finalize the clauses that need pre-built expressions for CodeGen.
6149 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006150 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006151 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006152 B.NumIterations, *this, CurScope,
6153 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006154 return StmtError();
6155 }
6156 }
6157
Alexey Bataev382967a2015-12-08 12:06:20 +00006158 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6159 // The grainsize clause and num_tasks clause are mutually exclusive and may
6160 // not appear on the same taskloop directive.
6161 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6162 return StmtError();
6163
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006164 getCurFunction()->setHasBranchProtectedScope();
6165 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6166 NestedLoopCount, Clauses, AStmt, B);
6167}
6168
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006169StmtResult Sema::ActOnOpenMPDistributeDirective(
6170 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6171 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006172 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006173 if (!AStmt)
6174 return StmtError();
6175
6176 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6177 OMPLoopDirective::HelperExprs B;
6178 // In presence of clause 'collapse' with number of loops, it will
6179 // define the nested loops number.
6180 unsigned NestedLoopCount =
6181 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6182 nullptr /*ordered not a clause on distribute*/, AStmt,
6183 *this, *DSAStack, VarsWithImplicitDSA, B);
6184 if (NestedLoopCount == 0)
6185 return StmtError();
6186
6187 assert((CurContext->isDependentContext() || B.builtAll()) &&
6188 "omp for loop exprs were not built");
6189
6190 getCurFunction()->setHasBranchProtectedScope();
6191 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6192 NestedLoopCount, Clauses, AStmt, B);
6193}
6194
Carlo Bertolli9925f152016-06-27 14:55:37 +00006195StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6196 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6197 SourceLocation EndLoc,
6198 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6199 if (!AStmt)
6200 return StmtError();
6201
6202 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6203 // 1.2.2 OpenMP Language Terminology
6204 // Structured block - An executable statement with a single entry at the
6205 // top and a single exit at the bottom.
6206 // The point of exit cannot be a branch out of the structured block.
6207 // longjmp() and throw() must not violate the entry/exit criteria.
6208 CS->getCapturedDecl()->setNothrow();
6209
6210 OMPLoopDirective::HelperExprs B;
6211 // In presence of clause 'collapse' with number of loops, it will
6212 // define the nested loops number.
6213 unsigned NestedLoopCount = CheckOpenMPLoop(
6214 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6215 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6216 VarsWithImplicitDSA, B);
6217 if (NestedLoopCount == 0)
6218 return StmtError();
6219
6220 assert((CurContext->isDependentContext() || B.builtAll()) &&
6221 "omp for loop exprs were not built");
6222
6223 getCurFunction()->setHasBranchProtectedScope();
6224 return OMPDistributeParallelForDirective::Create(
6225 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6226}
6227
Kelvin Li4a39add2016-07-05 05:00:15 +00006228StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6230 SourceLocation EndLoc,
6231 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6232 if (!AStmt)
6233 return StmtError();
6234
6235 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6236 // 1.2.2 OpenMP Language Terminology
6237 // Structured block - An executable statement with a single entry at the
6238 // top and a single exit at the bottom.
6239 // The point of exit cannot be a branch out of the structured block.
6240 // longjmp() and throw() must not violate the entry/exit criteria.
6241 CS->getCapturedDecl()->setNothrow();
6242
6243 OMPLoopDirective::HelperExprs B;
6244 // In presence of clause 'collapse' with number of loops, it will
6245 // define the nested loops number.
6246 unsigned NestedLoopCount = CheckOpenMPLoop(
6247 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6248 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6249 VarsWithImplicitDSA, B);
6250 if (NestedLoopCount == 0)
6251 return StmtError();
6252
6253 assert((CurContext->isDependentContext() || B.builtAll()) &&
6254 "omp for loop exprs were not built");
6255
Kelvin Lic5609492016-07-15 04:39:07 +00006256 if (checkSimdlenSafelenSpecified(*this, Clauses))
6257 return StmtError();
6258
Kelvin Li4a39add2016-07-05 05:00:15 +00006259 getCurFunction()->setHasBranchProtectedScope();
6260 return OMPDistributeParallelForSimdDirective::Create(
6261 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6262}
6263
Kelvin Li787f3fc2016-07-06 04:45:38 +00006264StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6265 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6266 SourceLocation EndLoc,
6267 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6268 if (!AStmt)
6269 return StmtError();
6270
6271 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6272 // 1.2.2 OpenMP Language Terminology
6273 // Structured block - An executable statement with a single entry at the
6274 // top and a single exit at the bottom.
6275 // The point of exit cannot be a branch out of the structured block.
6276 // longjmp() and throw() must not violate the entry/exit criteria.
6277 CS->getCapturedDecl()->setNothrow();
6278
6279 OMPLoopDirective::HelperExprs B;
6280 // In presence of clause 'collapse' with number of loops, it will
6281 // define the nested loops number.
6282 unsigned NestedLoopCount =
6283 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6284 nullptr /*ordered not a clause on distribute*/, AStmt,
6285 *this, *DSAStack, VarsWithImplicitDSA, B);
6286 if (NestedLoopCount == 0)
6287 return StmtError();
6288
6289 assert((CurContext->isDependentContext() || B.builtAll()) &&
6290 "omp for loop exprs were not built");
6291
Kelvin Lic5609492016-07-15 04:39:07 +00006292 if (checkSimdlenSafelenSpecified(*this, Clauses))
6293 return StmtError();
6294
Kelvin Li787f3fc2016-07-06 04:45:38 +00006295 getCurFunction()->setHasBranchProtectedScope();
6296 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6297 NestedLoopCount, Clauses, AStmt, B);
6298}
6299
Kelvin Lia579b912016-07-14 02:54:56 +00006300StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6301 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6302 SourceLocation EndLoc,
6303 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6304 if (!AStmt)
6305 return StmtError();
6306
6307 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6308 // 1.2.2 OpenMP Language Terminology
6309 // Structured block - An executable statement with a single entry at the
6310 // top and a single exit at the bottom.
6311 // The point of exit cannot be a branch out of the structured block.
6312 // longjmp() and throw() must not violate the entry/exit criteria.
6313 CS->getCapturedDecl()->setNothrow();
6314
6315 OMPLoopDirective::HelperExprs B;
6316 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6317 // define the nested loops number.
6318 unsigned NestedLoopCount = CheckOpenMPLoop(
6319 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6320 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6321 VarsWithImplicitDSA, B);
6322 if (NestedLoopCount == 0)
6323 return StmtError();
6324
6325 assert((CurContext->isDependentContext() || B.builtAll()) &&
6326 "omp target parallel for simd loop exprs were not built");
6327
6328 if (!CurContext->isDependentContext()) {
6329 // Finalize the clauses that need pre-built expressions for CodeGen.
6330 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006331 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006332 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6333 B.NumIterations, *this, CurScope,
6334 DSAStack))
6335 return StmtError();
6336 }
6337 }
Kelvin Lic5609492016-07-15 04:39:07 +00006338 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006339 return StmtError();
6340
6341 getCurFunction()->setHasBranchProtectedScope();
6342 return OMPTargetParallelForSimdDirective::Create(
6343 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6344}
6345
Kelvin Li986330c2016-07-20 22:57:10 +00006346StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6347 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6348 SourceLocation EndLoc,
6349 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6350 if (!AStmt)
6351 return StmtError();
6352
6353 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6354 // 1.2.2 OpenMP Language Terminology
6355 // Structured block - An executable statement with a single entry at the
6356 // top and a single exit at the bottom.
6357 // The point of exit cannot be a branch out of the structured block.
6358 // longjmp() and throw() must not violate the entry/exit criteria.
6359 CS->getCapturedDecl()->setNothrow();
6360
6361 OMPLoopDirective::HelperExprs B;
6362 // In presence of clause 'collapse' with number of loops, it will define the
6363 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006364 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006365 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6366 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6367 VarsWithImplicitDSA, B);
6368 if (NestedLoopCount == 0)
6369 return StmtError();
6370
6371 assert((CurContext->isDependentContext() || B.builtAll()) &&
6372 "omp target simd loop exprs were not built");
6373
6374 if (!CurContext->isDependentContext()) {
6375 // Finalize the clauses that need pre-built expressions for CodeGen.
6376 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006377 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006378 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6379 B.NumIterations, *this, CurScope,
6380 DSAStack))
6381 return StmtError();
6382 }
6383 }
6384
6385 if (checkSimdlenSafelenSpecified(*this, Clauses))
6386 return StmtError();
6387
6388 getCurFunction()->setHasBranchProtectedScope();
6389 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6390 NestedLoopCount, Clauses, AStmt, B);
6391}
6392
Kelvin Li02532872016-08-05 14:37:37 +00006393StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6395 SourceLocation EndLoc,
6396 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6397 if (!AStmt)
6398 return StmtError();
6399
6400 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6401 // 1.2.2 OpenMP Language Terminology
6402 // Structured block - An executable statement with a single entry at the
6403 // top and a single exit at the bottom.
6404 // The point of exit cannot be a branch out of the structured block.
6405 // longjmp() and throw() must not violate the entry/exit criteria.
6406 CS->getCapturedDecl()->setNothrow();
6407
6408 OMPLoopDirective::HelperExprs B;
6409 // In presence of clause 'collapse' with number of loops, it will
6410 // define the nested loops number.
6411 unsigned NestedLoopCount =
6412 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6413 nullptr /*ordered not a clause on distribute*/, AStmt,
6414 *this, *DSAStack, VarsWithImplicitDSA, B);
6415 if (NestedLoopCount == 0)
6416 return StmtError();
6417
6418 assert((CurContext->isDependentContext() || B.builtAll()) &&
6419 "omp teams distribute loop exprs were not built");
6420
6421 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006422 return OMPTeamsDistributeDirective::Create(
6423 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006424}
6425
Kelvin Li4e325f72016-10-25 12:50:55 +00006426StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6427 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6428 SourceLocation EndLoc,
6429 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6430 if (!AStmt)
6431 return StmtError();
6432
6433 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6434 // 1.2.2 OpenMP Language Terminology
6435 // Structured block - An executable statement with a single entry at the
6436 // top and a single exit at the bottom.
6437 // The point of exit cannot be a branch out of the structured block.
6438 // longjmp() and throw() must not violate the entry/exit criteria.
6439 CS->getCapturedDecl()->setNothrow();
6440
6441 OMPLoopDirective::HelperExprs B;
6442 // In presence of clause 'collapse' with number of loops, it will
6443 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006444 unsigned NestedLoopCount = CheckOpenMPLoop(
6445 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6446 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6447 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006448
6449 if (NestedLoopCount == 0)
6450 return StmtError();
6451
6452 assert((CurContext->isDependentContext() || B.builtAll()) &&
6453 "omp teams distribute simd loop exprs were not built");
6454
6455 if (!CurContext->isDependentContext()) {
6456 // Finalize the clauses that need pre-built expressions for CodeGen.
6457 for (auto C : Clauses) {
6458 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6459 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6460 B.NumIterations, *this, CurScope,
6461 DSAStack))
6462 return StmtError();
6463 }
6464 }
6465
6466 if (checkSimdlenSafelenSpecified(*this, Clauses))
6467 return StmtError();
6468
6469 getCurFunction()->setHasBranchProtectedScope();
6470 return OMPTeamsDistributeSimdDirective::Create(
6471 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6472}
6473
Kelvin Li579e41c2016-11-30 23:51:03 +00006474StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6475 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6476 SourceLocation EndLoc,
6477 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6478 if (!AStmt)
6479 return StmtError();
6480
6481 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6482 // 1.2.2 OpenMP Language Terminology
6483 // Structured block - An executable statement with a single entry at the
6484 // top and a single exit at the bottom.
6485 // The point of exit cannot be a branch out of the structured block.
6486 // longjmp() and throw() must not violate the entry/exit criteria.
6487 CS->getCapturedDecl()->setNothrow();
6488
6489 OMPLoopDirective::HelperExprs B;
6490 // In presence of clause 'collapse' with number of loops, it will
6491 // define the nested loops number.
6492 auto NestedLoopCount = CheckOpenMPLoop(
6493 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6494 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6495 VarsWithImplicitDSA, B);
6496
6497 if (NestedLoopCount == 0)
6498 return StmtError();
6499
6500 assert((CurContext->isDependentContext() || B.builtAll()) &&
6501 "omp for loop exprs were not built");
6502
6503 if (!CurContext->isDependentContext()) {
6504 // Finalize the clauses that need pre-built expressions for CodeGen.
6505 for (auto C : Clauses) {
6506 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6507 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6508 B.NumIterations, *this, CurScope,
6509 DSAStack))
6510 return StmtError();
6511 }
6512 }
6513
6514 if (checkSimdlenSafelenSpecified(*this, Clauses))
6515 return StmtError();
6516
6517 getCurFunction()->setHasBranchProtectedScope();
6518 return OMPTeamsDistributeParallelForSimdDirective::Create(
6519 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6520}
6521
Kelvin Li7ade93f2016-12-09 03:24:30 +00006522StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6523 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6524 SourceLocation EndLoc,
6525 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6526 if (!AStmt)
6527 return StmtError();
6528
6529 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6530 // 1.2.2 OpenMP Language Terminology
6531 // Structured block - An executable statement with a single entry at the
6532 // top and a single exit at the bottom.
6533 // The point of exit cannot be a branch out of the structured block.
6534 // longjmp() and throw() must not violate the entry/exit criteria.
6535 CS->getCapturedDecl()->setNothrow();
6536
6537 OMPLoopDirective::HelperExprs B;
6538 // In presence of clause 'collapse' with number of loops, it will
6539 // define the nested loops number.
6540 unsigned NestedLoopCount = CheckOpenMPLoop(
6541 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6542 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6543 VarsWithImplicitDSA, B);
6544
6545 if (NestedLoopCount == 0)
6546 return StmtError();
6547
6548 assert((CurContext->isDependentContext() || B.builtAll()) &&
6549 "omp for loop exprs were not built");
6550
6551 if (!CurContext->isDependentContext()) {
6552 // Finalize the clauses that need pre-built expressions for CodeGen.
6553 for (auto C : Clauses) {
6554 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6555 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6556 B.NumIterations, *this, CurScope,
6557 DSAStack))
6558 return StmtError();
6559 }
6560 }
6561
6562 getCurFunction()->setHasBranchProtectedScope();
6563 return OMPTeamsDistributeParallelForDirective::Create(
6564 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6565}
6566
Kelvin Libf594a52016-12-17 05:48:59 +00006567StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6568 Stmt *AStmt,
6569 SourceLocation StartLoc,
6570 SourceLocation EndLoc) {
6571 if (!AStmt)
6572 return StmtError();
6573
6574 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6575 // 1.2.2 OpenMP Language Terminology
6576 // Structured block - An executable statement with a single entry at the
6577 // top and a single exit at the bottom.
6578 // The point of exit cannot be a branch out of the structured block.
6579 // longjmp() and throw() must not violate the entry/exit criteria.
6580 CS->getCapturedDecl()->setNothrow();
6581
6582 getCurFunction()->setHasBranchProtectedScope();
6583
6584 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6585 AStmt);
6586}
6587
Kelvin Li83c451e2016-12-25 04:52:54 +00006588StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6589 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6590 SourceLocation EndLoc,
6591 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6592 if (!AStmt)
6593 return StmtError();
6594
6595 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6596 // 1.2.2 OpenMP Language Terminology
6597 // Structured block - An executable statement with a single entry at the
6598 // top and a single exit at the bottom.
6599 // The point of exit cannot be a branch out of the structured block.
6600 // longjmp() and throw() must not violate the entry/exit criteria.
6601 CS->getCapturedDecl()->setNothrow();
6602
6603 OMPLoopDirective::HelperExprs B;
6604 // In presence of clause 'collapse' with number of loops, it will
6605 // define the nested loops number.
6606 auto NestedLoopCount = CheckOpenMPLoop(
6607 OMPD_target_teams_distribute,
6608 getCollapseNumberExpr(Clauses),
6609 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6610 VarsWithImplicitDSA, B);
6611 if (NestedLoopCount == 0)
6612 return StmtError();
6613
6614 assert((CurContext->isDependentContext() || B.builtAll()) &&
6615 "omp target teams distribute loop exprs were not built");
6616
6617 getCurFunction()->setHasBranchProtectedScope();
6618 return OMPTargetTeamsDistributeDirective::Create(
6619 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6620}
6621
Kelvin Li80e8f562016-12-29 22:16:30 +00006622StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6623 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6624 SourceLocation EndLoc,
6625 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6626 if (!AStmt)
6627 return StmtError();
6628
6629 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6630 // 1.2.2 OpenMP Language Terminology
6631 // Structured block - An executable statement with a single entry at the
6632 // top and a single exit at the bottom.
6633 // The point of exit cannot be a branch out of the structured block.
6634 // longjmp() and throw() must not violate the entry/exit criteria.
6635 CS->getCapturedDecl()->setNothrow();
6636
6637 OMPLoopDirective::HelperExprs B;
6638 // In presence of clause 'collapse' with number of loops, it will
6639 // define the nested loops number.
6640 auto NestedLoopCount = CheckOpenMPLoop(
6641 OMPD_target_teams_distribute_parallel_for,
6642 getCollapseNumberExpr(Clauses),
6643 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6644 VarsWithImplicitDSA, B);
6645 if (NestedLoopCount == 0)
6646 return StmtError();
6647
6648 assert((CurContext->isDependentContext() || B.builtAll()) &&
6649 "omp target teams distribute parallel for loop exprs were not built");
6650
6651 if (!CurContext->isDependentContext()) {
6652 // Finalize the clauses that need pre-built expressions for CodeGen.
6653 for (auto C : Clauses) {
6654 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6655 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6656 B.NumIterations, *this, CurScope,
6657 DSAStack))
6658 return StmtError();
6659 }
6660 }
6661
6662 getCurFunction()->setHasBranchProtectedScope();
6663 return OMPTargetTeamsDistributeParallelForDirective::Create(
6664 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6665}
6666
Kelvin Li1851df52017-01-03 05:23:48 +00006667StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6668 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6669 SourceLocation EndLoc,
6670 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6671 if (!AStmt)
6672 return StmtError();
6673
6674 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6675 // 1.2.2 OpenMP Language Terminology
6676 // Structured block - An executable statement with a single entry at the
6677 // top and a single exit at the bottom.
6678 // The point of exit cannot be a branch out of the structured block.
6679 // longjmp() and throw() must not violate the entry/exit criteria.
6680 CS->getCapturedDecl()->setNothrow();
6681
6682 OMPLoopDirective::HelperExprs B;
6683 // In presence of clause 'collapse' with number of loops, it will
6684 // define the nested loops number.
6685 auto NestedLoopCount = CheckOpenMPLoop(
6686 OMPD_target_teams_distribute_parallel_for_simd,
6687 getCollapseNumberExpr(Clauses),
6688 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6689 VarsWithImplicitDSA, B);
6690 if (NestedLoopCount == 0)
6691 return StmtError();
6692
6693 assert((CurContext->isDependentContext() || B.builtAll()) &&
6694 "omp target teams distribute parallel for simd loop exprs were not "
6695 "built");
6696
6697 if (!CurContext->isDependentContext()) {
6698 // Finalize the clauses that need pre-built expressions for CodeGen.
6699 for (auto C : Clauses) {
6700 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6701 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6702 B.NumIterations, *this, CurScope,
6703 DSAStack))
6704 return StmtError();
6705 }
6706 }
6707
6708 getCurFunction()->setHasBranchProtectedScope();
6709 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6710 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6711}
6712
Kelvin Lida681182017-01-10 18:08:18 +00006713StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6714 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6715 SourceLocation EndLoc,
6716 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6717 if (!AStmt)
6718 return StmtError();
6719
6720 auto *CS = cast<CapturedStmt>(AStmt);
6721 // 1.2.2 OpenMP Language Terminology
6722 // Structured block - An executable statement with a single entry at the
6723 // top and a single exit at the bottom.
6724 // The point of exit cannot be a branch out of the structured block.
6725 // longjmp() and throw() must not violate the entry/exit criteria.
6726 CS->getCapturedDecl()->setNothrow();
6727
6728 OMPLoopDirective::HelperExprs B;
6729 // In presence of clause 'collapse' with number of loops, it will
6730 // define the nested loops number.
6731 auto NestedLoopCount = CheckOpenMPLoop(
6732 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6733 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6734 VarsWithImplicitDSA, B);
6735 if (NestedLoopCount == 0)
6736 return StmtError();
6737
6738 assert((CurContext->isDependentContext() || B.builtAll()) &&
6739 "omp target teams distribute simd loop exprs were not built");
6740
6741 getCurFunction()->setHasBranchProtectedScope();
6742 return OMPTargetTeamsDistributeSimdDirective::Create(
6743 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6744}
6745
Alexey Bataeved09d242014-05-28 05:53:51 +00006746OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006747 SourceLocation StartLoc,
6748 SourceLocation LParenLoc,
6749 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006750 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006751 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006752 case OMPC_final:
6753 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6754 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006755 case OMPC_num_threads:
6756 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6757 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006758 case OMPC_safelen:
6759 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6760 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006761 case OMPC_simdlen:
6762 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6763 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006764 case OMPC_collapse:
6765 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6766 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006767 case OMPC_ordered:
6768 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6769 break;
Michael Wonge710d542015-08-07 16:16:36 +00006770 case OMPC_device:
6771 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6772 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006773 case OMPC_num_teams:
6774 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6775 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006776 case OMPC_thread_limit:
6777 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6778 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006779 case OMPC_priority:
6780 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6781 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006782 case OMPC_grainsize:
6783 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6784 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006785 case OMPC_num_tasks:
6786 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6787 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006788 case OMPC_hint:
6789 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6790 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006791 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006792 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006793 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006794 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006795 case OMPC_private:
6796 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006797 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006798 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006799 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006800 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006801 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006802 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006803 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006804 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006805 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006806 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006807 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006808 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006809 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006810 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006811 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006812 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006813 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006814 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006815 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006816 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006817 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006818 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006819 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006820 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006821 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006822 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006823 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006824 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006825 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006826 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006827 llvm_unreachable("Clause is not allowed.");
6828 }
6829 return Res;
6830}
6831
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006832// An OpenMP directive such as 'target parallel' has two captured regions:
6833// for the 'target' and 'parallel' respectively. This function returns
6834// the region in which to capture expressions associated with a clause.
6835// A return value of OMPD_unknown signifies that the expression should not
6836// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006837static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6838 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6839 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006840 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6841
6842 switch (CKind) {
6843 case OMPC_if:
6844 switch (DKind) {
6845 case OMPD_target_parallel:
6846 // If this clause applies to the nested 'parallel' region, capture within
6847 // the 'target' region, otherwise do not capture.
6848 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6849 CaptureRegion = OMPD_target;
6850 break;
6851 case OMPD_cancel:
6852 case OMPD_parallel:
6853 case OMPD_parallel_sections:
6854 case OMPD_parallel_for:
6855 case OMPD_parallel_for_simd:
6856 case OMPD_target:
6857 case OMPD_target_simd:
6858 case OMPD_target_parallel_for:
6859 case OMPD_target_parallel_for_simd:
6860 case OMPD_target_teams:
6861 case OMPD_target_teams_distribute:
6862 case OMPD_target_teams_distribute_simd:
6863 case OMPD_target_teams_distribute_parallel_for:
6864 case OMPD_target_teams_distribute_parallel_for_simd:
6865 case OMPD_teams_distribute_parallel_for:
6866 case OMPD_teams_distribute_parallel_for_simd:
6867 case OMPD_distribute_parallel_for:
6868 case OMPD_distribute_parallel_for_simd:
6869 case OMPD_task:
6870 case OMPD_taskloop:
6871 case OMPD_taskloop_simd:
6872 case OMPD_target_data:
6873 case OMPD_target_enter_data:
6874 case OMPD_target_exit_data:
6875 case OMPD_target_update:
6876 // Do not capture if-clause expressions.
6877 break;
6878 case OMPD_threadprivate:
6879 case OMPD_taskyield:
6880 case OMPD_barrier:
6881 case OMPD_taskwait:
6882 case OMPD_cancellation_point:
6883 case OMPD_flush:
6884 case OMPD_declare_reduction:
6885 case OMPD_declare_simd:
6886 case OMPD_declare_target:
6887 case OMPD_end_declare_target:
6888 case OMPD_teams:
6889 case OMPD_simd:
6890 case OMPD_for:
6891 case OMPD_for_simd:
6892 case OMPD_sections:
6893 case OMPD_section:
6894 case OMPD_single:
6895 case OMPD_master:
6896 case OMPD_critical:
6897 case OMPD_taskgroup:
6898 case OMPD_distribute:
6899 case OMPD_ordered:
6900 case OMPD_atomic:
6901 case OMPD_distribute_simd:
6902 case OMPD_teams_distribute:
6903 case OMPD_teams_distribute_simd:
6904 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6905 case OMPD_unknown:
6906 llvm_unreachable("Unknown OpenMP directive");
6907 }
6908 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006909 case OMPC_num_threads:
6910 switch (DKind) {
6911 case OMPD_target_parallel:
6912 CaptureRegion = OMPD_target;
6913 break;
6914 case OMPD_cancel:
6915 case OMPD_parallel:
6916 case OMPD_parallel_sections:
6917 case OMPD_parallel_for:
6918 case OMPD_parallel_for_simd:
6919 case OMPD_target:
6920 case OMPD_target_simd:
6921 case OMPD_target_parallel_for:
6922 case OMPD_target_parallel_for_simd:
6923 case OMPD_target_teams:
6924 case OMPD_target_teams_distribute:
6925 case OMPD_target_teams_distribute_simd:
6926 case OMPD_target_teams_distribute_parallel_for:
6927 case OMPD_target_teams_distribute_parallel_for_simd:
6928 case OMPD_teams_distribute_parallel_for:
6929 case OMPD_teams_distribute_parallel_for_simd:
6930 case OMPD_distribute_parallel_for:
6931 case OMPD_distribute_parallel_for_simd:
6932 case OMPD_task:
6933 case OMPD_taskloop:
6934 case OMPD_taskloop_simd:
6935 case OMPD_target_data:
6936 case OMPD_target_enter_data:
6937 case OMPD_target_exit_data:
6938 case OMPD_target_update:
6939 // Do not capture num_threads-clause expressions.
6940 break;
6941 case OMPD_threadprivate:
6942 case OMPD_taskyield:
6943 case OMPD_barrier:
6944 case OMPD_taskwait:
6945 case OMPD_cancellation_point:
6946 case OMPD_flush:
6947 case OMPD_declare_reduction:
6948 case OMPD_declare_simd:
6949 case OMPD_declare_target:
6950 case OMPD_end_declare_target:
6951 case OMPD_teams:
6952 case OMPD_simd:
6953 case OMPD_for:
6954 case OMPD_for_simd:
6955 case OMPD_sections:
6956 case OMPD_section:
6957 case OMPD_single:
6958 case OMPD_master:
6959 case OMPD_critical:
6960 case OMPD_taskgroup:
6961 case OMPD_distribute:
6962 case OMPD_ordered:
6963 case OMPD_atomic:
6964 case OMPD_distribute_simd:
6965 case OMPD_teams_distribute:
6966 case OMPD_teams_distribute_simd:
6967 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6968 case OMPD_unknown:
6969 llvm_unreachable("Unknown OpenMP directive");
6970 }
6971 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00006972 case OMPC_num_teams:
6973 switch (DKind) {
6974 case OMPD_target_teams:
6975 CaptureRegion = OMPD_target;
6976 break;
6977 case OMPD_cancel:
6978 case OMPD_parallel:
6979 case OMPD_parallel_sections:
6980 case OMPD_parallel_for:
6981 case OMPD_parallel_for_simd:
6982 case OMPD_target:
6983 case OMPD_target_simd:
6984 case OMPD_target_parallel:
6985 case OMPD_target_parallel_for:
6986 case OMPD_target_parallel_for_simd:
6987 case OMPD_target_teams_distribute:
6988 case OMPD_target_teams_distribute_simd:
6989 case OMPD_target_teams_distribute_parallel_for:
6990 case OMPD_target_teams_distribute_parallel_for_simd:
6991 case OMPD_teams_distribute_parallel_for:
6992 case OMPD_teams_distribute_parallel_for_simd:
6993 case OMPD_distribute_parallel_for:
6994 case OMPD_distribute_parallel_for_simd:
6995 case OMPD_task:
6996 case OMPD_taskloop:
6997 case OMPD_taskloop_simd:
6998 case OMPD_target_data:
6999 case OMPD_target_enter_data:
7000 case OMPD_target_exit_data:
7001 case OMPD_target_update:
7002 case OMPD_teams:
7003 case OMPD_teams_distribute:
7004 case OMPD_teams_distribute_simd:
7005 // Do not capture num_teams-clause expressions.
7006 break;
7007 case OMPD_threadprivate:
7008 case OMPD_taskyield:
7009 case OMPD_barrier:
7010 case OMPD_taskwait:
7011 case OMPD_cancellation_point:
7012 case OMPD_flush:
7013 case OMPD_declare_reduction:
7014 case OMPD_declare_simd:
7015 case OMPD_declare_target:
7016 case OMPD_end_declare_target:
7017 case OMPD_simd:
7018 case OMPD_for:
7019 case OMPD_for_simd:
7020 case OMPD_sections:
7021 case OMPD_section:
7022 case OMPD_single:
7023 case OMPD_master:
7024 case OMPD_critical:
7025 case OMPD_taskgroup:
7026 case OMPD_distribute:
7027 case OMPD_ordered:
7028 case OMPD_atomic:
7029 case OMPD_distribute_simd:
7030 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7031 case OMPD_unknown:
7032 llvm_unreachable("Unknown OpenMP directive");
7033 }
7034 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007035 case OMPC_thread_limit:
7036 switch (DKind) {
7037 case OMPD_target_teams:
7038 CaptureRegion = OMPD_target;
7039 break;
7040 case OMPD_cancel:
7041 case OMPD_parallel:
7042 case OMPD_parallel_sections:
7043 case OMPD_parallel_for:
7044 case OMPD_parallel_for_simd:
7045 case OMPD_target:
7046 case OMPD_target_simd:
7047 case OMPD_target_parallel:
7048 case OMPD_target_parallel_for:
7049 case OMPD_target_parallel_for_simd:
7050 case OMPD_target_teams_distribute:
7051 case OMPD_target_teams_distribute_simd:
7052 case OMPD_target_teams_distribute_parallel_for:
7053 case OMPD_target_teams_distribute_parallel_for_simd:
7054 case OMPD_teams_distribute_parallel_for:
7055 case OMPD_teams_distribute_parallel_for_simd:
7056 case OMPD_distribute_parallel_for:
7057 case OMPD_distribute_parallel_for_simd:
7058 case OMPD_task:
7059 case OMPD_taskloop:
7060 case OMPD_taskloop_simd:
7061 case OMPD_target_data:
7062 case OMPD_target_enter_data:
7063 case OMPD_target_exit_data:
7064 case OMPD_target_update:
7065 case OMPD_teams:
7066 case OMPD_teams_distribute:
7067 case OMPD_teams_distribute_simd:
7068 // Do not capture thread_limit-clause expressions.
7069 break;
7070 case OMPD_threadprivate:
7071 case OMPD_taskyield:
7072 case OMPD_barrier:
7073 case OMPD_taskwait:
7074 case OMPD_cancellation_point:
7075 case OMPD_flush:
7076 case OMPD_declare_reduction:
7077 case OMPD_declare_simd:
7078 case OMPD_declare_target:
7079 case OMPD_end_declare_target:
7080 case OMPD_simd:
7081 case OMPD_for:
7082 case OMPD_for_simd:
7083 case OMPD_sections:
7084 case OMPD_section:
7085 case OMPD_single:
7086 case OMPD_master:
7087 case OMPD_critical:
7088 case OMPD_taskgroup:
7089 case OMPD_distribute:
7090 case OMPD_ordered:
7091 case OMPD_atomic:
7092 case OMPD_distribute_simd:
7093 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7094 case OMPD_unknown:
7095 llvm_unreachable("Unknown OpenMP directive");
7096 }
7097 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007098 case OMPC_schedule:
7099 case OMPC_dist_schedule:
7100 case OMPC_firstprivate:
7101 case OMPC_lastprivate:
7102 case OMPC_reduction:
7103 case OMPC_linear:
7104 case OMPC_default:
7105 case OMPC_proc_bind:
7106 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007107 case OMPC_safelen:
7108 case OMPC_simdlen:
7109 case OMPC_collapse:
7110 case OMPC_private:
7111 case OMPC_shared:
7112 case OMPC_aligned:
7113 case OMPC_copyin:
7114 case OMPC_copyprivate:
7115 case OMPC_ordered:
7116 case OMPC_nowait:
7117 case OMPC_untied:
7118 case OMPC_mergeable:
7119 case OMPC_threadprivate:
7120 case OMPC_flush:
7121 case OMPC_read:
7122 case OMPC_write:
7123 case OMPC_update:
7124 case OMPC_capture:
7125 case OMPC_seq_cst:
7126 case OMPC_depend:
7127 case OMPC_device:
7128 case OMPC_threads:
7129 case OMPC_simd:
7130 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007131 case OMPC_priority:
7132 case OMPC_grainsize:
7133 case OMPC_nogroup:
7134 case OMPC_num_tasks:
7135 case OMPC_hint:
7136 case OMPC_defaultmap:
7137 case OMPC_unknown:
7138 case OMPC_uniform:
7139 case OMPC_to:
7140 case OMPC_from:
7141 case OMPC_use_device_ptr:
7142 case OMPC_is_device_ptr:
7143 llvm_unreachable("Unexpected OpenMP clause.");
7144 }
7145 return CaptureRegion;
7146}
7147
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007148OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7149 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007150 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007151 SourceLocation NameModifierLoc,
7152 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007153 SourceLocation EndLoc) {
7154 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007155 Stmt *HelperValStmt = nullptr;
7156 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007157 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7158 !Condition->isInstantiationDependent() &&
7159 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007160 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007161 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007162 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007163
Richard Smith03a4aa32016-06-23 19:02:52 +00007164 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007165
7166 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7167 CaptureRegion =
7168 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7169 if (CaptureRegion != OMPD_unknown) {
7170 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7171 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7172 HelperValStmt = buildPreInits(Context, Captures);
7173 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007174 }
7175
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007176 return new (Context)
7177 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7178 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007179}
7180
Alexey Bataev3778b602014-07-17 07:32:53 +00007181OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7182 SourceLocation StartLoc,
7183 SourceLocation LParenLoc,
7184 SourceLocation EndLoc) {
7185 Expr *ValExpr = Condition;
7186 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7187 !Condition->isInstantiationDependent() &&
7188 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007189 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007190 if (Val.isInvalid())
7191 return nullptr;
7192
Richard Smith03a4aa32016-06-23 19:02:52 +00007193 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007194 }
7195
7196 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7197}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007198ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7199 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007200 if (!Op)
7201 return ExprError();
7202
7203 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7204 public:
7205 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007206 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007207 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7208 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007209 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7210 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007211 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7212 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007213 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7214 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007215 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7216 QualType T,
7217 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007218 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7219 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007220 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7221 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007222 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007223 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007224 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007225 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7226 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007227 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7228 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007229 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7230 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007231 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007232 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007233 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007234 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7235 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007236 llvm_unreachable("conversion functions are permitted");
7237 }
7238 } ConvertDiagnoser;
7239 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7240}
7241
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007242static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007243 OpenMPClauseKind CKind,
7244 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007245 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7246 !ValExpr->isInstantiationDependent()) {
7247 SourceLocation Loc = ValExpr->getExprLoc();
7248 ExprResult Value =
7249 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7250 if (Value.isInvalid())
7251 return false;
7252
7253 ValExpr = Value.get();
7254 // The expression must evaluate to a non-negative integer value.
7255 llvm::APSInt Result;
7256 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007257 Result.isSigned() &&
7258 !((!StrictlyPositive && Result.isNonNegative()) ||
7259 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007260 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007261 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7262 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007263 return false;
7264 }
7265 }
7266 return true;
7267}
7268
Alexey Bataev568a8332014-03-06 06:15:19 +00007269OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7270 SourceLocation StartLoc,
7271 SourceLocation LParenLoc,
7272 SourceLocation EndLoc) {
7273 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007274 Stmt *HelperValStmt = nullptr;
7275 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007276
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007277 // OpenMP [2.5, Restrictions]
7278 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007279 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7280 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007281 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007282
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007283 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7284 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7285 if (CaptureRegion != OMPD_unknown) {
7286 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7287 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7288 HelperValStmt = buildPreInits(Context, Captures);
7289 }
7290
7291 return new (Context) OMPNumThreadsClause(
7292 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007293}
7294
Alexey Bataev62c87d22014-03-21 04:51:18 +00007295ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007296 OpenMPClauseKind CKind,
7297 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007298 if (!E)
7299 return ExprError();
7300 if (E->isValueDependent() || E->isTypeDependent() ||
7301 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007302 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007303 llvm::APSInt Result;
7304 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7305 if (ICE.isInvalid())
7306 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007307 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7308 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007309 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007310 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7311 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007312 return ExprError();
7313 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007314 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7315 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7316 << E->getSourceRange();
7317 return ExprError();
7318 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007319 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7320 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007321 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007322 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007323 return ICE;
7324}
7325
7326OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7327 SourceLocation LParenLoc,
7328 SourceLocation EndLoc) {
7329 // OpenMP [2.8.1, simd construct, Description]
7330 // The parameter of the safelen clause must be a constant
7331 // positive integer expression.
7332 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7333 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007334 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007335 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007336 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007337}
7338
Alexey Bataev66b15b52015-08-21 11:14:16 +00007339OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7340 SourceLocation LParenLoc,
7341 SourceLocation EndLoc) {
7342 // OpenMP [2.8.1, simd construct, Description]
7343 // The parameter of the simdlen clause must be a constant
7344 // positive integer expression.
7345 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7346 if (Simdlen.isInvalid())
7347 return nullptr;
7348 return new (Context)
7349 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7350}
7351
Alexander Musman64d33f12014-06-04 07:53:32 +00007352OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7353 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007354 SourceLocation LParenLoc,
7355 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007356 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007357 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007358 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007359 // The parameter of the collapse clause must be a constant
7360 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007361 ExprResult NumForLoopsResult =
7362 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7363 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007364 return nullptr;
7365 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007366 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007367}
7368
Alexey Bataev10e775f2015-07-30 11:36:16 +00007369OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7370 SourceLocation EndLoc,
7371 SourceLocation LParenLoc,
7372 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007373 // OpenMP [2.7.1, loop construct, Description]
7374 // OpenMP [2.8.1, simd construct, Description]
7375 // OpenMP [2.9.6, distribute construct, Description]
7376 // The parameter of the ordered clause must be a constant
7377 // positive integer expression if any.
7378 if (NumForLoops && LParenLoc.isValid()) {
7379 ExprResult NumForLoopsResult =
7380 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7381 if (NumForLoopsResult.isInvalid())
7382 return nullptr;
7383 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007384 } else
7385 NumForLoops = nullptr;
7386 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007387 return new (Context)
7388 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7389}
7390
Alexey Bataeved09d242014-05-28 05:53:51 +00007391OMPClause *Sema::ActOnOpenMPSimpleClause(
7392 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7393 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007394 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007395 switch (Kind) {
7396 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007397 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007398 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7399 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007400 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007401 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007402 Res = ActOnOpenMPProcBindClause(
7403 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7404 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007405 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007406 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007407 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007408 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007409 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007410 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007411 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007412 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007413 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007414 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007415 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007416 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007417 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007418 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007419 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007420 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007421 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007422 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007423 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007424 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007425 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007426 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007427 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007428 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007429 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007430 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007431 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007432 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007433 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007434 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007435 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007436 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007437 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007438 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007439 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007440 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007441 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007442 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007443 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007444 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007445 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007446 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007447 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007448 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007449 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007450 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007451 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007452 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007453 llvm_unreachable("Clause is not allowed.");
7454 }
7455 return Res;
7456}
7457
Alexey Bataev6402bca2015-12-28 07:25:51 +00007458static std::string
7459getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7460 ArrayRef<unsigned> Exclude = llvm::None) {
7461 std::string Values;
7462 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7463 unsigned Skipped = Exclude.size();
7464 auto S = Exclude.begin(), E = Exclude.end();
7465 for (unsigned i = First; i < Last; ++i) {
7466 if (std::find(S, E, i) != E) {
7467 --Skipped;
7468 continue;
7469 }
7470 Values += "'";
7471 Values += getOpenMPSimpleClauseTypeName(K, i);
7472 Values += "'";
7473 if (i == Bound - Skipped)
7474 Values += " or ";
7475 else if (i != Bound + 1 - Skipped)
7476 Values += ", ";
7477 }
7478 return Values;
7479}
7480
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007481OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7482 SourceLocation KindKwLoc,
7483 SourceLocation StartLoc,
7484 SourceLocation LParenLoc,
7485 SourceLocation EndLoc) {
7486 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007487 static_assert(OMPC_DEFAULT_unknown > 0,
7488 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007489 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007490 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7491 /*Last=*/OMPC_DEFAULT_unknown)
7492 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007493 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007494 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007495 switch (Kind) {
7496 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007497 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007498 break;
7499 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007500 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007501 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007502 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007503 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007504 break;
7505 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007506 return new (Context)
7507 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007508}
7509
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007510OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7511 SourceLocation KindKwLoc,
7512 SourceLocation StartLoc,
7513 SourceLocation LParenLoc,
7514 SourceLocation EndLoc) {
7515 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007516 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007517 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7518 /*Last=*/OMPC_PROC_BIND_unknown)
7519 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007520 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007521 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007522 return new (Context)
7523 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007524}
7525
Alexey Bataev56dafe82014-06-20 07:16:17 +00007526OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007527 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007528 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007529 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007530 SourceLocation EndLoc) {
7531 OMPClause *Res = nullptr;
7532 switch (Kind) {
7533 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007534 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7535 assert(Argument.size() == NumberOfElements &&
7536 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007537 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007538 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7539 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7540 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7541 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7542 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007543 break;
7544 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007545 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7546 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7547 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7548 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007549 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007550 case OMPC_dist_schedule:
7551 Res = ActOnOpenMPDistScheduleClause(
7552 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7553 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7554 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007555 case OMPC_defaultmap:
7556 enum { Modifier, DefaultmapKind };
7557 Res = ActOnOpenMPDefaultmapClause(
7558 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7559 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007560 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7561 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007562 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007563 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007564 case OMPC_num_threads:
7565 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007566 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007567 case OMPC_collapse:
7568 case OMPC_default:
7569 case OMPC_proc_bind:
7570 case OMPC_private:
7571 case OMPC_firstprivate:
7572 case OMPC_lastprivate:
7573 case OMPC_shared:
7574 case OMPC_reduction:
7575 case OMPC_linear:
7576 case OMPC_aligned:
7577 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007578 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007579 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007580 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007581 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007582 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007583 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007584 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007585 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007586 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007587 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007588 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007589 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007590 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007591 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007592 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007593 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007594 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007595 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007596 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007597 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007598 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007599 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007600 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007601 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007602 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007603 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007604 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007605 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007606 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007607 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007608 llvm_unreachable("Clause is not allowed.");
7609 }
7610 return Res;
7611}
7612
Alexey Bataev6402bca2015-12-28 07:25:51 +00007613static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7614 OpenMPScheduleClauseModifier M2,
7615 SourceLocation M1Loc, SourceLocation M2Loc) {
7616 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7617 SmallVector<unsigned, 2> Excluded;
7618 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7619 Excluded.push_back(M2);
7620 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7621 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7622 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7623 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7624 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7625 << getListOfPossibleValues(OMPC_schedule,
7626 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7627 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7628 Excluded)
7629 << getOpenMPClauseName(OMPC_schedule);
7630 return true;
7631 }
7632 return false;
7633}
7634
Alexey Bataev56dafe82014-06-20 07:16:17 +00007635OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007636 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007637 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007638 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7639 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7640 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7641 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7642 return nullptr;
7643 // OpenMP, 2.7.1, Loop Construct, Restrictions
7644 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7645 // but not both.
7646 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7647 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7648 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7649 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7650 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7651 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7652 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7653 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7654 return nullptr;
7655 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007656 if (Kind == OMPC_SCHEDULE_unknown) {
7657 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007658 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7659 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7660 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7661 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7662 Exclude);
7663 } else {
7664 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7665 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007666 }
7667 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7668 << Values << getOpenMPClauseName(OMPC_schedule);
7669 return nullptr;
7670 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007671 // OpenMP, 2.7.1, Loop Construct, Restrictions
7672 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7673 // schedule(guided).
7674 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7675 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7676 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7677 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7678 diag::err_omp_schedule_nonmonotonic_static);
7679 return nullptr;
7680 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007681 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007682 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007683 if (ChunkSize) {
7684 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7685 !ChunkSize->isInstantiationDependent() &&
7686 !ChunkSize->containsUnexpandedParameterPack()) {
7687 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7688 ExprResult Val =
7689 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7690 if (Val.isInvalid())
7691 return nullptr;
7692
7693 ValExpr = Val.get();
7694
7695 // OpenMP [2.7.1, Restrictions]
7696 // chunk_size must be a loop invariant integer expression with a positive
7697 // value.
7698 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007699 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7700 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7701 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007702 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007703 return nullptr;
7704 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007705 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7706 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007707 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7708 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7709 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007710 }
7711 }
7712 }
7713
Alexey Bataev6402bca2015-12-28 07:25:51 +00007714 return new (Context)
7715 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007716 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007717}
7718
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007719OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7720 SourceLocation StartLoc,
7721 SourceLocation EndLoc) {
7722 OMPClause *Res = nullptr;
7723 switch (Kind) {
7724 case OMPC_ordered:
7725 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7726 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007727 case OMPC_nowait:
7728 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7729 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007730 case OMPC_untied:
7731 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7732 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007733 case OMPC_mergeable:
7734 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7735 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007736 case OMPC_read:
7737 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7738 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007739 case OMPC_write:
7740 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7741 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007742 case OMPC_update:
7743 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7744 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007745 case OMPC_capture:
7746 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7747 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007748 case OMPC_seq_cst:
7749 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7750 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007751 case OMPC_threads:
7752 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7753 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007754 case OMPC_simd:
7755 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7756 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007757 case OMPC_nogroup:
7758 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7759 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007760 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007761 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007762 case OMPC_num_threads:
7763 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007764 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007765 case OMPC_collapse:
7766 case OMPC_schedule:
7767 case OMPC_private:
7768 case OMPC_firstprivate:
7769 case OMPC_lastprivate:
7770 case OMPC_shared:
7771 case OMPC_reduction:
7772 case OMPC_linear:
7773 case OMPC_aligned:
7774 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007775 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007776 case OMPC_default:
7777 case OMPC_proc_bind:
7778 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007779 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007780 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007781 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007782 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007783 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007784 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007785 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007786 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007787 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007788 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007789 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007790 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007791 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007792 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007793 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007794 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007795 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007796 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007797 llvm_unreachable("Clause is not allowed.");
7798 }
7799 return Res;
7800}
7801
Alexey Bataev236070f2014-06-20 11:19:47 +00007802OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7803 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007804 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007805 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7806}
7807
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007808OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7809 SourceLocation EndLoc) {
7810 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7811}
7812
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007813OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7814 SourceLocation EndLoc) {
7815 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7816}
7817
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007818OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7819 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007820 return new (Context) OMPReadClause(StartLoc, EndLoc);
7821}
7822
Alexey Bataevdea47612014-07-23 07:46:59 +00007823OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7824 SourceLocation EndLoc) {
7825 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7826}
7827
Alexey Bataev67a4f222014-07-23 10:25:33 +00007828OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7829 SourceLocation EndLoc) {
7830 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7831}
7832
Alexey Bataev459dec02014-07-24 06:46:57 +00007833OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7834 SourceLocation EndLoc) {
7835 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7836}
7837
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007838OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7839 SourceLocation EndLoc) {
7840 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7841}
7842
Alexey Bataev346265e2015-09-25 10:37:12 +00007843OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7844 SourceLocation EndLoc) {
7845 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7846}
7847
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007848OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7849 SourceLocation EndLoc) {
7850 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7851}
7852
Alexey Bataevb825de12015-12-07 10:51:44 +00007853OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7854 SourceLocation EndLoc) {
7855 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7856}
7857
Alexey Bataevc5e02582014-06-16 07:08:35 +00007858OMPClause *Sema::ActOnOpenMPVarListClause(
7859 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7860 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7861 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007862 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007863 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7864 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7865 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007866 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007867 switch (Kind) {
7868 case OMPC_private:
7869 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7870 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007871 case OMPC_firstprivate:
7872 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7873 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007874 case OMPC_lastprivate:
7875 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7876 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007877 case OMPC_shared:
7878 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7879 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007880 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007881 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7882 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007883 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007884 case OMPC_linear:
7885 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007886 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007887 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007888 case OMPC_aligned:
7889 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7890 ColonLoc, EndLoc);
7891 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007892 case OMPC_copyin:
7893 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7894 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007895 case OMPC_copyprivate:
7896 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7897 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007898 case OMPC_flush:
7899 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7900 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007901 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007902 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007903 StartLoc, LParenLoc, EndLoc);
7904 break;
7905 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007906 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7907 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7908 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007909 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007910 case OMPC_to:
7911 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7912 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007913 case OMPC_from:
7914 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7915 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007916 case OMPC_use_device_ptr:
7917 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7918 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007919 case OMPC_is_device_ptr:
7920 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7921 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007922 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007923 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007924 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007925 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007926 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007927 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007928 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007929 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007930 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007931 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007932 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007933 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007934 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007935 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007936 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007937 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007938 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007939 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007940 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007941 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007942 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007943 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007944 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007945 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007946 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007947 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007948 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007949 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007950 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007951 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007952 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007953 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007954 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007955 llvm_unreachable("Clause is not allowed.");
7956 }
7957 return Res;
7958}
7959
Alexey Bataev90c228f2016-02-08 09:29:13 +00007960ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007961 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007962 ExprResult Res = BuildDeclRefExpr(
7963 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7964 if (!Res.isUsable())
7965 return ExprError();
7966 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7967 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7968 if (!Res.isUsable())
7969 return ExprError();
7970 }
7971 if (VK != VK_LValue && Res.get()->isGLValue()) {
7972 Res = DefaultLvalueConversion(Res.get());
7973 if (!Res.isUsable())
7974 return ExprError();
7975 }
7976 return Res;
7977}
7978
Alexey Bataev60da77e2016-02-29 05:54:20 +00007979static std::pair<ValueDecl *, bool>
7980getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7981 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007982 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7983 RefExpr->containsUnexpandedParameterPack())
7984 return std::make_pair(nullptr, true);
7985
Alexey Bataevd985eda2016-02-10 11:29:16 +00007986 // OpenMP [3.1, C/C++]
7987 // A list item is a variable name.
7988 // OpenMP [2.9.3.3, Restrictions, p.1]
7989 // A variable that is part of another variable (as an array or
7990 // structure element) cannot appear in a private clause.
7991 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007992 enum {
7993 NoArrayExpr = -1,
7994 ArraySubscript = 0,
7995 OMPArraySection = 1
7996 } IsArrayExpr = NoArrayExpr;
7997 if (AllowArraySection) {
7998 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7999 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8000 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8001 Base = TempASE->getBase()->IgnoreParenImpCasts();
8002 RefExpr = Base;
8003 IsArrayExpr = ArraySubscript;
8004 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8005 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8006 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8007 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8008 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8009 Base = TempASE->getBase()->IgnoreParenImpCasts();
8010 RefExpr = Base;
8011 IsArrayExpr = OMPArraySection;
8012 }
8013 }
8014 ELoc = RefExpr->getExprLoc();
8015 ERange = RefExpr->getSourceRange();
8016 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008017 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8018 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8019 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8020 (S.getCurrentThisType().isNull() || !ME ||
8021 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8022 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008023 if (IsArrayExpr != NoArrayExpr)
8024 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8025 << ERange;
8026 else {
8027 S.Diag(ELoc,
8028 AllowArraySection
8029 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8030 : diag::err_omp_expected_var_name_member_expr)
8031 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8032 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008033 return std::make_pair(nullptr, false);
8034 }
8035 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
8036}
8037
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008038OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8039 SourceLocation StartLoc,
8040 SourceLocation LParenLoc,
8041 SourceLocation EndLoc) {
8042 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008043 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008044 for (auto &RefExpr : VarList) {
8045 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008046 SourceLocation ELoc;
8047 SourceRange ERange;
8048 Expr *SimpleRefExpr = RefExpr;
8049 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008050 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008051 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008052 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008053 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008054 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008055 ValueDecl *D = Res.first;
8056 if (!D)
8057 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008058
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008059 QualType Type = D->getType();
8060 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008061
8062 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8063 // A variable that appears in a private clause must not have an incomplete
8064 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008065 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008066 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008067 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008068
Alexey Bataev758e55e2013-09-06 18:03:48 +00008069 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8070 // in a Construct]
8071 // Variables with the predetermined data-sharing attributes may not be
8072 // listed in data-sharing attributes clauses, except for the cases
8073 // listed below. For these exceptions only, listing a predetermined
8074 // variable in a data-sharing attribute clause is allowed and overrides
8075 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008076 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008077 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008078 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8079 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008080 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008081 continue;
8082 }
8083
Kelvin Libf594a52016-12-17 05:48:59 +00008084 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008085 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008086 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008087 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008088 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8089 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008090 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008091 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008092 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008093 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008094 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008095 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008096 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008097 continue;
8098 }
8099
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008100 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8101 // A list item cannot appear in both a map clause and a data-sharing
8102 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008103 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008104 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008105 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008106 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008107 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008108 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008109 CurrDir == OMPD_target_parallel_for_simd ||
8110 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008111 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008112 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008113 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008114 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8115 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8116 ConflictKind = WhereFoundClauseKind;
8117 return true;
8118 })) {
8119 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008120 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008121 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008122 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008123 ReportOriginalDSA(*this, DSAStack, D, DVar);
8124 continue;
8125 }
8126 }
8127
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008128 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8129 // A variable of class type (or array thereof) that appears in a private
8130 // clause requires an accessible, unambiguous default constructor for the
8131 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008132 // Generate helper private variable and initialize it with the default
8133 // value. The address of the original variable is replaced by the address of
8134 // the new private variable in CodeGen. This new variable is not added to
8135 // IdResolver, so the code in the OpenMP region uses original variable for
8136 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008137 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008138 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8139 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008140 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008141 if (VDPrivate->isInvalidDecl())
8142 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008143 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008144 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008145
Alexey Bataev90c228f2016-02-08 09:29:13 +00008146 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008147 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008148 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008149 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008150 Vars.push_back((VD || CurContext->isDependentContext())
8151 ? RefExpr->IgnoreParens()
8152 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008153 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008154 }
8155
Alexey Bataeved09d242014-05-28 05:53:51 +00008156 if (Vars.empty())
8157 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008158
Alexey Bataev03b340a2014-10-21 03:16:40 +00008159 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8160 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008161}
8162
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008163namespace {
8164class DiagsUninitializedSeveretyRAII {
8165private:
8166 DiagnosticsEngine &Diags;
8167 SourceLocation SavedLoc;
8168 bool IsIgnored;
8169
8170public:
8171 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8172 bool IsIgnored)
8173 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8174 if (!IsIgnored) {
8175 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8176 /*Map*/ diag::Severity::Ignored, Loc);
8177 }
8178 }
8179 ~DiagsUninitializedSeveretyRAII() {
8180 if (!IsIgnored)
8181 Diags.popMappings(SavedLoc);
8182 }
8183};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008184}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008185
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008186OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8187 SourceLocation StartLoc,
8188 SourceLocation LParenLoc,
8189 SourceLocation EndLoc) {
8190 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008191 SmallVector<Expr *, 8> PrivateCopies;
8192 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008193 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008194 bool IsImplicitClause =
8195 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8196 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8197
Alexey Bataeved09d242014-05-28 05:53:51 +00008198 for (auto &RefExpr : VarList) {
8199 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008200 SourceLocation ELoc;
8201 SourceRange ERange;
8202 Expr *SimpleRefExpr = RefExpr;
8203 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008204 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008205 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008206 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008207 PrivateCopies.push_back(nullptr);
8208 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008209 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008210 ValueDecl *D = Res.first;
8211 if (!D)
8212 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008213
Alexey Bataev60da77e2016-02-29 05:54:20 +00008214 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008215 QualType Type = D->getType();
8216 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008217
8218 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8219 // A variable that appears in a private clause must not have an incomplete
8220 // type or a reference type.
8221 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008222 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008223 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008224 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008225
8226 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8227 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008228 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008229 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008230 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008231
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008232 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008233 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008234 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008235 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008236 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008237 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008238 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8239 // A list item that specifies a given variable may not appear in more
8240 // than one clause on the same directive, except that a variable may be
8241 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008242 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00008243 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008244 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008245 << getOpenMPClauseName(DVar.CKind)
8246 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008247 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008248 continue;
8249 }
8250
8251 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8252 // in a Construct]
8253 // Variables with the predetermined data-sharing attributes may not be
8254 // listed in data-sharing attributes clauses, except for the cases
8255 // listed below. For these exceptions only, listing a predetermined
8256 // variable in a data-sharing attribute clause is allowed and overrides
8257 // the variable's predetermined data-sharing attributes.
8258 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8259 // in a Construct, C/C++, p.2]
8260 // Variables with const-qualified type having no mutable member may be
8261 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008262 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008263 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8264 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008265 << getOpenMPClauseName(DVar.CKind)
8266 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008267 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008268 continue;
8269 }
8270
Alexey Bataevf29276e2014-06-18 04:14:57 +00008271 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008272 // OpenMP [2.9.3.4, Restrictions, p.2]
8273 // A list item that is private within a parallel region must not appear
8274 // in a firstprivate clause on a worksharing construct if any of the
8275 // worksharing regions arising from the worksharing construct ever bind
8276 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008277 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008278 !isOpenMPParallelDirective(CurrDir) &&
8279 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008280 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008281 if (DVar.CKind != OMPC_shared &&
8282 (isOpenMPParallelDirective(DVar.DKind) ||
8283 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008284 Diag(ELoc, diag::err_omp_required_access)
8285 << getOpenMPClauseName(OMPC_firstprivate)
8286 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008287 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008288 continue;
8289 }
8290 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008291 // OpenMP [2.9.3.4, Restrictions, p.3]
8292 // A list item that appears in a reduction clause of a parallel construct
8293 // must not appear in a firstprivate clause on a worksharing or task
8294 // construct if any of the worksharing or task regions arising from the
8295 // worksharing or task construct ever bind to any of the parallel regions
8296 // arising from the parallel construct.
8297 // OpenMP [2.9.3.4, Restrictions, p.4]
8298 // A list item that appears in a reduction clause in worksharing
8299 // construct must not appear in a firstprivate clause in a task construct
8300 // encountered during execution of any of the worksharing regions arising
8301 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008302 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008303 DVar = DSAStack->hasInnermostDSA(
8304 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8305 [](OpenMPDirectiveKind K) -> bool {
8306 return isOpenMPParallelDirective(K) ||
8307 isOpenMPWorksharingDirective(K);
8308 },
8309 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008310 if (DVar.CKind == OMPC_reduction &&
8311 (isOpenMPParallelDirective(DVar.DKind) ||
8312 isOpenMPWorksharingDirective(DVar.DKind))) {
8313 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8314 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008315 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008316 continue;
8317 }
8318 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008319
8320 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8321 // A list item that is private within a teams region must not appear in a
8322 // firstprivate clause on a distribute construct if any of the distribute
8323 // regions arising from the distribute construct ever bind to any of the
8324 // teams regions arising from the teams construct.
8325 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8326 // A list item that appears in a reduction clause of a teams construct
8327 // must not appear in a firstprivate clause on a distribute construct if
8328 // any of the distribute regions arising from the distribute construct
8329 // ever bind to any of the teams regions arising from the teams construct.
8330 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8331 // A list item may appear in a firstprivate or lastprivate clause but not
8332 // both.
8333 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008334 DVar = DSAStack->hasInnermostDSA(
8335 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8336 [](OpenMPDirectiveKind K) -> bool {
8337 return isOpenMPTeamsDirective(K);
8338 },
8339 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008340 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8341 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008342 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008343 continue;
8344 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008345 DVar = DSAStack->hasInnermostDSA(
8346 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8347 [](OpenMPDirectiveKind K) -> bool {
8348 return isOpenMPTeamsDirective(K);
8349 },
8350 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008351 if (DVar.CKind == OMPC_reduction &&
8352 isOpenMPTeamsDirective(DVar.DKind)) {
8353 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008354 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008355 continue;
8356 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008357 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008358 if (DVar.CKind == OMPC_lastprivate) {
8359 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008360 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008361 continue;
8362 }
8363 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008364 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8365 // A list item cannot appear in both a map clause and a data-sharing
8366 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008367 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008368 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008369 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008370 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008371 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008372 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008373 CurrDir == OMPD_target_parallel_for_simd ||
8374 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008375 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008376 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008377 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008378 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8379 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8380 ConflictKind = WhereFoundClauseKind;
8381 return true;
8382 })) {
8383 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008384 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008385 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008386 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8387 ReportOriginalDSA(*this, DSAStack, D, DVar);
8388 continue;
8389 }
8390 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008391 }
8392
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008393 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008394 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008395 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008396 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8397 << getOpenMPClauseName(OMPC_firstprivate) << Type
8398 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8399 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008400 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008401 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008402 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008403 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008404 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008405 continue;
8406 }
8407
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008408 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008409 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8410 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008411 // Generate helper private variable and initialize it with the value of the
8412 // original variable. The address of the original variable is replaced by
8413 // the address of the new private variable in the CodeGen. This new variable
8414 // is not added to IdResolver, so the code in the OpenMP region uses
8415 // original variable for proper diagnostics and variable capturing.
8416 Expr *VDInitRefExpr = nullptr;
8417 // For arrays generate initializer for single element and replace it by the
8418 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008419 if (Type->isArrayType()) {
8420 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008421 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008422 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008423 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008424 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008425 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008426 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008427 InitializedEntity Entity =
8428 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008429 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8430
8431 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8432 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8433 if (Result.isInvalid())
8434 VDPrivate->setInvalidDecl();
8435 else
8436 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008437 // Remove temp variable declaration.
8438 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008439 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008440 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8441 ".firstprivate.temp");
8442 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8443 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008444 AddInitializerToDecl(VDPrivate,
8445 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008446 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008447 }
8448 if (VDPrivate->isInvalidDecl()) {
8449 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008450 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008451 diag::note_omp_task_predetermined_firstprivate_here);
8452 }
8453 continue;
8454 }
8455 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008456 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008457 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8458 RefExpr->getExprLoc());
8459 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008460 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008461 if (TopDVar.CKind == OMPC_lastprivate)
8462 Ref = TopDVar.PrivateCopy;
8463 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008464 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008465 if (!IsOpenMPCapturedDecl(D))
8466 ExprCaptures.push_back(Ref->getDecl());
8467 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008468 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008469 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008470 Vars.push_back((VD || CurContext->isDependentContext())
8471 ? RefExpr->IgnoreParens()
8472 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008473 PrivateCopies.push_back(VDPrivateRefExpr);
8474 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008475 }
8476
Alexey Bataeved09d242014-05-28 05:53:51 +00008477 if (Vars.empty())
8478 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008479
8480 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008481 Vars, PrivateCopies, Inits,
8482 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008483}
8484
Alexander Musman1bb328c2014-06-04 13:06:39 +00008485OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8486 SourceLocation StartLoc,
8487 SourceLocation LParenLoc,
8488 SourceLocation EndLoc) {
8489 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008490 SmallVector<Expr *, 8> SrcExprs;
8491 SmallVector<Expr *, 8> DstExprs;
8492 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008493 SmallVector<Decl *, 4> ExprCaptures;
8494 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008495 for (auto &RefExpr : VarList) {
8496 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008497 SourceLocation ELoc;
8498 SourceRange ERange;
8499 Expr *SimpleRefExpr = RefExpr;
8500 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008501 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008502 // It will be analyzed later.
8503 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008504 SrcExprs.push_back(nullptr);
8505 DstExprs.push_back(nullptr);
8506 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008507 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008508 ValueDecl *D = Res.first;
8509 if (!D)
8510 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008511
Alexey Bataev74caaf22016-02-20 04:09:36 +00008512 QualType Type = D->getType();
8513 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008514
8515 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8516 // A variable that appears in a lastprivate clause must not have an
8517 // incomplete type or a reference type.
8518 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008519 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008520 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008521 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008522
8523 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8524 // in a Construct]
8525 // Variables with the predetermined data-sharing attributes may not be
8526 // listed in data-sharing attributes clauses, except for the cases
8527 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008528 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008529 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8530 DVar.CKind != OMPC_firstprivate &&
8531 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8532 Diag(ELoc, diag::err_omp_wrong_dsa)
8533 << getOpenMPClauseName(DVar.CKind)
8534 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008535 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008536 continue;
8537 }
8538
Alexey Bataevf29276e2014-06-18 04:14:57 +00008539 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8540 // OpenMP [2.14.3.5, Restrictions, p.2]
8541 // A list item that is private within a parallel region, or that appears in
8542 // the reduction clause of a parallel construct, must not appear in a
8543 // lastprivate clause on a worksharing construct if any of the corresponding
8544 // worksharing regions ever binds to any of the corresponding parallel
8545 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008546 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008547 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008548 !isOpenMPParallelDirective(CurrDir) &&
8549 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008550 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008551 if (DVar.CKind != OMPC_shared) {
8552 Diag(ELoc, diag::err_omp_required_access)
8553 << getOpenMPClauseName(OMPC_lastprivate)
8554 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008555 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008556 continue;
8557 }
8558 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008559
8560 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8561 // A list item may appear in a firstprivate or lastprivate clause but not
8562 // both.
8563 if (CurrDir == OMPD_distribute) {
8564 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8565 if (DVar.CKind == OMPC_firstprivate) {
8566 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8567 ReportOriginalDSA(*this, DSAStack, D, DVar);
8568 continue;
8569 }
8570 }
8571
Alexander Musman1bb328c2014-06-04 13:06:39 +00008572 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008573 // A variable of class type (or array thereof) that appears in a
8574 // lastprivate clause requires an accessible, unambiguous default
8575 // constructor for the class type, unless the list item is also specified
8576 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008577 // A variable of class type (or array thereof) that appears in a
8578 // lastprivate clause requires an accessible, unambiguous copy assignment
8579 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008580 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008581 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008582 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008583 D->hasAttrs() ? &D->getAttrs() : nullptr);
8584 auto *PseudoSrcExpr =
8585 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008586 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008587 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008588 D->hasAttrs() ? &D->getAttrs() : nullptr);
8589 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008590 // For arrays generate assignment operation for single element and replace
8591 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008592 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008593 PseudoDstExpr, PseudoSrcExpr);
8594 if (AssignmentOp.isInvalid())
8595 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008596 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008597 /*DiscardedValue=*/true);
8598 if (AssignmentOp.isInvalid())
8599 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008600
Alexey Bataev74caaf22016-02-20 04:09:36 +00008601 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008602 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008603 if (TopDVar.CKind == OMPC_firstprivate)
8604 Ref = TopDVar.PrivateCopy;
8605 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008606 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008607 if (!IsOpenMPCapturedDecl(D))
8608 ExprCaptures.push_back(Ref->getDecl());
8609 }
8610 if (TopDVar.CKind == OMPC_firstprivate ||
8611 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008612 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008613 ExprResult RefRes = DefaultLvalueConversion(Ref);
8614 if (!RefRes.isUsable())
8615 continue;
8616 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008617 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8618 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008619 if (!PostUpdateRes.isUsable())
8620 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008621 ExprPostUpdates.push_back(
8622 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008623 }
8624 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008625 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008626 Vars.push_back((VD || CurContext->isDependentContext())
8627 ? RefExpr->IgnoreParens()
8628 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008629 SrcExprs.push_back(PseudoSrcExpr);
8630 DstExprs.push_back(PseudoDstExpr);
8631 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008632 }
8633
8634 if (Vars.empty())
8635 return nullptr;
8636
8637 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008638 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008639 buildPreInits(Context, ExprCaptures),
8640 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008641}
8642
Alexey Bataev758e55e2013-09-06 18:03:48 +00008643OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8644 SourceLocation StartLoc,
8645 SourceLocation LParenLoc,
8646 SourceLocation EndLoc) {
8647 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008648 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008649 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008650 SourceLocation ELoc;
8651 SourceRange ERange;
8652 Expr *SimpleRefExpr = RefExpr;
8653 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008654 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008655 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008656 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008657 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008658 ValueDecl *D = Res.first;
8659 if (!D)
8660 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008661
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008662 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008663 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8664 // in a Construct]
8665 // Variables with the predetermined data-sharing attributes may not be
8666 // listed in data-sharing attributes clauses, except for the cases
8667 // listed below. For these exceptions only, listing a predetermined
8668 // variable in a data-sharing attribute clause is allowed and overrides
8669 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008670 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008671 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8672 DVar.RefExpr) {
8673 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8674 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008675 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008676 continue;
8677 }
8678
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008679 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008680 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008681 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008682 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008683 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8684 ? RefExpr->IgnoreParens()
8685 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008686 }
8687
Alexey Bataeved09d242014-05-28 05:53:51 +00008688 if (Vars.empty())
8689 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008690
8691 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8692}
8693
Alexey Bataevc5e02582014-06-16 07:08:35 +00008694namespace {
8695class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8696 DSAStackTy *Stack;
8697
8698public:
8699 bool VisitDeclRefExpr(DeclRefExpr *E) {
8700 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008701 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008702 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8703 return false;
8704 if (DVar.CKind != OMPC_unknown)
8705 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008706 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8707 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8708 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008709 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008710 return true;
8711 return false;
8712 }
8713 return false;
8714 }
8715 bool VisitStmt(Stmt *S) {
8716 for (auto Child : S->children()) {
8717 if (Child && Visit(Child))
8718 return true;
8719 }
8720 return false;
8721 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008722 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008723};
Alexey Bataev23b69422014-06-18 07:08:49 +00008724} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008725
Alexey Bataev60da77e2016-02-29 05:54:20 +00008726namespace {
8727// Transform MemberExpression for specified FieldDecl of current class to
8728// DeclRefExpr to specified OMPCapturedExprDecl.
8729class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8730 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8731 ValueDecl *Field;
8732 DeclRefExpr *CapturedExpr;
8733
8734public:
8735 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8736 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8737
8738 ExprResult TransformMemberExpr(MemberExpr *E) {
8739 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8740 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008741 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008742 return CapturedExpr;
8743 }
8744 return BaseTransform::TransformMemberExpr(E);
8745 }
8746 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8747};
8748} // namespace
8749
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008750template <typename T>
8751static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8752 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8753 for (auto &Set : Lookups) {
8754 for (auto *D : Set) {
8755 if (auto Res = Gen(cast<ValueDecl>(D)))
8756 return Res;
8757 }
8758 }
8759 return T();
8760}
8761
8762static ExprResult
8763buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8764 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8765 const DeclarationNameInfo &ReductionId, QualType Ty,
8766 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8767 if (ReductionIdScopeSpec.isInvalid())
8768 return ExprError();
8769 SmallVector<UnresolvedSet<8>, 4> Lookups;
8770 if (S) {
8771 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8772 Lookup.suppressDiagnostics();
8773 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8774 auto *D = Lookup.getRepresentativeDecl();
8775 do {
8776 S = S->getParent();
8777 } while (S && !S->isDeclScope(D));
8778 if (S)
8779 S = S->getParent();
8780 Lookups.push_back(UnresolvedSet<8>());
8781 Lookups.back().append(Lookup.begin(), Lookup.end());
8782 Lookup.clear();
8783 }
8784 } else if (auto *ULE =
8785 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8786 Lookups.push_back(UnresolvedSet<8>());
8787 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008788 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008789 if (D == PrevD)
8790 Lookups.push_back(UnresolvedSet<8>());
8791 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8792 Lookups.back().addDecl(DRD);
8793 PrevD = D;
8794 }
8795 }
8796 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8797 Ty->containsUnexpandedParameterPack() ||
8798 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8799 return !D->isInvalidDecl() &&
8800 (D->getType()->isDependentType() ||
8801 D->getType()->isInstantiationDependentType() ||
8802 D->getType()->containsUnexpandedParameterPack());
8803 })) {
8804 UnresolvedSet<8> ResSet;
8805 for (auto &Set : Lookups) {
8806 ResSet.append(Set.begin(), Set.end());
8807 // The last item marks the end of all declarations at the specified scope.
8808 ResSet.addDecl(Set[Set.size() - 1]);
8809 }
8810 return UnresolvedLookupExpr::Create(
8811 SemaRef.Context, /*NamingClass=*/nullptr,
8812 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8813 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8814 }
8815 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8816 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8817 if (!D->isInvalidDecl() &&
8818 SemaRef.Context.hasSameType(D->getType(), Ty))
8819 return D;
8820 return nullptr;
8821 }))
8822 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8823 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8824 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8825 if (!D->isInvalidDecl() &&
8826 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8827 !Ty.isMoreQualifiedThan(D->getType()))
8828 return D;
8829 return nullptr;
8830 })) {
8831 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8832 /*DetectVirtual=*/false);
8833 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8834 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8835 VD->getType().getUnqualifiedType()))) {
8836 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8837 /*DiagID=*/0) !=
8838 Sema::AR_inaccessible) {
8839 SemaRef.BuildBasePathArray(Paths, BasePath);
8840 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8841 }
8842 }
8843 }
8844 }
8845 if (ReductionIdScopeSpec.isSet()) {
8846 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8847 return ExprError();
8848 }
8849 return ExprEmpty();
8850}
8851
Alexey Bataevc5e02582014-06-16 07:08:35 +00008852OMPClause *Sema::ActOnOpenMPReductionClause(
8853 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8854 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008855 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8856 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008857 auto DN = ReductionId.getName();
8858 auto OOK = DN.getCXXOverloadedOperator();
8859 BinaryOperatorKind BOK = BO_Comma;
8860
8861 // OpenMP [2.14.3.6, reduction clause]
8862 // C
8863 // reduction-identifier is either an identifier or one of the following
8864 // operators: +, -, *, &, |, ^, && and ||
8865 // C++
8866 // reduction-identifier is either an id-expression or one of the following
8867 // operators: +, -, *, &, |, ^, && and ||
8868 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8869 switch (OOK) {
8870 case OO_Plus:
8871 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008872 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008873 break;
8874 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008875 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008876 break;
8877 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008878 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008879 break;
8880 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008881 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008882 break;
8883 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008884 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008885 break;
8886 case OO_AmpAmp:
8887 BOK = BO_LAnd;
8888 break;
8889 case OO_PipePipe:
8890 BOK = BO_LOr;
8891 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008892 case OO_New:
8893 case OO_Delete:
8894 case OO_Array_New:
8895 case OO_Array_Delete:
8896 case OO_Slash:
8897 case OO_Percent:
8898 case OO_Tilde:
8899 case OO_Exclaim:
8900 case OO_Equal:
8901 case OO_Less:
8902 case OO_Greater:
8903 case OO_LessEqual:
8904 case OO_GreaterEqual:
8905 case OO_PlusEqual:
8906 case OO_MinusEqual:
8907 case OO_StarEqual:
8908 case OO_SlashEqual:
8909 case OO_PercentEqual:
8910 case OO_CaretEqual:
8911 case OO_AmpEqual:
8912 case OO_PipeEqual:
8913 case OO_LessLess:
8914 case OO_GreaterGreater:
8915 case OO_LessLessEqual:
8916 case OO_GreaterGreaterEqual:
8917 case OO_EqualEqual:
8918 case OO_ExclaimEqual:
8919 case OO_PlusPlus:
8920 case OO_MinusMinus:
8921 case OO_Comma:
8922 case OO_ArrowStar:
8923 case OO_Arrow:
8924 case OO_Call:
8925 case OO_Subscript:
8926 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008927 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008928 case NUM_OVERLOADED_OPERATORS:
8929 llvm_unreachable("Unexpected reduction identifier");
8930 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008931 if (auto II = DN.getAsIdentifierInfo()) {
8932 if (II->isStr("max"))
8933 BOK = BO_GT;
8934 else if (II->isStr("min"))
8935 BOK = BO_LT;
8936 }
8937 break;
8938 }
8939 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008940 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008941 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008942 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008943
8944 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008945 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008946 SmallVector<Expr *, 8> LHSs;
8947 SmallVector<Expr *, 8> RHSs;
8948 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008949 SmallVector<Decl *, 4> ExprCaptures;
8950 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008951 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8952 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008953 for (auto RefExpr : VarList) {
8954 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008955 // OpenMP [2.1, C/C++]
8956 // A list item is a variable or array section, subject to the restrictions
8957 // specified in Section 2.4 on page 42 and in each of the sections
8958 // describing clauses and directives for which a list appears.
8959 // OpenMP [2.14.3.3, Restrictions, p.1]
8960 // A variable that is part of another variable (as an array or
8961 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008962 if (!FirstIter && IR != ER)
8963 ++IR;
8964 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008965 SourceLocation ELoc;
8966 SourceRange ERange;
8967 Expr *SimpleRefExpr = RefExpr;
8968 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8969 /*AllowArraySection=*/true);
8970 if (Res.second) {
8971 // It will be analyzed later.
8972 Vars.push_back(RefExpr);
8973 Privates.push_back(nullptr);
8974 LHSs.push_back(nullptr);
8975 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008976 // Try to find 'declare reduction' corresponding construct before using
8977 // builtin/overloaded operators.
8978 QualType Type = Context.DependentTy;
8979 CXXCastPath BasePath;
8980 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8981 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8982 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8983 if (CurContext->isDependentContext() &&
8984 (DeclareReductionRef.isUnset() ||
8985 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8986 ReductionOps.push_back(DeclareReductionRef.get());
8987 else
8988 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008989 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008990 ValueDecl *D = Res.first;
8991 if (!D)
8992 continue;
8993
Alexey Bataeva1764212015-09-30 09:22:36 +00008994 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008995 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8996 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8997 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008998 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008999 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009000 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9001 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9002 Type = ATy->getElementType();
9003 else
9004 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009005 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009006 } else
9007 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9008 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009009
Alexey Bataevc5e02582014-06-16 07:08:35 +00009010 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9011 // A variable that appears in a private clause must not have an incomplete
9012 // type or a reference type.
9013 if (RequireCompleteType(ELoc, Type,
9014 diag::err_omp_reduction_incomplete_type))
9015 continue;
9016 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009017 // A list item that appears in a reduction clause must not be
9018 // const-qualified.
9019 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009020 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009021 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009022 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009023 bool IsDecl = !VD ||
9024 VD->isThisDeclarationADefinition(Context) ==
9025 VarDecl::DeclarationOnly;
9026 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00009027 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009028 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009029 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009030 continue;
9031 }
9032 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9033 // If a list-item is a reference type then it must bind to the same object
9034 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009035 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009036 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009037 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009038 DSARefChecker Check(DSAStack);
9039 if (Check.Visit(VDDef->getInit())) {
9040 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
9041 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
9042 continue;
9043 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009044 }
9045 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009046
Alexey Bataevc5e02582014-06-16 07:08:35 +00009047 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9048 // in a Construct]
9049 // Variables with the predetermined data-sharing attributes may not be
9050 // listed in data-sharing attributes clauses, except for the cases
9051 // listed below. For these exceptions only, listing a predetermined
9052 // variable in a data-sharing attribute clause is allowed and overrides
9053 // the variable's predetermined data-sharing attributes.
9054 // OpenMP [2.14.3.6, Restrictions, p.3]
9055 // Any number of reduction clauses can be specified on the directive,
9056 // but a list item can appear only once in the reduction clauses for that
9057 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009058 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009059 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009060 if (DVar.CKind == OMPC_reduction) {
9061 Diag(ELoc, diag::err_omp_once_referenced)
9062 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009063 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009064 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009065 } else if (DVar.CKind != OMPC_unknown) {
9066 Diag(ELoc, diag::err_omp_wrong_dsa)
9067 << getOpenMPClauseName(DVar.CKind)
9068 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009069 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009070 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009071 }
9072
9073 // OpenMP [2.14.3.6, Restrictions, p.1]
9074 // A list item that appears in a reduction clause of a worksharing
9075 // construct must be shared in the parallel regions to which any of the
9076 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009077 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9078 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009079 !isOpenMPParallelDirective(CurrDir) &&
9080 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009081 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009082 if (DVar.CKind != OMPC_shared) {
9083 Diag(ELoc, diag::err_omp_required_access)
9084 << getOpenMPClauseName(OMPC_reduction)
9085 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009086 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009087 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009088 }
9089 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009090
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009091 // Try to find 'declare reduction' corresponding construct before using
9092 // builtin/overloaded operators.
9093 CXXCastPath BasePath;
9094 ExprResult DeclareReductionRef = buildDeclareReductionRef(
9095 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
9096 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9097 if (DeclareReductionRef.isInvalid())
9098 continue;
9099 if (CurContext->isDependentContext() &&
9100 (DeclareReductionRef.isUnset() ||
9101 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
9102 Vars.push_back(RefExpr);
9103 Privates.push_back(nullptr);
9104 LHSs.push_back(nullptr);
9105 RHSs.push_back(nullptr);
9106 ReductionOps.push_back(DeclareReductionRef.get());
9107 continue;
9108 }
9109 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9110 // Not allowed reduction identifier is found.
9111 Diag(ReductionId.getLocStart(),
9112 diag::err_omp_unknown_reduction_identifier)
9113 << Type << ReductionIdRange;
9114 continue;
9115 }
9116
9117 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9118 // The type of a list item that appears in a reduction clause must be valid
9119 // for the reduction-identifier. For a max or min reduction in C, the type
9120 // of the list item must be an allowed arithmetic data type: char, int,
9121 // float, double, or _Bool, possibly modified with long, short, signed, or
9122 // unsigned. For a max or min reduction in C++, the type of the list item
9123 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9124 // double, or bool, possibly modified with long, short, signed, or unsigned.
9125 if (DeclareReductionRef.isUnset()) {
9126 if ((BOK == BO_GT || BOK == BO_LT) &&
9127 !(Type->isScalarType() ||
9128 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9129 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
9130 << getLangOpts().CPlusPlus;
9131 if (!ASE && !OASE) {
9132 bool IsDecl = !VD ||
9133 VD->isThisDeclarationADefinition(Context) ==
9134 VarDecl::DeclarationOnly;
9135 Diag(D->getLocation(),
9136 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9137 << D;
9138 }
9139 continue;
9140 }
9141 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
9142 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
9143 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
9144 if (!ASE && !OASE) {
9145 bool IsDecl = !VD ||
9146 VD->isThisDeclarationADefinition(Context) ==
9147 VarDecl::DeclarationOnly;
9148 Diag(D->getLocation(),
9149 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9150 << D;
9151 }
9152 continue;
9153 }
9154 }
9155
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009156 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009157 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009158 D->hasAttrs() ? &D->getAttrs() : nullptr);
9159 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9160 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009161 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009162 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009163 (!ASE &&
9164 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009165 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009166 // Create pseudo array type for private copy. The size for this array will
9167 // be generated during codegen.
9168 // For array subscripts or single variables Private Ty is the same as Type
9169 // (type of the variable or single array element).
9170 PrivateTy = Context.getVariableArrayType(
9171 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9172 Context.getSizeType(), VK_RValue),
9173 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009174 } else if (!ASE && !OASE &&
9175 Context.getAsArrayType(D->getType().getNonReferenceType()))
9176 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009177 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009178 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9179 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009180 // Add initializer for private variable.
9181 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009182 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9183 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9184 if (DeclareReductionRef.isUsable()) {
9185 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9186 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9187 if (DRD->getInitializer()) {
9188 Init = DRDRef;
9189 RHSVD->setInit(DRDRef);
9190 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009191 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009192 } else {
9193 switch (BOK) {
9194 case BO_Add:
9195 case BO_Xor:
9196 case BO_Or:
9197 case BO_LOr:
9198 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9199 if (Type->isScalarType() || Type->isAnyComplexType())
9200 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9201 break;
9202 case BO_Mul:
9203 case BO_LAnd:
9204 if (Type->isScalarType() || Type->isAnyComplexType()) {
9205 // '*' and '&&' reduction ops - initializer is '1'.
9206 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009207 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009208 break;
9209 case BO_And: {
9210 // '&' reduction op - initializer is '~0'.
9211 QualType OrigType = Type;
9212 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9213 Type = ComplexTy->getElementType();
9214 if (Type->isRealFloatingType()) {
9215 llvm::APFloat InitValue =
9216 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9217 /*isIEEE=*/true);
9218 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9219 Type, ELoc);
9220 } else if (Type->isScalarType()) {
9221 auto Size = Context.getTypeSize(Type);
9222 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9223 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9224 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9225 }
9226 if (Init && OrigType->isAnyComplexType()) {
9227 // Init = 0xFFFF + 0xFFFFi;
9228 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9229 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9230 }
9231 Type = OrigType;
9232 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009233 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009234 case BO_LT:
9235 case BO_GT: {
9236 // 'min' reduction op - initializer is 'Largest representable number in
9237 // the reduction list item type'.
9238 // 'max' reduction op - initializer is 'Least representable number in
9239 // the reduction list item type'.
9240 if (Type->isIntegerType() || Type->isPointerType()) {
9241 bool IsSigned = Type->hasSignedIntegerRepresentation();
9242 auto Size = Context.getTypeSize(Type);
9243 QualType IntTy =
9244 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9245 llvm::APInt InitValue =
9246 (BOK != BO_LT)
9247 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9248 : llvm::APInt::getMinValue(Size)
9249 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9250 : llvm::APInt::getMaxValue(Size);
9251 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9252 if (Type->isPointerType()) {
9253 // Cast to pointer type.
9254 auto CastExpr = BuildCStyleCastExpr(
9255 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9256 SourceLocation(), Init);
9257 if (CastExpr.isInvalid())
9258 continue;
9259 Init = CastExpr.get();
9260 }
9261 } else if (Type->isRealFloatingType()) {
9262 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9263 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9264 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9265 Type, ELoc);
9266 }
9267 break;
9268 }
9269 case BO_PtrMemD:
9270 case BO_PtrMemI:
9271 case BO_MulAssign:
9272 case BO_Div:
9273 case BO_Rem:
9274 case BO_Sub:
9275 case BO_Shl:
9276 case BO_Shr:
9277 case BO_LE:
9278 case BO_GE:
9279 case BO_EQ:
9280 case BO_NE:
9281 case BO_AndAssign:
9282 case BO_XorAssign:
9283 case BO_OrAssign:
9284 case BO_Assign:
9285 case BO_AddAssign:
9286 case BO_SubAssign:
9287 case BO_DivAssign:
9288 case BO_RemAssign:
9289 case BO_ShlAssign:
9290 case BO_ShrAssign:
9291 case BO_Comma:
9292 llvm_unreachable("Unexpected reduction operation");
9293 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009294 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009295 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009296 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009297 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009298 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009299 if (RHSVD->isInvalidDecl())
9300 continue;
9301 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009302 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9303 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009304 bool IsDecl =
9305 !VD ||
9306 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9307 Diag(D->getLocation(),
9308 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9309 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009310 continue;
9311 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009312 // Store initializer for single element in private copy. Will be used during
9313 // codegen.
9314 PrivateVD->setInit(RHSVD->getInit());
9315 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009316 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009317 ExprResult ReductionOp;
9318 if (DeclareReductionRef.isUsable()) {
9319 QualType RedTy = DeclareReductionRef.get()->getType();
9320 QualType PtrRedTy = Context.getPointerType(RedTy);
9321 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9322 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9323 if (!BasePath.empty()) {
9324 LHS = DefaultLvalueConversion(LHS.get());
9325 RHS = DefaultLvalueConversion(RHS.get());
9326 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9327 CK_UncheckedDerivedToBase, LHS.get(),
9328 &BasePath, LHS.get()->getValueKind());
9329 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9330 CK_UncheckedDerivedToBase, RHS.get(),
9331 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009332 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009333 FunctionProtoType::ExtProtoInfo EPI;
9334 QualType Params[] = {PtrRedTy, PtrRedTy};
9335 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9336 auto *OVE = new (Context) OpaqueValueExpr(
9337 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9338 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9339 Expr *Args[] = {LHS.get(), RHS.get()};
9340 ReductionOp = new (Context)
9341 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9342 } else {
9343 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9344 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9345 if (ReductionOp.isUsable()) {
9346 if (BOK != BO_LT && BOK != BO_GT) {
9347 ReductionOp =
9348 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9349 BO_Assign, LHSDRE, ReductionOp.get());
9350 } else {
9351 auto *ConditionalOp = new (Context) ConditionalOperator(
9352 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9353 RHSDRE, Type, VK_LValue, OK_Ordinary);
9354 ReductionOp =
9355 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9356 BO_Assign, LHSDRE, ConditionalOp);
9357 }
9358 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9359 }
9360 if (ReductionOp.isInvalid())
9361 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009362 }
9363
Alexey Bataev60da77e2016-02-29 05:54:20 +00009364 DeclRefExpr *Ref = nullptr;
9365 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009366 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009367 if (ASE || OASE) {
9368 TransformExprToCaptures RebuildToCapture(*this, D);
9369 VarsExpr =
9370 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9371 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009372 } else {
9373 VarsExpr = Ref =
9374 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009375 }
9376 if (!IsOpenMPCapturedDecl(D)) {
9377 ExprCaptures.push_back(Ref->getDecl());
9378 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9379 ExprResult RefRes = DefaultLvalueConversion(Ref);
9380 if (!RefRes.isUsable())
9381 continue;
9382 ExprResult PostUpdateRes =
9383 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9384 SimpleRefExpr, RefRes.get());
9385 if (!PostUpdateRes.isUsable())
9386 continue;
9387 ExprPostUpdates.push_back(
9388 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009389 }
9390 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009391 }
9392 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9393 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009394 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009395 LHSs.push_back(LHSDRE);
9396 RHSs.push_back(RHSDRE);
9397 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009398 }
9399
9400 if (Vars.empty())
9401 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009402
Alexey Bataevc5e02582014-06-16 07:08:35 +00009403 return OMPReductionClause::Create(
9404 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009405 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009406 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9407 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009408}
9409
Alexey Bataevecba70f2016-04-12 11:02:11 +00009410bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9411 SourceLocation LinLoc) {
9412 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9413 LinKind == OMPC_LINEAR_unknown) {
9414 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9415 return true;
9416 }
9417 return false;
9418}
9419
9420bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9421 OpenMPLinearClauseKind LinKind,
9422 QualType Type) {
9423 auto *VD = dyn_cast_or_null<VarDecl>(D);
9424 // A variable must not have an incomplete type or a reference type.
9425 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9426 return true;
9427 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9428 !Type->isReferenceType()) {
9429 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9430 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9431 return true;
9432 }
9433 Type = Type.getNonReferenceType();
9434
9435 // A list item must not be const-qualified.
9436 if (Type.isConstant(Context)) {
9437 Diag(ELoc, diag::err_omp_const_variable)
9438 << getOpenMPClauseName(OMPC_linear);
9439 if (D) {
9440 bool IsDecl =
9441 !VD ||
9442 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9443 Diag(D->getLocation(),
9444 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9445 << D;
9446 }
9447 return true;
9448 }
9449
9450 // A list item must be of integral or pointer type.
9451 Type = Type.getUnqualifiedType().getCanonicalType();
9452 const auto *Ty = Type.getTypePtrOrNull();
9453 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9454 !Ty->isPointerType())) {
9455 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9456 if (D) {
9457 bool IsDecl =
9458 !VD ||
9459 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9460 Diag(D->getLocation(),
9461 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9462 << D;
9463 }
9464 return true;
9465 }
9466 return false;
9467}
9468
Alexey Bataev182227b2015-08-20 10:54:39 +00009469OMPClause *Sema::ActOnOpenMPLinearClause(
9470 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9471 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9472 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009473 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009474 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009475 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009476 SmallVector<Decl *, 4> ExprCaptures;
9477 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009478 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009479 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009480 for (auto &RefExpr : VarList) {
9481 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009482 SourceLocation ELoc;
9483 SourceRange ERange;
9484 Expr *SimpleRefExpr = RefExpr;
9485 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9486 /*AllowArraySection=*/false);
9487 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009488 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009489 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009490 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009491 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009492 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009493 ValueDecl *D = Res.first;
9494 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009495 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009496
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009497 QualType Type = D->getType();
9498 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009499
9500 // OpenMP [2.14.3.7, linear clause]
9501 // A list-item cannot appear in more than one linear clause.
9502 // A list-item that appears in a linear clause cannot appear in any
9503 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009504 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009505 if (DVar.RefExpr) {
9506 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9507 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009508 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009509 continue;
9510 }
9511
Alexey Bataevecba70f2016-04-12 11:02:11 +00009512 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009513 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009514 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009515
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009516 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009517 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9518 D->hasAttrs() ? &D->getAttrs() : nullptr);
9519 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009520 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009521 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009522 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009523 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009524 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009525 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9526 if (!IsOpenMPCapturedDecl(D)) {
9527 ExprCaptures.push_back(Ref->getDecl());
9528 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9529 ExprResult RefRes = DefaultLvalueConversion(Ref);
9530 if (!RefRes.isUsable())
9531 continue;
9532 ExprResult PostUpdateRes =
9533 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9534 SimpleRefExpr, RefRes.get());
9535 if (!PostUpdateRes.isUsable())
9536 continue;
9537 ExprPostUpdates.push_back(
9538 IgnoredValueConversions(PostUpdateRes.get()).get());
9539 }
9540 }
9541 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009542 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009543 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009544 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009545 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009546 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009547 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009548 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9549
9550 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009551 Vars.push_back((VD || CurContext->isDependentContext())
9552 ? RefExpr->IgnoreParens()
9553 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009554 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009555 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009556 }
9557
9558 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009559 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009560
9561 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009562 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009563 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9564 !Step->isInstantiationDependent() &&
9565 !Step->containsUnexpandedParameterPack()) {
9566 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009567 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009568 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009569 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009570 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009571
Alexander Musman3276a272015-03-21 10:12:56 +00009572 // Build var to save the step value.
9573 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009574 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009575 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009576 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009577 ExprResult CalcStep =
9578 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009579 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009580
Alexander Musman8dba6642014-04-22 13:09:42 +00009581 // Warn about zero linear step (it would be probably better specified as
9582 // making corresponding variables 'const').
9583 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009584 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9585 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009586 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9587 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009588 if (!IsConstant && CalcStep.isUsable()) {
9589 // Calculate the step beforehand instead of doing this on each iteration.
9590 // (This is not used if the number of iterations may be kfold-ed).
9591 CalcStepExpr = CalcStep.get();
9592 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009593 }
9594
Alexey Bataev182227b2015-08-20 10:54:39 +00009595 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9596 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009597 StepExpr, CalcStepExpr,
9598 buildPreInits(Context, ExprCaptures),
9599 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009600}
9601
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009602static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9603 Expr *NumIterations, Sema &SemaRef,
9604 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009605 // Walk the vars and build update/final expressions for the CodeGen.
9606 SmallVector<Expr *, 8> Updates;
9607 SmallVector<Expr *, 8> Finals;
9608 Expr *Step = Clause.getStep();
9609 Expr *CalcStep = Clause.getCalcStep();
9610 // OpenMP [2.14.3.7, linear clause]
9611 // If linear-step is not specified it is assumed to be 1.
9612 if (Step == nullptr)
9613 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009614 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009615 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009616 }
Alexander Musman3276a272015-03-21 10:12:56 +00009617 bool HasErrors = false;
9618 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009619 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009620 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009621 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009622 SourceLocation ELoc;
9623 SourceRange ERange;
9624 Expr *SimpleRefExpr = RefExpr;
9625 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9626 /*AllowArraySection=*/false);
9627 ValueDecl *D = Res.first;
9628 if (Res.second || !D) {
9629 Updates.push_back(nullptr);
9630 Finals.push_back(nullptr);
9631 HasErrors = true;
9632 continue;
9633 }
9634 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9635 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9636 ->getMemberDecl();
9637 }
9638 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009639 Expr *InitExpr = *CurInit;
9640
9641 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009642 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009643 Expr *CapturedRef;
9644 if (LinKind == OMPC_LINEAR_uval)
9645 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9646 else
9647 CapturedRef =
9648 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9649 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9650 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009651
9652 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009653 ExprResult Update;
9654 if (!Info.first) {
9655 Update =
9656 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9657 InitExpr, IV, Step, /* Subtract */ false);
9658 } else
9659 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009660 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9661 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009662
9663 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009664 ExprResult Final;
9665 if (!Info.first) {
9666 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9667 InitExpr, NumIterations, Step,
9668 /* Subtract */ false);
9669 } else
9670 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009671 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9672 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009673
Alexander Musman3276a272015-03-21 10:12:56 +00009674 if (!Update.isUsable() || !Final.isUsable()) {
9675 Updates.push_back(nullptr);
9676 Finals.push_back(nullptr);
9677 HasErrors = true;
9678 } else {
9679 Updates.push_back(Update.get());
9680 Finals.push_back(Final.get());
9681 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009682 ++CurInit;
9683 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009684 }
9685 Clause.setUpdates(Updates);
9686 Clause.setFinals(Finals);
9687 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009688}
9689
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009690OMPClause *Sema::ActOnOpenMPAlignedClause(
9691 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9692 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9693
9694 SmallVector<Expr *, 8> Vars;
9695 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009696 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9697 SourceLocation ELoc;
9698 SourceRange ERange;
9699 Expr *SimpleRefExpr = RefExpr;
9700 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9701 /*AllowArraySection=*/false);
9702 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009703 // It will be analyzed later.
9704 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009705 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009706 ValueDecl *D = Res.first;
9707 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009708 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009709
Alexey Bataev1efd1662016-03-29 10:59:56 +00009710 QualType QType = D->getType();
9711 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009712
9713 // OpenMP [2.8.1, simd construct, Restrictions]
9714 // The type of list items appearing in the aligned clause must be
9715 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009716 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009717 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009718 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009719 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009720 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009721 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009722 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009723 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009724 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009725 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009726 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009727 continue;
9728 }
9729
9730 // OpenMP [2.8.1, simd construct, Restrictions]
9731 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009732 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009733 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009734 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9735 << getOpenMPClauseName(OMPC_aligned);
9736 continue;
9737 }
9738
Alexey Bataev1efd1662016-03-29 10:59:56 +00009739 DeclRefExpr *Ref = nullptr;
9740 if (!VD && IsOpenMPCapturedDecl(D))
9741 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9742 Vars.push_back(DefaultFunctionArrayConversion(
9743 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9744 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009745 }
9746
9747 // OpenMP [2.8.1, simd construct, Description]
9748 // The parameter of the aligned clause, alignment, must be a constant
9749 // positive integer expression.
9750 // If no optional parameter is specified, implementation-defined default
9751 // alignments for SIMD instructions on the target platforms are assumed.
9752 if (Alignment != nullptr) {
9753 ExprResult AlignResult =
9754 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9755 if (AlignResult.isInvalid())
9756 return nullptr;
9757 Alignment = AlignResult.get();
9758 }
9759 if (Vars.empty())
9760 return nullptr;
9761
9762 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9763 EndLoc, Vars, Alignment);
9764}
9765
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009766OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9767 SourceLocation StartLoc,
9768 SourceLocation LParenLoc,
9769 SourceLocation EndLoc) {
9770 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009771 SmallVector<Expr *, 8> SrcExprs;
9772 SmallVector<Expr *, 8> DstExprs;
9773 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009774 for (auto &RefExpr : VarList) {
9775 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9776 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009777 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009778 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009779 SrcExprs.push_back(nullptr);
9780 DstExprs.push_back(nullptr);
9781 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009782 continue;
9783 }
9784
Alexey Bataeved09d242014-05-28 05:53:51 +00009785 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009786 // OpenMP [2.1, C/C++]
9787 // A list item is a variable name.
9788 // OpenMP [2.14.4.1, Restrictions, p.1]
9789 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009790 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009791 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009792 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9793 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009794 continue;
9795 }
9796
9797 Decl *D = DE->getDecl();
9798 VarDecl *VD = cast<VarDecl>(D);
9799
9800 QualType Type = VD->getType();
9801 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9802 // It will be analyzed later.
9803 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009804 SrcExprs.push_back(nullptr);
9805 DstExprs.push_back(nullptr);
9806 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009807 continue;
9808 }
9809
9810 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9811 // A list item that appears in a copyin clause must be threadprivate.
9812 if (!DSAStack->isThreadPrivate(VD)) {
9813 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009814 << getOpenMPClauseName(OMPC_copyin)
9815 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009816 continue;
9817 }
9818
9819 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9820 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009821 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009822 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009823 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009824 auto *SrcVD =
9825 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9826 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009827 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009828 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9829 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009830 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9831 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009832 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009833 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009834 // For arrays generate assignment operation for single element and replace
9835 // it by the original array element in CodeGen.
9836 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9837 PseudoDstExpr, PseudoSrcExpr);
9838 if (AssignmentOp.isInvalid())
9839 continue;
9840 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9841 /*DiscardedValue=*/true);
9842 if (AssignmentOp.isInvalid())
9843 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009844
9845 DSAStack->addDSA(VD, DE, OMPC_copyin);
9846 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009847 SrcExprs.push_back(PseudoSrcExpr);
9848 DstExprs.push_back(PseudoDstExpr);
9849 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009850 }
9851
Alexey Bataeved09d242014-05-28 05:53:51 +00009852 if (Vars.empty())
9853 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009854
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009855 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9856 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009857}
9858
Alexey Bataevbae9a792014-06-27 10:37:06 +00009859OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9860 SourceLocation StartLoc,
9861 SourceLocation LParenLoc,
9862 SourceLocation EndLoc) {
9863 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009864 SmallVector<Expr *, 8> SrcExprs;
9865 SmallVector<Expr *, 8> DstExprs;
9866 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009867 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009868 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9869 SourceLocation ELoc;
9870 SourceRange ERange;
9871 Expr *SimpleRefExpr = RefExpr;
9872 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9873 /*AllowArraySection=*/false);
9874 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009875 // It will be analyzed later.
9876 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009877 SrcExprs.push_back(nullptr);
9878 DstExprs.push_back(nullptr);
9879 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009880 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009881 ValueDecl *D = Res.first;
9882 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009883 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009884
Alexey Bataeve122da12016-03-17 10:50:17 +00009885 QualType Type = D->getType();
9886 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009887
9888 // OpenMP [2.14.4.2, Restrictions, p.2]
9889 // A list item that appears in a copyprivate clause may not appear in a
9890 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009891 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9892 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009893 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9894 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009895 Diag(ELoc, diag::err_omp_wrong_dsa)
9896 << getOpenMPClauseName(DVar.CKind)
9897 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009898 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009899 continue;
9900 }
9901
9902 // OpenMP [2.11.4.2, Restrictions, p.1]
9903 // All list items that appear in a copyprivate clause must be either
9904 // threadprivate or private in the enclosing context.
9905 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009906 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009907 if (DVar.CKind == OMPC_shared) {
9908 Diag(ELoc, diag::err_omp_required_access)
9909 << getOpenMPClauseName(OMPC_copyprivate)
9910 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009911 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009912 continue;
9913 }
9914 }
9915 }
9916
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009917 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009918 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009919 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009920 << getOpenMPClauseName(OMPC_copyprivate) << Type
9921 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009922 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009923 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009924 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009925 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009926 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009927 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009928 continue;
9929 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009930
Alexey Bataevbae9a792014-06-27 10:37:06 +00009931 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9932 // A variable of class type (or array thereof) that appears in a
9933 // copyin clause requires an accessible, unambiguous copy assignment
9934 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009935 Type = Context.getBaseElementType(Type.getNonReferenceType())
9936 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009937 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009938 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9939 D->hasAttrs() ? &D->getAttrs() : nullptr);
9940 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009941 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009942 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9943 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009944 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009945 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009946 PseudoDstExpr, PseudoSrcExpr);
9947 if (AssignmentOp.isInvalid())
9948 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009949 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009950 /*DiscardedValue=*/true);
9951 if (AssignmentOp.isInvalid())
9952 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009953
9954 // No need to mark vars as copyprivate, they are already threadprivate or
9955 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009956 assert(VD || IsOpenMPCapturedDecl(D));
9957 Vars.push_back(
9958 VD ? RefExpr->IgnoreParens()
9959 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009960 SrcExprs.push_back(PseudoSrcExpr);
9961 DstExprs.push_back(PseudoDstExpr);
9962 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009963 }
9964
9965 if (Vars.empty())
9966 return nullptr;
9967
Alexey Bataeva63048e2015-03-23 06:18:07 +00009968 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9969 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009970}
9971
Alexey Bataev6125da92014-07-21 11:26:11 +00009972OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9973 SourceLocation StartLoc,
9974 SourceLocation LParenLoc,
9975 SourceLocation EndLoc) {
9976 if (VarList.empty())
9977 return nullptr;
9978
9979 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9980}
Alexey Bataevdea47612014-07-23 07:46:59 +00009981
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009982OMPClause *
9983Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9984 SourceLocation DepLoc, SourceLocation ColonLoc,
9985 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9986 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009987 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009988 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009989 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009990 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009991 return nullptr;
9992 }
9993 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009994 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9995 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009996 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009997 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009998 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9999 /*Last=*/OMPC_DEPEND_unknown, Except)
10000 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010001 return nullptr;
10002 }
10003 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010004 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010005 llvm::APSInt DepCounter(/*BitWidth=*/32);
10006 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10007 if (DepKind == OMPC_DEPEND_sink) {
10008 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10009 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10010 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010011 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010012 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010013 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10014 DSAStack->getParentOrderedRegionParam()) {
10015 for (auto &RefExpr : VarList) {
10016 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010017 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010018 // It will be analyzed later.
10019 Vars.push_back(RefExpr);
10020 continue;
10021 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010022
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010023 SourceLocation ELoc = RefExpr->getExprLoc();
10024 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10025 if (DepKind == OMPC_DEPEND_sink) {
10026 if (DepCounter >= TotalDepCount) {
10027 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10028 continue;
10029 }
10030 ++DepCounter;
10031 // OpenMP [2.13.9, Summary]
10032 // depend(dependence-type : vec), where dependence-type is:
10033 // 'sink' and where vec is the iteration vector, which has the form:
10034 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10035 // where n is the value specified by the ordered clause in the loop
10036 // directive, xi denotes the loop iteration variable of the i-th nested
10037 // loop associated with the loop directive, and di is a constant
10038 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010039 if (CurContext->isDependentContext()) {
10040 // It will be analyzed later.
10041 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010042 continue;
10043 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010044 SimpleExpr = SimpleExpr->IgnoreImplicit();
10045 OverloadedOperatorKind OOK = OO_None;
10046 SourceLocation OOLoc;
10047 Expr *LHS = SimpleExpr;
10048 Expr *RHS = nullptr;
10049 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10050 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10051 OOLoc = BO->getOperatorLoc();
10052 LHS = BO->getLHS()->IgnoreParenImpCasts();
10053 RHS = BO->getRHS()->IgnoreParenImpCasts();
10054 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10055 OOK = OCE->getOperator();
10056 OOLoc = OCE->getOperatorLoc();
10057 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10058 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10059 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10060 OOK = MCE->getMethodDecl()
10061 ->getNameInfo()
10062 .getName()
10063 .getCXXOverloadedOperator();
10064 OOLoc = MCE->getCallee()->getExprLoc();
10065 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10066 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10067 }
10068 SourceLocation ELoc;
10069 SourceRange ERange;
10070 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10071 /*AllowArraySection=*/false);
10072 if (Res.second) {
10073 // It will be analyzed later.
10074 Vars.push_back(RefExpr);
10075 }
10076 ValueDecl *D = Res.first;
10077 if (!D)
10078 continue;
10079
10080 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10081 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10082 continue;
10083 }
10084 if (RHS) {
10085 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10086 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10087 if (RHSRes.isInvalid())
10088 continue;
10089 }
10090 if (!CurContext->isDependentContext() &&
10091 DSAStack->getParentOrderedRegionParam() &&
10092 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10093 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10094 << DSAStack->getParentLoopControlVariable(
10095 DepCounter.getZExtValue());
10096 continue;
10097 }
10098 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010099 } else {
10100 // OpenMP [2.11.1.1, Restrictions, p.3]
10101 // A variable that is part of another variable (such as a field of a
10102 // structure) but is not an array element or an array section cannot
10103 // appear in a depend clause.
10104 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10105 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10106 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10107 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10108 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010109 (ASE &&
10110 !ASE->getBase()
10111 ->getType()
10112 .getNonReferenceType()
10113 ->isPointerType() &&
10114 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010115 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10116 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010117 continue;
10118 }
10119 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010120 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10121 }
10122
10123 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10124 TotalDepCount > VarList.size() &&
10125 DSAStack->getParentOrderedRegionParam()) {
10126 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10127 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10128 }
10129 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10130 Vars.empty())
10131 return nullptr;
10132 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010133 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10134 DepKind, DepLoc, ColonLoc, Vars);
10135 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10136 DSAStack->addDoacrossDependClause(C, OpsOffs);
10137 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010138}
Michael Wonge710d542015-08-07 16:16:36 +000010139
10140OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10141 SourceLocation LParenLoc,
10142 SourceLocation EndLoc) {
10143 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010144
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010145 // OpenMP [2.9.1, Restrictions]
10146 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010147 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10148 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010149 return nullptr;
10150
Michael Wonge710d542015-08-07 16:16:36 +000010151 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10152}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010153
10154static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10155 DSAStackTy *Stack, CXXRecordDecl *RD) {
10156 if (!RD || RD->isInvalidDecl())
10157 return true;
10158
10159 auto QTy = SemaRef.Context.getRecordType(RD);
10160 if (RD->isDynamicClass()) {
10161 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10162 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10163 return false;
10164 }
10165 auto *DC = RD;
10166 bool IsCorrect = true;
10167 for (auto *I : DC->decls()) {
10168 if (I) {
10169 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10170 if (MD->isStatic()) {
10171 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10172 SemaRef.Diag(MD->getLocation(),
10173 diag::note_omp_static_member_in_target);
10174 IsCorrect = false;
10175 }
10176 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10177 if (VD->isStaticDataMember()) {
10178 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10179 SemaRef.Diag(VD->getLocation(),
10180 diag::note_omp_static_member_in_target);
10181 IsCorrect = false;
10182 }
10183 }
10184 }
10185 }
10186
10187 for (auto &I : RD->bases()) {
10188 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10189 I.getType()->getAsCXXRecordDecl()))
10190 IsCorrect = false;
10191 }
10192 return IsCorrect;
10193}
10194
10195static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10196 DSAStackTy *Stack, QualType QTy) {
10197 NamedDecl *ND;
10198 if (QTy->isIncompleteType(&ND)) {
10199 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10200 return false;
10201 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010202 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010203 return false;
10204 }
10205 return true;
10206}
10207
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010208/// \brief Return true if it can be proven that the provided array expression
10209/// (array section or array subscript) does NOT specify the whole size of the
10210/// array whose base type is \a BaseQTy.
10211static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10212 const Expr *E,
10213 QualType BaseQTy) {
10214 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10215
10216 // If this is an array subscript, it refers to the whole size if the size of
10217 // the dimension is constant and equals 1. Also, an array section assumes the
10218 // format of an array subscript if no colon is used.
10219 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10220 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10221 return ATy->getSize().getSExtValue() != 1;
10222 // Size can't be evaluated statically.
10223 return false;
10224 }
10225
10226 assert(OASE && "Expecting array section if not an array subscript.");
10227 auto *LowerBound = OASE->getLowerBound();
10228 auto *Length = OASE->getLength();
10229
10230 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010231 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010232 if (LowerBound) {
10233 llvm::APSInt ConstLowerBound;
10234 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10235 return false; // Can't get the integer value as a constant.
10236 if (ConstLowerBound.getSExtValue())
10237 return true;
10238 }
10239
10240 // If we don't have a length we covering the whole dimension.
10241 if (!Length)
10242 return false;
10243
10244 // If the base is a pointer, we don't have a way to get the size of the
10245 // pointee.
10246 if (BaseQTy->isPointerType())
10247 return false;
10248
10249 // We can only check if the length is the same as the size of the dimension
10250 // if we have a constant array.
10251 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10252 if (!CATy)
10253 return false;
10254
10255 llvm::APSInt ConstLength;
10256 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10257 return false; // Can't get the integer value as a constant.
10258
10259 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10260}
10261
10262// Return true if it can be proven that the provided array expression (array
10263// section or array subscript) does NOT specify a single element of the array
10264// whose base type is \a BaseQTy.
10265static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010266 const Expr *E,
10267 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010268 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10269
10270 // An array subscript always refer to a single element. Also, an array section
10271 // assumes the format of an array subscript if no colon is used.
10272 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10273 return false;
10274
10275 assert(OASE && "Expecting array section if not an array subscript.");
10276 auto *Length = OASE->getLength();
10277
10278 // If we don't have a length we have to check if the array has unitary size
10279 // for this dimension. Also, we should always expect a length if the base type
10280 // is pointer.
10281 if (!Length) {
10282 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10283 return ATy->getSize().getSExtValue() != 1;
10284 // We cannot assume anything.
10285 return false;
10286 }
10287
10288 // Check if the length evaluates to 1.
10289 llvm::APSInt ConstLength;
10290 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10291 return false; // Can't get the integer value as a constant.
10292
10293 return ConstLength.getSExtValue() != 1;
10294}
10295
Samuel Antao661c0902016-05-26 17:39:58 +000010296// Return the expression of the base of the mappable expression or null if it
10297// cannot be determined and do all the necessary checks to see if the expression
10298// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010299// components of the expression.
10300static Expr *CheckMapClauseExpressionBase(
10301 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010302 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10303 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010304 SourceLocation ELoc = E->getExprLoc();
10305 SourceRange ERange = E->getSourceRange();
10306
10307 // The base of elements of list in a map clause have to be either:
10308 // - a reference to variable or field.
10309 // - a member expression.
10310 // - an array expression.
10311 //
10312 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10313 // reference to 'r'.
10314 //
10315 // If we have:
10316 //
10317 // struct SS {
10318 // Bla S;
10319 // foo() {
10320 // #pragma omp target map (S.Arr[:12]);
10321 // }
10322 // }
10323 //
10324 // We want to retrieve the member expression 'this->S';
10325
10326 Expr *RelevantExpr = nullptr;
10327
Samuel Antao5de996e2016-01-22 20:21:36 +000010328 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10329 // If a list item is an array section, it must specify contiguous storage.
10330 //
10331 // For this restriction it is sufficient that we make sure only references
10332 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010333 // exist except in the rightmost expression (unless they cover the whole
10334 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010335 //
10336 // r.ArrS[3:5].Arr[6:7]
10337 //
10338 // r.ArrS[3:5].x
10339 //
10340 // but these would be valid:
10341 // r.ArrS[3].Arr[6:7]
10342 //
10343 // r.ArrS[3].x
10344
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010345 bool AllowUnitySizeArraySection = true;
10346 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010347
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010348 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010349 E = E->IgnoreParenImpCasts();
10350
10351 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10352 if (!isa<VarDecl>(CurE->getDecl()))
10353 break;
10354
10355 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010356
10357 // If we got a reference to a declaration, we should not expect any array
10358 // section before that.
10359 AllowUnitySizeArraySection = false;
10360 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010361
10362 // Record the component.
10363 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10364 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010365 continue;
10366 }
10367
10368 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10369 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10370
10371 if (isa<CXXThisExpr>(BaseE))
10372 // We found a base expression: this->Val.
10373 RelevantExpr = CurE;
10374 else
10375 E = BaseE;
10376
10377 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10378 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10379 << CurE->getSourceRange();
10380 break;
10381 }
10382
10383 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10384
10385 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10386 // A bit-field cannot appear in a map clause.
10387 //
10388 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010389 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10390 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010391 break;
10392 }
10393
10394 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10395 // If the type of a list item is a reference to a type T then the type
10396 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010397 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010398
10399 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10400 // A list item cannot be a variable that is a member of a structure with
10401 // a union type.
10402 //
10403 if (auto *RT = CurType->getAs<RecordType>())
10404 if (RT->isUnionType()) {
10405 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10406 << CurE->getSourceRange();
10407 break;
10408 }
10409
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010410 // If we got a member expression, we should not expect any array section
10411 // before that:
10412 //
10413 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10414 // If a list item is an element of a structure, only the rightmost symbol
10415 // of the variable reference can be an array section.
10416 //
10417 AllowUnitySizeArraySection = false;
10418 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010419
10420 // Record the component.
10421 CurComponents.push_back(
10422 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010423 continue;
10424 }
10425
10426 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10427 E = CurE->getBase()->IgnoreParenImpCasts();
10428
10429 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10430 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10431 << 0 << CurE->getSourceRange();
10432 break;
10433 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010434
10435 // If we got an array subscript that express the whole dimension we
10436 // can have any array expressions before. If it only expressing part of
10437 // the dimension, we can only have unitary-size array expressions.
10438 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10439 E->getType()))
10440 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010441
10442 // Record the component - we don't have any declaration associated.
10443 CurComponents.push_back(
10444 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010445 continue;
10446 }
10447
10448 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010449 E = CurE->getBase()->IgnoreParenImpCasts();
10450
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010451 auto CurType =
10452 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10453
Samuel Antao5de996e2016-01-22 20:21:36 +000010454 // 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 Antao5de996e2016-01-22 20:21:36 +000010457 if (CurType->isReferenceType())
10458 CurType = CurType->getPointeeType();
10459
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010460 bool IsPointer = CurType->isAnyPointerType();
10461
10462 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010463 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10464 << 0 << CurE->getSourceRange();
10465 break;
10466 }
10467
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010468 bool NotWhole =
10469 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10470 bool NotUnity =
10471 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10472
Samuel Antaodab51bb2016-07-18 23:22:11 +000010473 if (AllowWholeSizeArraySection) {
10474 // Any array section is currently allowed. Allowing a whole size array
10475 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010476 //
10477 // If this array section refers to the whole dimension we can still
10478 // accept other array sections before this one, except if the base is a
10479 // pointer. Otherwise, only unitary sections are accepted.
10480 if (NotWhole || IsPointer)
10481 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010482 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010483 // A unity or whole array section is not allowed and that is not
10484 // compatible with the properties of the current array section.
10485 SemaRef.Diag(
10486 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10487 << CurE->getSourceRange();
10488 break;
10489 }
Samuel Antao90927002016-04-26 14:54:23 +000010490
10491 // Record the component - we don't have any declaration associated.
10492 CurComponents.push_back(
10493 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010494 continue;
10495 }
10496
10497 // If nothing else worked, this is not a valid map clause expression.
10498 SemaRef.Diag(ELoc,
10499 diag::err_omp_expected_named_var_member_or_array_expression)
10500 << ERange;
10501 break;
10502 }
10503
10504 return RelevantExpr;
10505}
10506
10507// Return true if expression E associated with value VD has conflicts with other
10508// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010509static bool CheckMapConflicts(
10510 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10511 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010512 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10513 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010514 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010515 SourceLocation ELoc = E->getExprLoc();
10516 SourceRange ERange = E->getSourceRange();
10517
10518 // In order to easily check the conflicts we need to match each component of
10519 // the expression under test with the components of the expressions that are
10520 // already in the stack.
10521
Samuel Antao5de996e2016-01-22 20:21:36 +000010522 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010523 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010524 "Map clause expression with unexpected base!");
10525
10526 // Variables to help detecting enclosing problems in data environment nests.
10527 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010528 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010529
Samuel Antao90927002016-04-26 14:54:23 +000010530 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10531 VD, CurrentRegionOnly,
10532 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010533 StackComponents,
10534 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010535
Samuel Antao5de996e2016-01-22 20:21:36 +000010536 assert(!StackComponents.empty() &&
10537 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010538 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010539 "Map clause expression with unexpected base!");
10540
Samuel Antao90927002016-04-26 14:54:23 +000010541 // The whole expression in the stack.
10542 auto *RE = StackComponents.front().getAssociatedExpression();
10543
Samuel Antao5de996e2016-01-22 20:21:36 +000010544 // Expressions must start from the same base. Here we detect at which
10545 // point both expressions diverge from each other and see if we can
10546 // detect if the memory referred to both expressions is contiguous and
10547 // do not overlap.
10548 auto CI = CurComponents.rbegin();
10549 auto CE = CurComponents.rend();
10550 auto SI = StackComponents.rbegin();
10551 auto SE = StackComponents.rend();
10552 for (; CI != CE && SI != SE; ++CI, ++SI) {
10553
10554 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10555 // At most one list item can be an array item derived from a given
10556 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010557 if (CurrentRegionOnly &&
10558 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10559 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10560 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10561 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10562 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010563 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010564 << CI->getAssociatedExpression()->getSourceRange();
10565 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10566 diag::note_used_here)
10567 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010568 return true;
10569 }
10570
10571 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010572 if (CI->getAssociatedExpression()->getStmtClass() !=
10573 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010574 break;
10575
10576 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010577 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010578 break;
10579 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010580 // Check if the extra components of the expressions in the enclosing
10581 // data environment are redundant for the current base declaration.
10582 // If they are, the maps completely overlap, which is legal.
10583 for (; SI != SE; ++SI) {
10584 QualType Type;
10585 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010586 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010587 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010588 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10589 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010590 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10591 Type =
10592 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10593 }
10594 if (Type.isNull() || Type->isAnyPointerType() ||
10595 CheckArrayExpressionDoesNotReferToWholeSize(
10596 SemaRef, SI->getAssociatedExpression(), Type))
10597 break;
10598 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010599
10600 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10601 // List items of map clauses in the same construct must not share
10602 // original storage.
10603 //
10604 // If the expressions are exactly the same or one is a subset of the
10605 // other, it means they are sharing storage.
10606 if (CI == CE && SI == SE) {
10607 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010608 if (CKind == OMPC_map)
10609 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10610 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010611 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010612 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10613 << ERange;
10614 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010615 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10616 << RE->getSourceRange();
10617 return true;
10618 } else {
10619 // If we find the same expression in the enclosing data environment,
10620 // that is legal.
10621 IsEnclosedByDataEnvironmentExpr = true;
10622 return false;
10623 }
10624 }
10625
Samuel Antao90927002016-04-26 14:54:23 +000010626 QualType DerivedType =
10627 std::prev(CI)->getAssociatedDeclaration()->getType();
10628 SourceLocation DerivedLoc =
10629 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010630
10631 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10632 // If the type of a list item is a reference to a type T then the type
10633 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010634 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010635
10636 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10637 // A variable for which the type is pointer and an array section
10638 // derived from that variable must not appear as list items of map
10639 // clauses of the same construct.
10640 //
10641 // Also, cover one of the cases in:
10642 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10643 // If any part of the original storage of a list item has corresponding
10644 // storage in the device data environment, all of the original storage
10645 // must have corresponding storage in the device data environment.
10646 //
10647 if (DerivedType->isAnyPointerType()) {
10648 if (CI == CE || SI == SE) {
10649 SemaRef.Diag(
10650 DerivedLoc,
10651 diag::err_omp_pointer_mapped_along_with_derived_section)
10652 << DerivedLoc;
10653 } else {
10654 assert(CI != CE && SI != SE);
10655 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10656 << DerivedLoc;
10657 }
10658 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10659 << RE->getSourceRange();
10660 return true;
10661 }
10662
10663 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10664 // List items of map clauses in the same construct must not share
10665 // original storage.
10666 //
10667 // An expression is a subset of the other.
10668 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010669 if (CKind == OMPC_map)
10670 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10671 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010672 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010673 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10674 << ERange;
10675 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010676 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10677 << RE->getSourceRange();
10678 return true;
10679 }
10680
10681 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010682 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010683 if (!CurrentRegionOnly && SI != SE)
10684 EnclosingExpr = RE;
10685
10686 // The current expression is a subset of the expression in the data
10687 // environment.
10688 IsEnclosedByDataEnvironmentExpr |=
10689 (!CurrentRegionOnly && CI != CE && SI == SE);
10690
10691 return false;
10692 });
10693
10694 if (CurrentRegionOnly)
10695 return FoundError;
10696
10697 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10698 // If any part of the original storage of a list item has corresponding
10699 // storage in the device data environment, all of the original storage must
10700 // have corresponding storage in the device data environment.
10701 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10702 // If a list item is an element of a structure, and a different element of
10703 // the structure has a corresponding list item in the device data environment
10704 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010705 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010706 // data environment prior to the task encountering the construct.
10707 //
10708 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10709 SemaRef.Diag(ELoc,
10710 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10711 << ERange;
10712 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10713 << EnclosingExpr->getSourceRange();
10714 return true;
10715 }
10716
10717 return FoundError;
10718}
10719
Samuel Antao661c0902016-05-26 17:39:58 +000010720namespace {
10721// Utility struct that gathers all the related lists associated with a mappable
10722// expression.
10723struct MappableVarListInfo final {
10724 // The list of expressions.
10725 ArrayRef<Expr *> VarList;
10726 // The list of processed expressions.
10727 SmallVector<Expr *, 16> ProcessedVarList;
10728 // The mappble components for each expression.
10729 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10730 // The base declaration of the variable.
10731 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10732
10733 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10734 // We have a list of components and base declarations for each entry in the
10735 // variable list.
10736 VarComponents.reserve(VarList.size());
10737 VarBaseDeclarations.reserve(VarList.size());
10738 }
10739};
10740}
10741
10742// Check the validity of the provided variable list for the provided clause kind
10743// \a CKind. In the check process the valid expressions, and mappable expression
10744// components and variables are extracted and used to fill \a Vars,
10745// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10746// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10747static void
10748checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10749 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10750 SourceLocation StartLoc,
10751 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10752 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010753 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10754 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010755 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010756
Samuel Antao90927002016-04-26 14:54:23 +000010757 // Keep track of the mappable components and base declarations in this clause.
10758 // Each entry in the list is going to have a list of components associated. We
10759 // record each set of the components so that we can build the clause later on.
10760 // In the end we should have the same amount of declarations and component
10761 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010762
Samuel Antao661c0902016-05-26 17:39:58 +000010763 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010764 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010765 SourceLocation ELoc = RE->getExprLoc();
10766
Kelvin Li0bff7af2015-11-23 05:32:03 +000010767 auto *VE = RE->IgnoreParenLValueCasts();
10768
10769 if (VE->isValueDependent() || VE->isTypeDependent() ||
10770 VE->isInstantiationDependent() ||
10771 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010772 // We can only analyze this information once the missing information is
10773 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010774 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010775 continue;
10776 }
10777
10778 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010779
Samuel Antao5de996e2016-01-22 20:21:36 +000010780 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010781 SemaRef.Diag(ELoc,
10782 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010783 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010784 continue;
10785 }
10786
Samuel Antao90927002016-04-26 14:54:23 +000010787 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10788 ValueDecl *CurDeclaration = nullptr;
10789
10790 // Obtain the array or member expression bases if required. Also, fill the
10791 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010792 auto *BE =
10793 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010794 if (!BE)
10795 continue;
10796
Samuel Antao90927002016-04-26 14:54:23 +000010797 assert(!CurComponents.empty() &&
10798 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010799
Samuel Antao90927002016-04-26 14:54:23 +000010800 // For the following checks, we rely on the base declaration which is
10801 // expected to be associated with the last component. The declaration is
10802 // expected to be a variable or a field (if 'this' is being mapped).
10803 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10804 assert(CurDeclaration && "Null decl on map clause.");
10805 assert(
10806 CurDeclaration->isCanonicalDecl() &&
10807 "Expecting components to have associated only canonical declarations.");
10808
10809 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10810 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010811
10812 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010813 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010814
10815 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010816 // threadprivate variables cannot appear in a map clause.
10817 // OpenMP 4.5 [2.10.5, target update Construct]
10818 // threadprivate variables cannot appear in a from clause.
10819 if (VD && DSAS->isThreadPrivate(VD)) {
10820 auto DVar = DSAS->getTopDSA(VD, false);
10821 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10822 << getOpenMPClauseName(CKind);
10823 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010824 continue;
10825 }
10826
Samuel Antao5de996e2016-01-22 20:21:36 +000010827 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10828 // A list item cannot appear in both a map clause and a data-sharing
10829 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010830
Samuel Antao5de996e2016-01-22 20:21:36 +000010831 // Check conflicts with other map clause expressions. We check the conflicts
10832 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010833 // environment, because the restrictions are different. We only have to
10834 // check conflicts across regions for the map clauses.
10835 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10836 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010837 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010838 if (CKind == OMPC_map &&
10839 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10840 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010841 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010842
Samuel Antao661c0902016-05-26 17:39:58 +000010843 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010844 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10845 // If the type of a list item is a reference to a type T then the type will
10846 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010847 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010848
Samuel Antao661c0902016-05-26 17:39:58 +000010849 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10850 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010851 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010852 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010853 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10854 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010855 continue;
10856
Samuel Antao661c0902016-05-26 17:39:58 +000010857 if (CKind == OMPC_map) {
10858 // target enter data
10859 // OpenMP [2.10.2, Restrictions, p. 99]
10860 // A map-type must be specified in all map clauses and must be either
10861 // to or alloc.
10862 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10863 if (DKind == OMPD_target_enter_data &&
10864 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10865 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10866 << (IsMapTypeImplicit ? 1 : 0)
10867 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10868 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010869 continue;
10870 }
Samuel Antao661c0902016-05-26 17:39:58 +000010871
10872 // target exit_data
10873 // OpenMP [2.10.3, Restrictions, p. 102]
10874 // A map-type must be specified in all map clauses and must be either
10875 // from, release, or delete.
10876 if (DKind == OMPD_target_exit_data &&
10877 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10878 MapType == OMPC_MAP_delete)) {
10879 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10880 << (IsMapTypeImplicit ? 1 : 0)
10881 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10882 << getOpenMPDirectiveName(DKind);
10883 continue;
10884 }
10885
10886 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10887 // A list item cannot appear in both a map clause and a data-sharing
10888 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010889 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010890 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010891 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010892 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10893 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010894 auto DVar = DSAS->getTopDSA(VD, false);
10895 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010896 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010897 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010898 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010899 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10900 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10901 continue;
10902 }
10903 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010904 }
10905
Samuel Antao90927002016-04-26 14:54:23 +000010906 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010907 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010908
10909 // Store the components in the stack so that they can be used to check
10910 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010911 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10912 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010913
10914 // Save the components and declaration to create the clause. For purposes of
10915 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010916 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010917 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10918 MVLI.VarComponents.back().append(CurComponents.begin(),
10919 CurComponents.end());
10920 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10921 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010922 }
Samuel Antao661c0902016-05-26 17:39:58 +000010923}
10924
10925OMPClause *
10926Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10927 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10928 SourceLocation MapLoc, SourceLocation ColonLoc,
10929 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10930 SourceLocation LParenLoc, SourceLocation EndLoc) {
10931 MappableVarListInfo MVLI(VarList);
10932 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10933 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010934
Samuel Antao5de996e2016-01-22 20:21:36 +000010935 // We need to produce a map clause even if we don't have variables so that
10936 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010937 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10938 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10939 MVLI.VarComponents, MapTypeModifier, MapType,
10940 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010941}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010942
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010943QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10944 TypeResult ParsedType) {
10945 assert(ParsedType.isUsable());
10946
10947 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10948 if (ReductionType.isNull())
10949 return QualType();
10950
10951 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10952 // A type name in a declare reduction directive cannot be a function type, an
10953 // array type, a reference type, or a type qualified with const, volatile or
10954 // restrict.
10955 if (ReductionType.hasQualifiers()) {
10956 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10957 return QualType();
10958 }
10959
10960 if (ReductionType->isFunctionType()) {
10961 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10962 return QualType();
10963 }
10964 if (ReductionType->isReferenceType()) {
10965 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10966 return QualType();
10967 }
10968 if (ReductionType->isArrayType()) {
10969 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10970 return QualType();
10971 }
10972 return ReductionType;
10973}
10974
10975Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10976 Scope *S, DeclContext *DC, DeclarationName Name,
10977 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10978 AccessSpecifier AS, Decl *PrevDeclInScope) {
10979 SmallVector<Decl *, 8> Decls;
10980 Decls.reserve(ReductionTypes.size());
10981
10982 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10983 ForRedeclaration);
10984 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10985 // A reduction-identifier may not be re-declared in the current scope for the
10986 // same type or for a type that is compatible according to the base language
10987 // rules.
10988 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10989 OMPDeclareReductionDecl *PrevDRD = nullptr;
10990 bool InCompoundScope = true;
10991 if (S != nullptr) {
10992 // Find previous declaration with the same name not referenced in other
10993 // declarations.
10994 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10995 InCompoundScope =
10996 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10997 LookupName(Lookup, S);
10998 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10999 /*AllowInlineNamespace=*/false);
11000 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11001 auto Filter = Lookup.makeFilter();
11002 while (Filter.hasNext()) {
11003 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11004 if (InCompoundScope) {
11005 auto I = UsedAsPrevious.find(PrevDecl);
11006 if (I == UsedAsPrevious.end())
11007 UsedAsPrevious[PrevDecl] = false;
11008 if (auto *D = PrevDecl->getPrevDeclInScope())
11009 UsedAsPrevious[D] = true;
11010 }
11011 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11012 PrevDecl->getLocation();
11013 }
11014 Filter.done();
11015 if (InCompoundScope) {
11016 for (auto &PrevData : UsedAsPrevious) {
11017 if (!PrevData.second) {
11018 PrevDRD = PrevData.first;
11019 break;
11020 }
11021 }
11022 }
11023 } else if (PrevDeclInScope != nullptr) {
11024 auto *PrevDRDInScope = PrevDRD =
11025 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11026 do {
11027 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11028 PrevDRDInScope->getLocation();
11029 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11030 } while (PrevDRDInScope != nullptr);
11031 }
11032 for (auto &TyData : ReductionTypes) {
11033 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11034 bool Invalid = false;
11035 if (I != PreviousRedeclTypes.end()) {
11036 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11037 << TyData.first;
11038 Diag(I->second, diag::note_previous_definition);
11039 Invalid = true;
11040 }
11041 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11042 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11043 Name, TyData.first, PrevDRD);
11044 DC->addDecl(DRD);
11045 DRD->setAccess(AS);
11046 Decls.push_back(DRD);
11047 if (Invalid)
11048 DRD->setInvalidDecl();
11049 else
11050 PrevDRD = DRD;
11051 }
11052
11053 return DeclGroupPtrTy::make(
11054 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11055}
11056
11057void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11058 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11059
11060 // Enter new function scope.
11061 PushFunctionScope();
11062 getCurFunction()->setHasBranchProtectedScope();
11063 getCurFunction()->setHasOMPDeclareReductionCombiner();
11064
11065 if (S != nullptr)
11066 PushDeclContext(S, DRD);
11067 else
11068 CurContext = DRD;
11069
Faisal Valid143a0c2017-04-01 21:30:49 +000011070 PushExpressionEvaluationContext(
11071 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011072
11073 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011074 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11075 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11076 // uses semantics of argument handles by value, but it should be passed by
11077 // reference. C lang does not support references, so pass all parameters as
11078 // pointers.
11079 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011080 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011081 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011082 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11083 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11084 // uses semantics of argument handles by value, but it should be passed by
11085 // reference. C lang does not support references, so pass all parameters as
11086 // pointers.
11087 // Create 'T omp_out;' variable.
11088 auto *OmpOutParm =
11089 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11090 if (S != nullptr) {
11091 PushOnScopeChains(OmpInParm, S);
11092 PushOnScopeChains(OmpOutParm, S);
11093 } else {
11094 DRD->addDecl(OmpInParm);
11095 DRD->addDecl(OmpOutParm);
11096 }
11097}
11098
11099void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11100 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11101 DiscardCleanupsInEvaluationContext();
11102 PopExpressionEvaluationContext();
11103
11104 PopDeclContext();
11105 PopFunctionScopeInfo();
11106
11107 if (Combiner != nullptr)
11108 DRD->setCombiner(Combiner);
11109 else
11110 DRD->setInvalidDecl();
11111}
11112
11113void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11114 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11115
11116 // Enter new function scope.
11117 PushFunctionScope();
11118 getCurFunction()->setHasBranchProtectedScope();
11119
11120 if (S != nullptr)
11121 PushDeclContext(S, DRD);
11122 else
11123 CurContext = DRD;
11124
Faisal Valid143a0c2017-04-01 21:30:49 +000011125 PushExpressionEvaluationContext(
11126 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011127
11128 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011129 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11130 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11131 // uses semantics of argument handles by value, but it should be passed by
11132 // reference. C lang does not support references, so pass all parameters as
11133 // pointers.
11134 // Create 'T omp_priv;' variable.
11135 auto *OmpPrivParm =
11136 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011137 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11138 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11139 // uses semantics of argument handles by value, but it should be passed by
11140 // reference. C lang does not support references, so pass all parameters as
11141 // pointers.
11142 // Create 'T omp_orig;' variable.
11143 auto *OmpOrigParm =
11144 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011145 if (S != nullptr) {
11146 PushOnScopeChains(OmpPrivParm, S);
11147 PushOnScopeChains(OmpOrigParm, S);
11148 } else {
11149 DRD->addDecl(OmpPrivParm);
11150 DRD->addDecl(OmpOrigParm);
11151 }
11152}
11153
11154void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11155 Expr *Initializer) {
11156 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11157 DiscardCleanupsInEvaluationContext();
11158 PopExpressionEvaluationContext();
11159
11160 PopDeclContext();
11161 PopFunctionScopeInfo();
11162
11163 if (Initializer != nullptr)
11164 DRD->setInitializer(Initializer);
11165 else
11166 DRD->setInvalidDecl();
11167}
11168
11169Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11170 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11171 for (auto *D : DeclReductions.get()) {
11172 if (IsValid) {
11173 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11174 if (S != nullptr)
11175 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11176 } else
11177 D->setInvalidDecl();
11178 }
11179 return DeclReductions;
11180}
11181
David Majnemer9d168222016-08-05 17:44:54 +000011182OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011183 SourceLocation StartLoc,
11184 SourceLocation LParenLoc,
11185 SourceLocation EndLoc) {
11186 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011187 Stmt *HelperValStmt = nullptr;
11188 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011189
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011190 // OpenMP [teams Constrcut, Restrictions]
11191 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011192 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11193 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011194 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011195
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011196 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11197 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11198 if (CaptureRegion != OMPD_unknown) {
11199 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11200 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11201 HelperValStmt = buildPreInits(Context, Captures);
11202 }
11203
11204 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11205 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011206}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011207
11208OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11209 SourceLocation StartLoc,
11210 SourceLocation LParenLoc,
11211 SourceLocation EndLoc) {
11212 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011213 Stmt *HelperValStmt = nullptr;
11214 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011215
11216 // OpenMP [teams Constrcut, Restrictions]
11217 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011218 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11219 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011220 return nullptr;
11221
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011222 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11223 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11224 if (CaptureRegion != OMPD_unknown) {
11225 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11226 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11227 HelperValStmt = buildPreInits(Context, Captures);
11228 }
11229
11230 return new (Context) OMPThreadLimitClause(
11231 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011232}
Alexey Bataeva0569352015-12-01 10:17:31 +000011233
11234OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11235 SourceLocation StartLoc,
11236 SourceLocation LParenLoc,
11237 SourceLocation EndLoc) {
11238 Expr *ValExpr = Priority;
11239
11240 // OpenMP [2.9.1, task Constrcut]
11241 // The priority-value is a non-negative numerical scalar expression.
11242 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11243 /*StrictlyPositive=*/false))
11244 return nullptr;
11245
11246 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11247}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011248
11249OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11250 SourceLocation StartLoc,
11251 SourceLocation LParenLoc,
11252 SourceLocation EndLoc) {
11253 Expr *ValExpr = Grainsize;
11254
11255 // OpenMP [2.9.2, taskloop Constrcut]
11256 // The parameter of the grainsize clause must be a positive integer
11257 // expression.
11258 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11259 /*StrictlyPositive=*/true))
11260 return nullptr;
11261
11262 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11263}
Alexey Bataev382967a2015-12-08 12:06:20 +000011264
11265OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11266 SourceLocation StartLoc,
11267 SourceLocation LParenLoc,
11268 SourceLocation EndLoc) {
11269 Expr *ValExpr = NumTasks;
11270
11271 // OpenMP [2.9.2, taskloop Constrcut]
11272 // The parameter of the num_tasks clause must be a positive integer
11273 // expression.
11274 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11275 /*StrictlyPositive=*/true))
11276 return nullptr;
11277
11278 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11279}
11280
Alexey Bataev28c75412015-12-15 08:19:24 +000011281OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11282 SourceLocation LParenLoc,
11283 SourceLocation EndLoc) {
11284 // OpenMP [2.13.2, critical construct, Description]
11285 // ... where hint-expression is an integer constant expression that evaluates
11286 // to a valid lock hint.
11287 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11288 if (HintExpr.isInvalid())
11289 return nullptr;
11290 return new (Context)
11291 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11292}
11293
Carlo Bertollib4adf552016-01-15 18:50:31 +000011294OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11295 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11296 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11297 SourceLocation EndLoc) {
11298 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11299 std::string Values;
11300 Values += "'";
11301 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11302 Values += "'";
11303 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11304 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11305 return nullptr;
11306 }
11307 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011308 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011309 if (ChunkSize) {
11310 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11311 !ChunkSize->isInstantiationDependent() &&
11312 !ChunkSize->containsUnexpandedParameterPack()) {
11313 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11314 ExprResult Val =
11315 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11316 if (Val.isInvalid())
11317 return nullptr;
11318
11319 ValExpr = Val.get();
11320
11321 // OpenMP [2.7.1, Restrictions]
11322 // chunk_size must be a loop invariant integer expression with a positive
11323 // value.
11324 llvm::APSInt Result;
11325 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11326 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11327 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11328 << "dist_schedule" << ChunkSize->getSourceRange();
11329 return nullptr;
11330 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011331 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11332 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011333 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11334 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11335 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011336 }
11337 }
11338 }
11339
11340 return new (Context)
11341 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011342 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011343}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011344
11345OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11346 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11347 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11348 SourceLocation KindLoc, SourceLocation EndLoc) {
11349 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011350 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011351 std::string Value;
11352 SourceLocation Loc;
11353 Value += "'";
11354 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11355 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011356 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011357 Loc = MLoc;
11358 } else {
11359 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011360 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011361 Loc = KindLoc;
11362 }
11363 Value += "'";
11364 Diag(Loc, diag::err_omp_unexpected_clause_value)
11365 << Value << getOpenMPClauseName(OMPC_defaultmap);
11366 return nullptr;
11367 }
11368
11369 return new (Context)
11370 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11371}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011372
11373bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11374 DeclContext *CurLexicalContext = getCurLexicalContext();
11375 if (!CurLexicalContext->isFileContext() &&
11376 !CurLexicalContext->isExternCContext() &&
11377 !CurLexicalContext->isExternCXXContext()) {
11378 Diag(Loc, diag::err_omp_region_not_file_context);
11379 return false;
11380 }
11381 if (IsInOpenMPDeclareTargetContext) {
11382 Diag(Loc, diag::err_omp_enclosed_declare_target);
11383 return false;
11384 }
11385
11386 IsInOpenMPDeclareTargetContext = true;
11387 return true;
11388}
11389
11390void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11391 assert(IsInOpenMPDeclareTargetContext &&
11392 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11393
11394 IsInOpenMPDeclareTargetContext = false;
11395}
11396
David Majnemer9d168222016-08-05 17:44:54 +000011397void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11398 CXXScopeSpec &ScopeSpec,
11399 const DeclarationNameInfo &Id,
11400 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11401 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011402 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11403 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11404
11405 if (Lookup.isAmbiguous())
11406 return;
11407 Lookup.suppressDiagnostics();
11408
11409 if (!Lookup.isSingleResult()) {
11410 if (TypoCorrection Corrected =
11411 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11412 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11413 CTK_ErrorRecovery)) {
11414 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11415 << Id.getName());
11416 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11417 return;
11418 }
11419
11420 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11421 return;
11422 }
11423
11424 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11425 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11426 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11427 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11428
11429 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11430 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11431 ND->addAttr(A);
11432 if (ASTMutationListener *ML = Context.getASTMutationListener())
11433 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11434 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11435 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11436 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11437 << Id.getName();
11438 }
11439 } else
11440 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11441}
11442
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011443static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11444 Sema &SemaRef, Decl *D) {
11445 if (!D)
11446 return;
11447 Decl *LD = nullptr;
11448 if (isa<TagDecl>(D)) {
11449 LD = cast<TagDecl>(D)->getDefinition();
11450 } else if (isa<VarDecl>(D)) {
11451 LD = cast<VarDecl>(D)->getDefinition();
11452
11453 // If this is an implicit variable that is legal and we do not need to do
11454 // anything.
11455 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011456 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11457 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11458 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011459 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011460 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011461 return;
11462 }
11463
11464 } else if (isa<FunctionDecl>(D)) {
11465 const FunctionDecl *FD = nullptr;
11466 if (cast<FunctionDecl>(D)->hasBody(FD))
11467 LD = const_cast<FunctionDecl *>(FD);
11468
11469 // If the definition is associated with the current declaration in the
11470 // target region (it can be e.g. a lambda) that is legal and we do not need
11471 // to do anything else.
11472 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011473 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11474 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11475 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011476 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011477 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011478 return;
11479 }
11480 }
11481 if (!LD)
11482 LD = D;
11483 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11484 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11485 // Outlined declaration is not declared target.
11486 if (LD->isOutOfLine()) {
11487 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11488 SemaRef.Diag(SL, diag::note_used_here) << SR;
11489 } else {
11490 DeclContext *DC = LD->getDeclContext();
11491 while (DC) {
11492 if (isa<FunctionDecl>(DC) &&
11493 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11494 break;
11495 DC = DC->getParent();
11496 }
11497 if (DC)
11498 return;
11499
11500 // Is not declared in target context.
11501 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11502 SemaRef.Diag(SL, diag::note_used_here) << SR;
11503 }
11504 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011505 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11506 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11507 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011508 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011509 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011510 }
11511}
11512
11513static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11514 Sema &SemaRef, DSAStackTy *Stack,
11515 ValueDecl *VD) {
11516 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11517 return true;
11518 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11519 return false;
11520 return true;
11521}
11522
11523void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11524 if (!D || D->isInvalidDecl())
11525 return;
11526 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11527 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11528 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11529 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11530 if (DSAStack->isThreadPrivate(VD)) {
11531 Diag(SL, diag::err_omp_threadprivate_in_target);
11532 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11533 return;
11534 }
11535 }
11536 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11537 // Problem if any with var declared with incomplete type will be reported
11538 // as normal, so no need to check it here.
11539 if ((E || !VD->getType()->isIncompleteType()) &&
11540 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11541 // Mark decl as declared target to prevent further diagnostic.
11542 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011543 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11544 Context, OMPDeclareTargetDeclAttr::MT_To);
11545 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011546 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011547 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011548 }
11549 return;
11550 }
11551 }
11552 if (!E) {
11553 // Checking declaration inside declare target region.
11554 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11555 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011556 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11557 Context, OMPDeclareTargetDeclAttr::MT_To);
11558 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011559 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011560 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011561 }
11562 return;
11563 }
11564 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11565}
Samuel Antao661c0902016-05-26 17:39:58 +000011566
11567OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11568 SourceLocation StartLoc,
11569 SourceLocation LParenLoc,
11570 SourceLocation EndLoc) {
11571 MappableVarListInfo MVLI(VarList);
11572 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11573 if (MVLI.ProcessedVarList.empty())
11574 return nullptr;
11575
11576 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11577 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11578 MVLI.VarComponents);
11579}
Samuel Antaoec172c62016-05-26 17:49:04 +000011580
11581OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11582 SourceLocation StartLoc,
11583 SourceLocation LParenLoc,
11584 SourceLocation EndLoc) {
11585 MappableVarListInfo MVLI(VarList);
11586 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11587 if (MVLI.ProcessedVarList.empty())
11588 return nullptr;
11589
11590 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11591 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11592 MVLI.VarComponents);
11593}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011594
11595OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11596 SourceLocation StartLoc,
11597 SourceLocation LParenLoc,
11598 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011599 MappableVarListInfo MVLI(VarList);
11600 SmallVector<Expr *, 8> PrivateCopies;
11601 SmallVector<Expr *, 8> Inits;
11602
Carlo Bertolli2404b172016-07-13 15:37:16 +000011603 for (auto &RefExpr : VarList) {
11604 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11605 SourceLocation ELoc;
11606 SourceRange ERange;
11607 Expr *SimpleRefExpr = RefExpr;
11608 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11609 if (Res.second) {
11610 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011611 MVLI.ProcessedVarList.push_back(RefExpr);
11612 PrivateCopies.push_back(nullptr);
11613 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011614 }
11615 ValueDecl *D = Res.first;
11616 if (!D)
11617 continue;
11618
11619 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011620 Type = Type.getNonReferenceType().getUnqualifiedType();
11621
11622 auto *VD = dyn_cast<VarDecl>(D);
11623
11624 // Item should be a pointer or reference to pointer.
11625 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011626 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11627 << 0 << RefExpr->getSourceRange();
11628 continue;
11629 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011630
11631 // Build the private variable and the expression that refers to it.
11632 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11633 D->hasAttrs() ? &D->getAttrs() : nullptr);
11634 if (VDPrivate->isInvalidDecl())
11635 continue;
11636
11637 CurContext->addDecl(VDPrivate);
11638 auto VDPrivateRefExpr = buildDeclRefExpr(
11639 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11640
11641 // Add temporary variable to initialize the private copy of the pointer.
11642 auto *VDInit =
11643 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11644 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11645 RefExpr->getExprLoc());
11646 AddInitializerToDecl(VDPrivate,
11647 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011648 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011649
11650 // If required, build a capture to implement the privatization initialized
11651 // with the current list item value.
11652 DeclRefExpr *Ref = nullptr;
11653 if (!VD)
11654 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11655 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11656 PrivateCopies.push_back(VDPrivateRefExpr);
11657 Inits.push_back(VDInitRefExpr);
11658
11659 // We need to add a data sharing attribute for this variable to make sure it
11660 // is correctly captured. A variable that shows up in a use_device_ptr has
11661 // similar properties of a first private variable.
11662 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11663
11664 // Create a mappable component for the list item. List items in this clause
11665 // only need a component.
11666 MVLI.VarBaseDeclarations.push_back(D);
11667 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11668 MVLI.VarComponents.back().push_back(
11669 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011670 }
11671
Samuel Antaocc10b852016-07-28 14:23:26 +000011672 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011673 return nullptr;
11674
Samuel Antaocc10b852016-07-28 14:23:26 +000011675 return OMPUseDevicePtrClause::Create(
11676 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11677 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011678}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011679
11680OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11681 SourceLocation StartLoc,
11682 SourceLocation LParenLoc,
11683 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011684 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011685 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011686 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011687 SourceLocation ELoc;
11688 SourceRange ERange;
11689 Expr *SimpleRefExpr = RefExpr;
11690 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11691 if (Res.second) {
11692 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011693 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011694 }
11695 ValueDecl *D = Res.first;
11696 if (!D)
11697 continue;
11698
11699 QualType Type = D->getType();
11700 // item should be a pointer or array or reference to pointer or array
11701 if (!Type.getNonReferenceType()->isPointerType() &&
11702 !Type.getNonReferenceType()->isArrayType()) {
11703 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11704 << 0 << RefExpr->getSourceRange();
11705 continue;
11706 }
Samuel Antao6890b092016-07-28 14:25:09 +000011707
11708 // Check if the declaration in the clause does not show up in any data
11709 // sharing attribute.
11710 auto DVar = DSAStack->getTopDSA(D, false);
11711 if (isOpenMPPrivate(DVar.CKind)) {
11712 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11713 << getOpenMPClauseName(DVar.CKind)
11714 << getOpenMPClauseName(OMPC_is_device_ptr)
11715 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11716 ReportOriginalDSA(*this, DSAStack, D, DVar);
11717 continue;
11718 }
11719
11720 Expr *ConflictExpr;
11721 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011722 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011723 [&ConflictExpr](
11724 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11725 OpenMPClauseKind) -> bool {
11726 ConflictExpr = R.front().getAssociatedExpression();
11727 return true;
11728 })) {
11729 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11730 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11731 << ConflictExpr->getSourceRange();
11732 continue;
11733 }
11734
11735 // Store the components in the stack so that they can be used to check
11736 // against other clauses later on.
11737 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11738 DSAStack->addMappableExpressionComponents(
11739 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11740
11741 // Record the expression we've just processed.
11742 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11743
11744 // Create a mappable component for the list item. List items in this clause
11745 // only need a component. We use a null declaration to signal fields in
11746 // 'this'.
11747 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11748 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11749 "Unexpected device pointer expression!");
11750 MVLI.VarBaseDeclarations.push_back(
11751 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11752 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11753 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011754 }
11755
Samuel Antao6890b092016-07-28 14:25:09 +000011756 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011757 return nullptr;
11758
Samuel Antao6890b092016-07-28 14:25:09 +000011759 return OMPIsDevicePtrClause::Create(
11760 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11761 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011762}