blob: fb13669407fc1a6624a72066010283cfaf0b1807 [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;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000836 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000837 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000838 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000839 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000840 return DVar;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000841 } while (I != EndI);
842 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000843}
844
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000845DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
846 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
847 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
848 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000849 if (isStackEmpty())
850 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000851 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000852 auto StartI = std::next(Stack.back().first.rbegin());
853 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000854 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000855 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000856 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +0000857 return {};
Alexey Bataeve3978122016-07-19 05:06:39 +0000858 DSAVarData DVar = getDSA(StartI, D);
859 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000860}
861
Alexey Bataevaac108a2015-06-23 04:51:00 +0000862bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000863 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000864 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000865 if (CPred(ClauseKindMode))
866 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000867 if (isStackEmpty())
868 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000869 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000870 auto StartI = Stack.back().first.begin();
871 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000872 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000873 return false;
874 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000875 return (StartI->SharingMap.count(D) > 0) &&
876 StartI->SharingMap[D].RefExpr.getPointer() &&
877 CPred(StartI->SharingMap[D].Attributes) &&
878 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000879}
880
Samuel Antao4be30e92015-10-02 17:14:03 +0000881bool DSAStackTy::hasExplicitDirective(
882 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
883 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000884 if (isStackEmpty())
885 return false;
886 auto StartI = Stack.back().first.begin();
887 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000888 if (std::distance(StartI, EndI) <= (int)Level)
889 return false;
890 std::advance(StartI, Level);
891 return DPred(StartI->Directive);
892}
893
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000894bool DSAStackTy::hasDirective(
895 const llvm::function_ref<bool(OpenMPDirectiveKind,
896 const DeclarationNameInfo &, SourceLocation)>
897 &DPred,
898 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000899 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000900 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +0000901 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +0000902 auto StartI = std::next(Stack.back().first.rbegin());
903 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000904 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000905 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000906 for (auto I = StartI, EE = EndI; I != EE; ++I) {
907 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
908 return true;
909 }
910 return false;
911}
912
Alexey Bataev758e55e2013-09-06 18:03:48 +0000913void Sema::InitDataSharingAttributesStack() {
914 VarDataSharingAttributesStack = new DSAStackTy(*this);
915}
916
917#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
918
Alexey Bataev4b465392017-04-26 15:06:24 +0000919void Sema::pushOpenMPFunctionRegion() {
920 DSAStack->pushFunction();
921}
922
923void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
924 DSAStack->popFunction(OldFSI);
925}
926
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000927bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000928 assert(LangOpts.OpenMP && "OpenMP is not allowed");
929
930 auto &Ctx = getASTContext();
931 bool IsByRef = true;
932
933 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000934 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000935
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000936 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000937 // This table summarizes how a given variable should be passed to the device
938 // given its type and the clauses where it appears. This table is based on
939 // the description in OpenMP 4.5 [2.10.4, target Construct] and
940 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
941 //
942 // =========================================================================
943 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
944 // | |(tofrom:scalar)| | pvt | | | |
945 // =========================================================================
946 // | scl | | | | - | | bycopy|
947 // | scl | | - | x | - | - | bycopy|
948 // | scl | | x | - | - | - | null |
949 // | scl | x | | | - | | byref |
950 // | scl | x | - | x | - | - | bycopy|
951 // | scl | x | x | - | - | - | null |
952 // | scl | | - | - | - | x | byref |
953 // | scl | x | - | - | - | x | byref |
954 //
955 // | agg | n.a. | | | - | | byref |
956 // | agg | n.a. | - | x | - | - | byref |
957 // | agg | n.a. | x | - | - | - | null |
958 // | agg | n.a. | - | - | - | x | byref |
959 // | agg | n.a. | - | - | - | x[] | byref |
960 //
961 // | ptr | n.a. | | | - | | bycopy|
962 // | ptr | n.a. | - | x | - | - | bycopy|
963 // | ptr | n.a. | x | - | - | - | null |
964 // | ptr | n.a. | - | - | - | x | byref |
965 // | ptr | n.a. | - | - | - | x[] | bycopy|
966 // | ptr | n.a. | - | - | x | | bycopy|
967 // | ptr | n.a. | - | - | x | x | bycopy|
968 // | ptr | n.a. | - | - | x | x[] | bycopy|
969 // =========================================================================
970 // Legend:
971 // scl - scalar
972 // ptr - pointer
973 // agg - aggregate
974 // x - applies
975 // - - invalid in this combination
976 // [] - mapped with an array section
977 // byref - should be mapped by reference
978 // byval - should be mapped by value
979 // null - initialize a local variable to null on the device
980 //
981 // Observations:
982 // - All scalar declarations that show up in a map clause have to be passed
983 // by reference, because they may have been mapped in the enclosing data
984 // environment.
985 // - If the scalar value does not fit the size of uintptr, it has to be
986 // passed by reference, regardless the result in the table above.
987 // - For pointers mapped by value that have either an implicit map or an
988 // array section, the runtime library may pass the NULL value to the
989 // device instead of the value passed to it by the compiler.
990
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000991 if (Ty->isReferenceType())
992 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000993
994 // Locate map clauses and see if the variable being captured is referred to
995 // in any of those clauses. Here we only care about variables, not fields,
996 // because fields are part of aggregates.
997 bool IsVariableUsedInMapClause = false;
998 bool IsVariableAssociatedWithSection = false;
999
1000 DSAStack->checkMappableExprComponentListsForDecl(
1001 D, /*CurrentRegionOnly=*/true,
1002 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001003 MapExprComponents,
1004 OpenMPClauseKind WhereFoundClauseKind) {
1005 // Only the map clause information influences how a variable is
1006 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001007 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001008 if (WhereFoundClauseKind != OMPC_map)
1009 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001010
1011 auto EI = MapExprComponents.rbegin();
1012 auto EE = MapExprComponents.rend();
1013
1014 assert(EI != EE && "Invalid map expression!");
1015
1016 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1017 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1018
1019 ++EI;
1020 if (EI == EE)
1021 return false;
1022
1023 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1024 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1025 isa<MemberExpr>(EI->getAssociatedExpression())) {
1026 IsVariableAssociatedWithSection = true;
1027 // There is nothing more we need to know about this variable.
1028 return true;
1029 }
1030
1031 // Keep looking for more map info.
1032 return false;
1033 });
1034
1035 if (IsVariableUsedInMapClause) {
1036 // If variable is identified in a map clause it is always captured by
1037 // reference except if it is a pointer that is dereferenced somehow.
1038 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1039 } else {
1040 // By default, all the data that has a scalar type is mapped by copy.
1041 IsByRef = !Ty->isScalarType();
1042 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001043 }
1044
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001045 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1046 IsByRef = !DSAStack->hasExplicitDSA(
1047 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1048 Level, /*NotLastprivate=*/true);
1049 }
1050
Samuel Antao86ace552016-04-27 22:40:57 +00001051 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001052 // and alignment, because the runtime library only deals with uintptr types.
1053 // If it does not fit the uintptr size, we need to pass the data by reference
1054 // instead.
1055 if (!IsByRef &&
1056 (Ctx.getTypeSizeInChars(Ty) >
1057 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001058 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001059 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001060 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001061
1062 return IsByRef;
1063}
1064
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001065unsigned Sema::getOpenMPNestingLevel() const {
1066 assert(getLangOpts().OpenMP);
1067 return DSAStack->getNestingLevel();
1068}
1069
Alexey Bataev90c228f2016-02-08 09:29:13 +00001070VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001071 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001072 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001073
1074 // If we are attempting to capture a global variable in a directive with
1075 // 'target' we return true so that this global is also mapped to the device.
1076 //
1077 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1078 // then it should not be captured. Therefore, an extra check has to be
1079 // inserted here once support for 'declare target' is added.
1080 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001081 auto *VD = dyn_cast<VarDecl>(D);
1082 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001083 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001084 !DSAStack->isClauseParsingMode())
1085 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001086 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001087 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1088 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001089 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001090 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001091 false))
1092 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001093 }
1094
Alexey Bataev48977c32015-08-04 08:10:48 +00001095 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1096 (!DSAStack->isClauseParsingMode() ||
1097 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001098 auto &&Info = DSAStack->isLoopControlVariable(D);
1099 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001100 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001101 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001102 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001103 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001105 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001106 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001107 DVarPrivate = DSAStack->hasDSA(
1108 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1109 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001110 if (DVarPrivate.CKind != OMPC_unknown)
1111 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001112 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001113 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001114}
1115
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001116bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001117 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1118 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001119 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001120}
1121
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001122bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001123 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1124 // Return true if the current level is no longer enclosed in a target region.
1125
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001126 auto *VD = dyn_cast<VarDecl>(D);
1127 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001128 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1129 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001130}
1131
Alexey Bataeved09d242014-05-28 05:53:51 +00001132void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001133
1134void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1135 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001136 Scope *CurScope, SourceLocation Loc) {
1137 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001138 PushExpressionEvaluationContext(
1139 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001140}
1141
Alexey Bataevaac108a2015-06-23 04:51:00 +00001142void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1143 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001144}
1145
Alexey Bataevaac108a2015-06-23 04:51:00 +00001146void Sema::EndOpenMPClause() {
1147 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001148}
1149
Alexey Bataev758e55e2013-09-06 18:03:48 +00001150void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001151 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1152 // A variable of class type (or array thereof) that appears in a lastprivate
1153 // clause requires an accessible, unambiguous default constructor for the
1154 // class type, unless the list item is also specified in a firstprivate
1155 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001156 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001157 for (auto *C : D->clauses()) {
1158 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1159 SmallVector<Expr *, 8> PrivateCopies;
1160 for (auto *DE : Clause->varlists()) {
1161 if (DE->isValueDependent() || DE->isTypeDependent()) {
1162 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001163 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001164 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001165 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001166 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1167 QualType Type = VD->getType().getNonReferenceType();
1168 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001169 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001170 // Generate helper private variable and initialize it with the
1171 // default value. The address of the original variable is replaced
1172 // by the address of the new private variable in CodeGen. This new
1173 // variable is not added to IdResolver, so the code in the OpenMP
1174 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001175 auto *VDPrivate = buildVarDecl(
1176 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001177 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001178 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001179 if (VDPrivate->isInvalidDecl())
1180 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001181 PrivateCopies.push_back(buildDeclRefExpr(
1182 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001183 } else {
1184 // The variable is also a firstprivate, so initialization sequence
1185 // for private copy is generated already.
1186 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001187 }
1188 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001189 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001190 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001191 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001192 }
1193 }
1194 }
1195
Alexey Bataev758e55e2013-09-06 18:03:48 +00001196 DSAStack->pop();
1197 DiscardCleanupsInEvaluationContext();
1198 PopExpressionEvaluationContext();
1199}
1200
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001201static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1202 Expr *NumIterations, Sema &SemaRef,
1203 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001204
Alexey Bataeva769e072013-03-22 06:34:35 +00001205namespace {
1206
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001207class VarDeclFilterCCC : public CorrectionCandidateCallback {
1208private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001209 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001210
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001211public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001212 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001213 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001214 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001215 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001216 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001217 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1218 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001221 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001222};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001223
1224class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1225private:
1226 Sema &SemaRef;
1227
1228public:
1229 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1230 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1231 NamedDecl *ND = Candidate.getCorrectionDecl();
1232 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1233 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1234 SemaRef.getCurScope());
1235 }
1236 return false;
1237 }
1238};
1239
Alexey Bataeved09d242014-05-28 05:53:51 +00001240} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001241
1242ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1243 CXXScopeSpec &ScopeSpec,
1244 const DeclarationNameInfo &Id) {
1245 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1246 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1247
1248 if (Lookup.isAmbiguous())
1249 return ExprError();
1250
1251 VarDecl *VD;
1252 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001253 if (TypoCorrection Corrected = CorrectTypo(
1254 Id, LookupOrdinaryName, CurScope, nullptr,
1255 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001256 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001257 PDiag(Lookup.empty()
1258 ? diag::err_undeclared_var_use_suggest
1259 : diag::err_omp_expected_var_arg_suggest)
1260 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001261 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001262 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001263 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1264 : diag::err_omp_expected_var_arg)
1265 << Id.getName();
1266 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001267 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001268 } else {
1269 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001270 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001271 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1272 return ExprError();
1273 }
1274 }
1275 Lookup.suppressDiagnostics();
1276
1277 // OpenMP [2.9.2, Syntax, C/C++]
1278 // Variables must be file-scope, namespace-scope, or static block-scope.
1279 if (!VD->hasGlobalStorage()) {
1280 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001281 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1282 bool IsDecl =
1283 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001284 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001285 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1286 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001287 return ExprError();
1288 }
1289
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001290 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1291 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001292 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1293 // A threadprivate directive for file-scope variables must appear outside
1294 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001295 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1296 !getCurLexicalContext()->isTranslationUnit()) {
1297 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001298 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1299 bool IsDecl =
1300 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1301 Diag(VD->getLocation(),
1302 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1303 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001304 return ExprError();
1305 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001306 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1307 // A threadprivate directive for static class member variables must appear
1308 // in the class definition, in the same scope in which the member
1309 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001310 if (CanonicalVD->isStaticDataMember() &&
1311 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1312 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001313 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1314 bool IsDecl =
1315 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1316 Diag(VD->getLocation(),
1317 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1318 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001319 return ExprError();
1320 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001321 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1322 // A threadprivate directive for namespace-scope variables must appear
1323 // outside any definition or declaration other than the namespace
1324 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001325 if (CanonicalVD->getDeclContext()->isNamespace() &&
1326 (!getCurLexicalContext()->isFileContext() ||
1327 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1328 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001329 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1330 bool IsDecl =
1331 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1332 Diag(VD->getLocation(),
1333 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1334 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001335 return ExprError();
1336 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001337 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1338 // A threadprivate directive for static block-scope variables must appear
1339 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001340 if (CanonicalVD->isStaticLocal() && CurScope &&
1341 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001342 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001343 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1344 bool IsDecl =
1345 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1346 Diag(VD->getLocation(),
1347 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1348 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001349 return ExprError();
1350 }
1351
1352 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1353 // A threadprivate directive must lexically precede all references to any
1354 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001355 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001356 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001357 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001358 return ExprError();
1359 }
1360
1361 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001362 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1363 SourceLocation(), VD,
1364 /*RefersToEnclosingVariableOrCapture=*/false,
1365 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001366}
1367
Alexey Bataeved09d242014-05-28 05:53:51 +00001368Sema::DeclGroupPtrTy
1369Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1370 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001371 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001372 CurContext->addDecl(D);
1373 return DeclGroupPtrTy::make(DeclGroupRef(D));
1374 }
David Blaikie0403cb12016-01-15 23:43:25 +00001375 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001376}
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378namespace {
1379class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1380 Sema &SemaRef;
1381
1382public:
1383 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001384 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001385 if (VD->hasLocalStorage()) {
1386 SemaRef.Diag(E->getLocStart(),
1387 diag::err_omp_local_var_in_threadprivate_init)
1388 << E->getSourceRange();
1389 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1390 << VD << VD->getSourceRange();
1391 return true;
1392 }
1393 }
1394 return false;
1395 }
1396 bool VisitStmt(const Stmt *S) {
1397 for (auto Child : S->children()) {
1398 if (Child && Visit(Child))
1399 return true;
1400 }
1401 return false;
1402 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001403 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001404};
1405} // namespace
1406
Alexey Bataeved09d242014-05-28 05:53:51 +00001407OMPThreadPrivateDecl *
1408Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001409 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001410 for (auto &RefExpr : VarList) {
1411 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001412 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1413 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001414
Alexey Bataev376b4a42016-02-09 09:41:09 +00001415 // Mark variable as used.
1416 VD->setReferenced();
1417 VD->markUsed(Context);
1418
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001419 QualType QType = VD->getType();
1420 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1421 // It will be analyzed later.
1422 Vars.push_back(DE);
1423 continue;
1424 }
1425
Alexey Bataeva769e072013-03-22 06:34:35 +00001426 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1427 // A threadprivate variable must not have an incomplete type.
1428 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001429 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001430 continue;
1431 }
1432
1433 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1434 // A threadprivate variable must not have a reference type.
1435 if (VD->getType()->isReferenceType()) {
1436 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001437 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1438 bool IsDecl =
1439 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1440 Diag(VD->getLocation(),
1441 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1442 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001443 continue;
1444 }
1445
Samuel Antaof8b50122015-07-13 22:54:53 +00001446 // Check if this is a TLS variable. If TLS is not being supported, produce
1447 // the corresponding diagnostic.
1448 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1449 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1450 getLangOpts().OpenMPUseTLS &&
1451 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001452 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1453 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001454 Diag(ILoc, diag::err_omp_var_thread_local)
1455 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001456 bool IsDecl =
1457 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1458 Diag(VD->getLocation(),
1459 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1460 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001461 continue;
1462 }
1463
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001464 // Check if initial value of threadprivate variable reference variable with
1465 // local storage (it is not supported by runtime).
1466 if (auto Init = VD->getAnyInitializer()) {
1467 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001468 if (Checker.Visit(Init))
1469 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001470 }
1471
Alexey Bataeved09d242014-05-28 05:53:51 +00001472 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001473 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001474 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1475 Context, SourceRange(Loc, Loc)));
1476 if (auto *ML = Context.getASTMutationListener())
1477 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001478 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001479 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001480 if (!Vars.empty()) {
1481 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1482 Vars);
1483 D->setAccess(AS_public);
1484 }
1485 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001486}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001487
Alexey Bataev7ff55242014-06-19 09:13:45 +00001488static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001489 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001490 bool IsLoopIterVar = false) {
1491 if (DVar.RefExpr) {
1492 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1493 << getOpenMPClauseName(DVar.CKind);
1494 return;
1495 }
1496 enum {
1497 PDSA_StaticMemberShared,
1498 PDSA_StaticLocalVarShared,
1499 PDSA_LoopIterVarPrivate,
1500 PDSA_LoopIterVarLinear,
1501 PDSA_LoopIterVarLastprivate,
1502 PDSA_ConstVarShared,
1503 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001504 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001505 PDSA_LocalVarPrivate,
1506 PDSA_Implicit
1507 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001509 auto ReportLoc = D->getLocation();
1510 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001511 if (IsLoopIterVar) {
1512 if (DVar.CKind == OMPC_private)
1513 Reason = PDSA_LoopIterVarPrivate;
1514 else if (DVar.CKind == OMPC_lastprivate)
1515 Reason = PDSA_LoopIterVarLastprivate;
1516 else
1517 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001518 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1519 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001520 Reason = PDSA_TaskVarFirstprivate;
1521 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001522 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001523 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001525 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001526 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001527 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001528 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001529 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001530 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001531 ReportHint = true;
1532 Reason = PDSA_LocalVarPrivate;
1533 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001534 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001535 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001536 << Reason << ReportHint
1537 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1538 } else if (DVar.ImplicitDSALoc.isValid()) {
1539 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1540 << getOpenMPClauseName(DVar.CKind);
1541 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001542}
1543
Alexey Bataev758e55e2013-09-06 18:03:48 +00001544namespace {
1545class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1546 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001547 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001548 bool ErrorFound;
1549 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001550 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001551 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001552
Alexey Bataev758e55e2013-09-06 18:03:48 +00001553public:
1554 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001555 if (E->isTypeDependent() || E->isValueDependent() ||
1556 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1557 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001558 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001559 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001560 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1561 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 auto DVar = Stack->getTopDSA(VD, false);
1564 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001565 if (DVar.RefExpr)
1566 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001567
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001568 auto ELoc = E->getExprLoc();
1569 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001570 // The default(none) clause requires that each variable that is referenced
1571 // in the construct, and does not have a predetermined data-sharing
1572 // attribute, must have its data-sharing attribute explicitly determined
1573 // by being listed in a data-sharing attribute clause.
1574 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001575 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001576 VarsWithInheritedDSA.count(VD) == 0) {
1577 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001578 return;
1579 }
1580
1581 // OpenMP [2.9.3.6, Restrictions, p.2]
1582 // A list item that appears in a reduction clause of the innermost
1583 // enclosing worksharing or parallel construct may not be accessed in an
1584 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001585 DVar = Stack->hasInnermostDSA(
1586 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1587 [](OpenMPDirectiveKind K) -> bool {
1588 return isOpenMPParallelDirective(K) ||
1589 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1590 },
1591 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001592 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001593 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001594 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1595 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001596 return;
1597 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001598
1599 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001600 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001601 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1602 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001603 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001604 }
1605 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001606 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001607 if (E->isTypeDependent() || E->isValueDependent() ||
1608 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1609 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001610 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1611 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1612 auto DVar = Stack->getTopDSA(FD, false);
1613 // Check if the variable has explicit DSA set and stop analysis if it
1614 // so.
1615 if (DVar.RefExpr)
1616 return;
1617
1618 auto ELoc = E->getExprLoc();
1619 auto DKind = Stack->getCurrentDirective();
1620 // OpenMP [2.9.3.6, Restrictions, p.2]
1621 // A list item that appears in a reduction clause of the innermost
1622 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001623 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001624 DVar = Stack->hasInnermostDSA(
1625 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1626 [](OpenMPDirectiveKind K) -> bool {
1627 return isOpenMPParallelDirective(K) ||
1628 isOpenMPWorksharingDirective(K) ||
1629 isOpenMPTeamsDirective(K);
1630 },
1631 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001632 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001633 ErrorFound = true;
1634 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1635 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1636 return;
1637 }
1638
1639 // Define implicit data-sharing attributes for task.
1640 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001641 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1642 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001643 ImplicitFirstprivate.push_back(E);
1644 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001645 } else
1646 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001647 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001648 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001649 for (auto *C : S->clauses()) {
1650 // Skip analysis of arguments of implicitly defined firstprivate clause
1651 // for task directives.
1652 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1653 for (auto *CC : C->children()) {
1654 if (CC)
1655 Visit(CC);
1656 }
1657 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001658 }
1659 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001660 for (auto *C : S->children()) {
1661 if (C && !isa<OMPExecutableDirective>(C))
1662 Visit(C);
1663 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001664 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001665
1666 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001667 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001668 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001669 return VarsWithInheritedDSA;
1670 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001671
Alexey Bataev7ff55242014-06-19 09:13:45 +00001672 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1673 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001674};
Alexey Bataeved09d242014-05-28 05:53:51 +00001675} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001676
Alexey Bataevbae9a792014-06-27 10:37:06 +00001677void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001678 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001679 case OMPD_parallel:
1680 case OMPD_parallel_for:
1681 case OMPD_parallel_for_simd:
1682 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001683 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001684 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001685 QualType KmpInt32PtrTy =
1686 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001687 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001688 std::make_pair(".global_tid.", KmpInt32PtrTy),
1689 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1690 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001691 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001692 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1693 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001694 break;
1695 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001696 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001697 case OMPD_target_parallel: {
1698 Sema::CapturedParamNameType ParamsTarget[] = {
1699 std::make_pair(StringRef(), QualType()) // __context with shared vars
1700 };
1701 // Start a captured region for 'target' with no implicit parameters.
1702 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1703 ParamsTarget);
1704 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1705 QualType KmpInt32PtrTy =
1706 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001707 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001708 std::make_pair(".global_tid.", KmpInt32PtrTy),
1709 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1710 std::make_pair(StringRef(), QualType()) // __context with shared vars
1711 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001712 // Start a captured region for 'teams' or 'parallel'. Both regions have
1713 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001714 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001715 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001716 break;
1717 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001718 case OMPD_simd:
1719 case OMPD_for:
1720 case OMPD_for_simd:
1721 case OMPD_sections:
1722 case OMPD_section:
1723 case OMPD_single:
1724 case OMPD_master:
1725 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001726 case OMPD_taskgroup:
1727 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001728 case OMPD_ordered:
1729 case OMPD_atomic:
1730 case OMPD_target_data:
1731 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001732 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001733 case OMPD_target_parallel_for_simd:
1734 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001735 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001736 std::make_pair(StringRef(), QualType()) // __context with shared vars
1737 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001738 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1739 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001740 break;
1741 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001742 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001743 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001744 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1745 FunctionProtoType::ExtProtoInfo EPI;
1746 EPI.Variadic = true;
1747 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001748 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001749 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001750 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1751 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1752 std::make_pair(".copy_fn.",
1753 Context.getPointerType(CopyFnType).withConst()),
1754 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001755 std::make_pair(StringRef(), QualType()) // __context with shared vars
1756 };
1757 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1758 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001759 // Mark this captured region as inlined, because we don't use outlined
1760 // function directly.
1761 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1762 AlwaysInlineAttr::CreateImplicit(
1763 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001764 break;
1765 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001766 case OMPD_taskloop:
1767 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001768 QualType KmpInt32Ty =
1769 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1770 QualType KmpUInt64Ty =
1771 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1772 QualType KmpInt64Ty =
1773 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1774 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1775 FunctionProtoType::ExtProtoInfo EPI;
1776 EPI.Variadic = true;
1777 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001778 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001779 std::make_pair(".global_tid.", KmpInt32Ty),
1780 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1781 std::make_pair(".privates.",
1782 Context.VoidPtrTy.withConst().withRestrict()),
1783 std::make_pair(
1784 ".copy_fn.",
1785 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1786 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1787 std::make_pair(".lb.", KmpUInt64Ty),
1788 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1789 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001790 std::make_pair(StringRef(), QualType()) // __context with shared vars
1791 };
1792 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1793 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001794 // Mark this captured region as inlined, because we don't use outlined
1795 // function directly.
1796 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1797 AlwaysInlineAttr::CreateImplicit(
1798 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001799 break;
1800 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001801 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001802 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001803 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001804 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001805 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001806 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001807 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001808 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001809 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001810 case OMPD_target_teams_distribute_parallel_for_simd:
1811 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001812 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1813 QualType KmpInt32PtrTy =
1814 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1815 Sema::CapturedParamNameType Params[] = {
1816 std::make_pair(".global_tid.", KmpInt32PtrTy),
1817 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1818 std::make_pair(".previous.lb.", Context.getSizeType()),
1819 std::make_pair(".previous.ub.", Context.getSizeType()),
1820 std::make_pair(StringRef(), QualType()) // __context with shared vars
1821 };
1822 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1823 Params);
1824 break;
1825 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001826 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001827 case OMPD_taskyield:
1828 case OMPD_barrier:
1829 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001830 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001831 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001832 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001833 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001834 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001835 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001836 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001837 case OMPD_declare_target:
1838 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001839 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001840 llvm_unreachable("OpenMP Directive is not allowed");
1841 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001842 llvm_unreachable("Unknown OpenMP directive");
1843 }
1844}
1845
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001846int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1847 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1848 getOpenMPCaptureRegions(CaptureRegions, DKind);
1849 return CaptureRegions.size();
1850}
1851
Alexey Bataev3392d762016-02-16 11:18:12 +00001852static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001853 Expr *CaptureExpr, bool WithInit,
1854 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001855 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001856 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001857 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001858 QualType Ty = Init->getType();
1859 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1860 if (S.getLangOpts().CPlusPlus)
1861 Ty = C.getLValueReferenceType(Ty);
1862 else {
1863 Ty = C.getPointerType(Ty);
1864 ExprResult Res =
1865 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1866 if (!Res.isUsable())
1867 return nullptr;
1868 Init = Res.get();
1869 }
Alexey Bataev61205072016-03-02 04:57:40 +00001870 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001871 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001872 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1873 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001874 if (!WithInit)
1875 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001876 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001877 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001878 return CED;
1879}
1880
Alexey Bataev61205072016-03-02 04:57:40 +00001881static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1882 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001883 OMPCapturedExprDecl *CD;
1884 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1885 CD = cast<OMPCapturedExprDecl>(VD);
1886 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001887 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1888 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001889 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001890 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001891}
1892
Alexey Bataev5a3af132016-03-29 08:58:54 +00001893static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1894 if (!Ref) {
1895 auto *CD =
1896 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1897 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1898 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1899 CaptureExpr->getExprLoc());
1900 }
1901 ExprResult Res = Ref;
1902 if (!S.getLangOpts().CPlusPlus &&
1903 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1904 Ref->getType()->isPointerType())
1905 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1906 if (!Res.isUsable())
1907 return ExprError();
1908 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001909}
1910
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001911namespace {
1912// OpenMP directives parsed in this section are represented as a
1913// CapturedStatement with an associated statement. If a syntax error
1914// is detected during the parsing of the associated statement, the
1915// compiler must abort processing and close the CapturedStatement.
1916//
1917// Combined directives such as 'target parallel' have more than one
1918// nested CapturedStatements. This RAII ensures that we unwind out
1919// of all the nested CapturedStatements when an error is found.
1920class CaptureRegionUnwinderRAII {
1921private:
1922 Sema &S;
1923 bool &ErrorFound;
1924 OpenMPDirectiveKind DKind;
1925
1926public:
1927 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1928 OpenMPDirectiveKind DKind)
1929 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1930 ~CaptureRegionUnwinderRAII() {
1931 if (ErrorFound) {
1932 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1933 while (--ThisCaptureLevel >= 0)
1934 S.ActOnCapturedRegionError();
1935 }
1936 }
1937};
1938} // namespace
1939
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001940StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1941 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001942 bool ErrorFound = false;
1943 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1944 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001945 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001946 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001947 return StmtError();
1948 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001949
1950 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001951 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001952 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001953 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001954 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001955 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001956 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001957 Clause->getClauseKind() == OMPC_copyprivate ||
1958 (getLangOpts().OpenMPUseTLS &&
1959 getASTContext().getTargetInfo().isTLSSupported() &&
1960 Clause->getClauseKind() == OMPC_copyin)) {
1961 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001962 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001963 for (auto *VarRef : Clause->children()) {
1964 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001965 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001966 }
1967 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001968 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001969 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001970 if (auto *C = OMPClauseWithPreInit::get(Clause))
1971 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001972 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1973 if (auto *E = C->getPostUpdateExpr())
1974 MarkDeclarationsReferencedInExpr(E);
1975 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001976 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001977 if (Clause->getClauseKind() == OMPC_schedule)
1978 SC = cast<OMPScheduleClause>(Clause);
1979 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001980 OC = cast<OMPOrderedClause>(Clause);
1981 else if (Clause->getClauseKind() == OMPC_linear)
1982 LCs.push_back(cast<OMPLinearClause>(Clause));
1983 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001984 // OpenMP, 2.7.1 Loop Construct, Restrictions
1985 // The nonmonotonic modifier cannot be specified if an ordered clause is
1986 // specified.
1987 if (SC &&
1988 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1989 SC->getSecondScheduleModifier() ==
1990 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1991 OC) {
1992 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1993 ? SC->getFirstScheduleModifierLoc()
1994 : SC->getSecondScheduleModifierLoc(),
1995 diag::err_omp_schedule_nonmonotonic_ordered)
1996 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1997 ErrorFound = true;
1998 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001999 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2000 for (auto *C : LCs) {
2001 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2002 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2003 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002004 ErrorFound = true;
2005 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002006 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2007 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2008 OC->getNumForLoops()) {
2009 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2010 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2011 ErrorFound = true;
2012 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002013 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002014 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002015 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002016 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002017 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2018 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2019 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2020 // Mark all variables in private list clauses as used in inner region.
2021 // Required for proper codegen of combined directives.
2022 // TODO: add processing for other clauses.
2023 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2024 for (auto *C : PICs) {
2025 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2026 // Find the particular capture region for the clause if the
2027 // directive is a combined one with multiple capture regions.
2028 // If the directive is not a combined one, the capture region
2029 // associated with the clause is OMPD_unknown and is generated
2030 // only once.
2031 if (CaptureRegion == ThisCaptureRegion ||
2032 CaptureRegion == OMPD_unknown) {
2033 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2034 for (auto *D : DS->decls())
2035 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2036 }
2037 }
2038 }
2039 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002040 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002041 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002042 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002043}
2044
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002045static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2046 OpenMPDirectiveKind CancelRegion,
2047 SourceLocation StartLoc) {
2048 // CancelRegion is only needed for cancel and cancellation_point.
2049 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2050 return false;
2051
2052 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2053 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2054 return false;
2055
2056 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2057 << getOpenMPDirectiveName(CancelRegion);
2058 return true;
2059}
2060
2061static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002062 OpenMPDirectiveKind CurrentRegion,
2063 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002064 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002065 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002066 if (Stack->getCurScope()) {
2067 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002068 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002069 bool NestingProhibited = false;
2070 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002071 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002072 enum {
2073 NoRecommend,
2074 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002075 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002076 ShouldBeInTargetRegion,
2077 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002078 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002079 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002080 // OpenMP [2.16, Nesting of Regions]
2081 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002082 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002083 // An ordered construct with the simd clause is the only OpenMP
2084 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002085 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002086 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2087 // message.
2088 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2089 ? diag::err_omp_prohibited_region_simd
2090 : diag::warn_omp_nesting_simd);
2091 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002092 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002093 if (ParentRegion == OMPD_atomic) {
2094 // OpenMP [2.16, Nesting of Regions]
2095 // OpenMP constructs may not be nested inside an atomic region.
2096 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2097 return true;
2098 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002099 if (CurrentRegion == OMPD_section) {
2100 // OpenMP [2.7.2, sections Construct, Restrictions]
2101 // Orphaned section directives are prohibited. That is, the section
2102 // directives must appear within the sections construct and must not be
2103 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002104 if (ParentRegion != OMPD_sections &&
2105 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002106 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2107 << (ParentRegion != OMPD_unknown)
2108 << getOpenMPDirectiveName(ParentRegion);
2109 return true;
2110 }
2111 return false;
2112 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002113 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002114 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002115 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002116 if (ParentRegion == OMPD_unknown &&
2117 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002118 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002119 if (CurrentRegion == OMPD_cancellation_point ||
2120 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002121 // OpenMP [2.16, Nesting of Regions]
2122 // A cancellation point construct for which construct-type-clause is
2123 // taskgroup must be nested inside a task construct. A cancellation
2124 // point construct for which construct-type-clause is not taskgroup must
2125 // be closely nested inside an OpenMP construct that matches the type
2126 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002127 // A cancel construct for which construct-type-clause is taskgroup must be
2128 // nested inside a task construct. A cancel construct for which
2129 // construct-type-clause is not taskgroup must be closely nested inside an
2130 // OpenMP construct that matches the type specified in
2131 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002132 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002133 !((CancelRegion == OMPD_parallel &&
2134 (ParentRegion == OMPD_parallel ||
2135 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002136 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002137 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2138 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002139 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2140 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002141 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2142 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002143 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002144 // OpenMP [2.16, Nesting of Regions]
2145 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002146 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002147 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002148 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002149 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2150 // OpenMP [2.16, Nesting of Regions]
2151 // A critical region may not be nested (closely or otherwise) inside a
2152 // critical region with the same name. Note that this restriction is not
2153 // sufficient to prevent deadlock.
2154 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002155 bool DeadLock = Stack->hasDirective(
2156 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2157 const DeclarationNameInfo &DNI,
2158 SourceLocation Loc) -> bool {
2159 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2160 PreviousCriticalLoc = Loc;
2161 return true;
2162 } else
2163 return false;
2164 },
2165 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002166 if (DeadLock) {
2167 SemaRef.Diag(StartLoc,
2168 diag::err_omp_prohibited_region_critical_same_name)
2169 << CurrentName.getName();
2170 if (PreviousCriticalLoc.isValid())
2171 SemaRef.Diag(PreviousCriticalLoc,
2172 diag::note_omp_previous_critical_region);
2173 return true;
2174 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002175 } else if (CurrentRegion == OMPD_barrier) {
2176 // OpenMP [2.16, Nesting of Regions]
2177 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002178 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002179 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2180 isOpenMPTaskingDirective(ParentRegion) ||
2181 ParentRegion == OMPD_master ||
2182 ParentRegion == OMPD_critical ||
2183 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002184 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002185 !isOpenMPParallelDirective(CurrentRegion) &&
2186 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002187 // OpenMP [2.16, Nesting of Regions]
2188 // A worksharing region may not be closely nested inside a worksharing,
2189 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002190 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2191 isOpenMPTaskingDirective(ParentRegion) ||
2192 ParentRegion == OMPD_master ||
2193 ParentRegion == OMPD_critical ||
2194 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002195 Recommend = ShouldBeInParallelRegion;
2196 } else if (CurrentRegion == OMPD_ordered) {
2197 // OpenMP [2.16, Nesting of Regions]
2198 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002199 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002200 // An ordered region must be closely nested inside a loop region (or
2201 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002202 // OpenMP [2.8.1,simd Construct, Restrictions]
2203 // An ordered construct with the simd clause is the only OpenMP construct
2204 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002205 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002206 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002207 !(isOpenMPSimdDirective(ParentRegion) ||
2208 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002209 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002210 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002211 // OpenMP [2.16, Nesting of Regions]
2212 // If specified, a teams construct must be contained within a target
2213 // construct.
2214 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002215 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002216 Recommend = ShouldBeInTargetRegion;
2217 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2218 }
Kelvin Libf594a52016-12-17 05:48:59 +00002219 if (!NestingProhibited &&
2220 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2221 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2222 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002223 // OpenMP [2.16, Nesting of Regions]
2224 // distribute, parallel, parallel sections, parallel workshare, and the
2225 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2226 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002227 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2228 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002229 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002230 }
David Majnemer9d168222016-08-05 17:44:54 +00002231 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002232 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002233 // OpenMP 4.5 [2.17 Nesting of Regions]
2234 // The region associated with the distribute construct must be strictly
2235 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002236 NestingProhibited =
2237 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002238 Recommend = ShouldBeInTeamsRegion;
2239 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002240 if (!NestingProhibited &&
2241 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2242 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2243 // OpenMP 4.5 [2.17 Nesting of Regions]
2244 // If a target, target update, target data, target enter data, or
2245 // target exit data construct is encountered during execution of a
2246 // target region, the behavior is unspecified.
2247 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002248 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2249 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002250 if (isOpenMPTargetExecutionDirective(K)) {
2251 OffendingRegion = K;
2252 return true;
2253 } else
2254 return false;
2255 },
2256 false /* don't skip top directive */);
2257 CloseNesting = false;
2258 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002259 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002260 if (OrphanSeen) {
2261 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2262 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2263 } else {
2264 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2265 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2266 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2267 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002268 return true;
2269 }
2270 }
2271 return false;
2272}
2273
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002274static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2275 ArrayRef<OMPClause *> Clauses,
2276 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2277 bool ErrorFound = false;
2278 unsigned NamedModifiersNumber = 0;
2279 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2280 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002281 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002282 for (const auto *C : Clauses) {
2283 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2284 // At most one if clause without a directive-name-modifier can appear on
2285 // the directive.
2286 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2287 if (FoundNameModifiers[CurNM]) {
2288 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2289 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2290 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2291 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002292 } else if (CurNM != OMPD_unknown) {
2293 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002294 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002295 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002296 FoundNameModifiers[CurNM] = IC;
2297 if (CurNM == OMPD_unknown)
2298 continue;
2299 // Check if the specified name modifier is allowed for the current
2300 // directive.
2301 // At most one if clause with the particular directive-name-modifier can
2302 // appear on the directive.
2303 bool MatchFound = false;
2304 for (auto NM : AllowedNameModifiers) {
2305 if (CurNM == NM) {
2306 MatchFound = true;
2307 break;
2308 }
2309 }
2310 if (!MatchFound) {
2311 S.Diag(IC->getNameModifierLoc(),
2312 diag::err_omp_wrong_if_directive_name_modifier)
2313 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2314 ErrorFound = true;
2315 }
2316 }
2317 }
2318 // If any if clause on the directive includes a directive-name-modifier then
2319 // all if clauses on the directive must include a directive-name-modifier.
2320 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2321 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2322 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2323 diag::err_omp_no_more_if_clause);
2324 } else {
2325 std::string Values;
2326 std::string Sep(", ");
2327 unsigned AllowedCnt = 0;
2328 unsigned TotalAllowedNum =
2329 AllowedNameModifiers.size() - NamedModifiersNumber;
2330 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2331 ++Cnt) {
2332 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2333 if (!FoundNameModifiers[NM]) {
2334 Values += "'";
2335 Values += getOpenMPDirectiveName(NM);
2336 Values += "'";
2337 if (AllowedCnt + 2 == TotalAllowedNum)
2338 Values += " or ";
2339 else if (AllowedCnt + 1 != TotalAllowedNum)
2340 Values += Sep;
2341 ++AllowedCnt;
2342 }
2343 }
2344 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2345 diag::err_omp_unnamed_if_clause)
2346 << (TotalAllowedNum > 1) << Values;
2347 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002348 for (auto Loc : NameModifierLoc) {
2349 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2350 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002351 ErrorFound = true;
2352 }
2353 return ErrorFound;
2354}
2355
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002356StmtResult Sema::ActOnOpenMPExecutableDirective(
2357 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2358 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2359 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002360 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002361 // First check CancelRegion which is then used in checkNestingOfRegions.
2362 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2363 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002364 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002365 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002366
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002367 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002368 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002369 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002370 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002371 if (AStmt) {
2372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2373
2374 // Check default data sharing attributes for referenced variables.
2375 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002376 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2377 Stmt *S = AStmt;
2378 while (--ThisCaptureLevel >= 0)
2379 S = cast<CapturedStmt>(S)->getCapturedStmt();
2380 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002381 if (DSAChecker.isErrorFound())
2382 return StmtError();
2383 // Generate list of implicitly defined firstprivate variables.
2384 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002385
2386 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2387 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2388 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2389 SourceLocation(), SourceLocation())) {
2390 ClausesWithImplicit.push_back(Implicit);
2391 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2392 DSAChecker.getImplicitFirstprivate().size();
2393 } else
2394 ErrorFound = true;
2395 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002396 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002397
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002398 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002399 switch (Kind) {
2400 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002401 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2402 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002403 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002404 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002405 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002406 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2407 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002408 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002409 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002410 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2411 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002412 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002413 case OMPD_for_simd:
2414 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2415 EndLoc, VarsWithInheritedDSA);
2416 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002417 case OMPD_sections:
2418 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2419 EndLoc);
2420 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002421 case OMPD_section:
2422 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002423 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002424 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2425 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002426 case OMPD_single:
2427 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2428 EndLoc);
2429 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002430 case OMPD_master:
2431 assert(ClausesWithImplicit.empty() &&
2432 "No clauses are allowed for 'omp master' directive");
2433 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2434 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002435 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002436 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2437 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002438 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002439 case OMPD_parallel_for:
2440 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2441 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002442 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002443 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002444 case OMPD_parallel_for_simd:
2445 Res = ActOnOpenMPParallelForSimdDirective(
2446 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002447 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002448 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002449 case OMPD_parallel_sections:
2450 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2451 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002452 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002453 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002454 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002455 Res =
2456 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002457 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002458 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002459 case OMPD_taskyield:
2460 assert(ClausesWithImplicit.empty() &&
2461 "No clauses are allowed for 'omp taskyield' directive");
2462 assert(AStmt == nullptr &&
2463 "No associated statement allowed for 'omp taskyield' directive");
2464 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2465 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002466 case OMPD_barrier:
2467 assert(ClausesWithImplicit.empty() &&
2468 "No clauses are allowed for 'omp barrier' directive");
2469 assert(AStmt == nullptr &&
2470 "No associated statement allowed for 'omp barrier' directive");
2471 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2472 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002473 case OMPD_taskwait:
2474 assert(ClausesWithImplicit.empty() &&
2475 "No clauses are allowed for 'omp taskwait' directive");
2476 assert(AStmt == nullptr &&
2477 "No associated statement allowed for 'omp taskwait' directive");
2478 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2479 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002480 case OMPD_taskgroup:
2481 assert(ClausesWithImplicit.empty() &&
2482 "No clauses are allowed for 'omp taskgroup' directive");
2483 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2484 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002485 case OMPD_flush:
2486 assert(AStmt == nullptr &&
2487 "No associated statement allowed for 'omp flush' directive");
2488 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2489 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002490 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002491 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2492 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002493 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002494 case OMPD_atomic:
2495 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2496 EndLoc);
2497 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002498 case OMPD_teams:
2499 Res =
2500 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2501 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002502 case OMPD_target:
2503 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2504 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002505 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002506 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002507 case OMPD_target_parallel:
2508 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2509 StartLoc, EndLoc);
2510 AllowedNameModifiers.push_back(OMPD_target);
2511 AllowedNameModifiers.push_back(OMPD_parallel);
2512 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002513 case OMPD_target_parallel_for:
2514 Res = ActOnOpenMPTargetParallelForDirective(
2515 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2516 AllowedNameModifiers.push_back(OMPD_target);
2517 AllowedNameModifiers.push_back(OMPD_parallel);
2518 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002519 case OMPD_cancellation_point:
2520 assert(ClausesWithImplicit.empty() &&
2521 "No clauses are allowed for 'omp cancellation point' directive");
2522 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2523 "cancellation point' directive");
2524 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2525 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002526 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002527 assert(AStmt == nullptr &&
2528 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002529 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2530 CancelRegion);
2531 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002532 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002533 case OMPD_target_data:
2534 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2535 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002536 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002537 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002538 case OMPD_target_enter_data:
2539 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2540 EndLoc);
2541 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2542 break;
Samuel Antao72590762016-01-19 20:04:50 +00002543 case OMPD_target_exit_data:
2544 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2545 EndLoc);
2546 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2547 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002548 case OMPD_taskloop:
2549 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2550 EndLoc, VarsWithInheritedDSA);
2551 AllowedNameModifiers.push_back(OMPD_taskloop);
2552 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002553 case OMPD_taskloop_simd:
2554 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2555 EndLoc, VarsWithInheritedDSA);
2556 AllowedNameModifiers.push_back(OMPD_taskloop);
2557 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002558 case OMPD_distribute:
2559 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2560 EndLoc, VarsWithInheritedDSA);
2561 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002562 case OMPD_target_update:
2563 assert(!AStmt && "Statement is not allowed for target update");
2564 Res =
2565 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2566 AllowedNameModifiers.push_back(OMPD_target_update);
2567 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002568 case OMPD_distribute_parallel_for:
2569 Res = ActOnOpenMPDistributeParallelForDirective(
2570 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2571 AllowedNameModifiers.push_back(OMPD_parallel);
2572 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002573 case OMPD_distribute_parallel_for_simd:
2574 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2575 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2576 AllowedNameModifiers.push_back(OMPD_parallel);
2577 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002578 case OMPD_distribute_simd:
2579 Res = ActOnOpenMPDistributeSimdDirective(
2580 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2581 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002582 case OMPD_target_parallel_for_simd:
2583 Res = ActOnOpenMPTargetParallelForSimdDirective(
2584 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2585 AllowedNameModifiers.push_back(OMPD_target);
2586 AllowedNameModifiers.push_back(OMPD_parallel);
2587 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002588 case OMPD_target_simd:
2589 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2590 EndLoc, VarsWithInheritedDSA);
2591 AllowedNameModifiers.push_back(OMPD_target);
2592 break;
Kelvin Li02532872016-08-05 14:37:37 +00002593 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002594 Res = ActOnOpenMPTeamsDistributeDirective(
2595 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002596 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002597 case OMPD_teams_distribute_simd:
2598 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2599 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2600 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002601 case OMPD_teams_distribute_parallel_for_simd:
2602 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2603 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2604 AllowedNameModifiers.push_back(OMPD_parallel);
2605 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002606 case OMPD_teams_distribute_parallel_for:
2607 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2608 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2609 AllowedNameModifiers.push_back(OMPD_parallel);
2610 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002611 case OMPD_target_teams:
2612 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2613 EndLoc);
2614 AllowedNameModifiers.push_back(OMPD_target);
2615 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002616 case OMPD_target_teams_distribute:
2617 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2618 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2619 AllowedNameModifiers.push_back(OMPD_target);
2620 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002621 case OMPD_target_teams_distribute_parallel_for:
2622 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2623 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2624 AllowedNameModifiers.push_back(OMPD_target);
2625 AllowedNameModifiers.push_back(OMPD_parallel);
2626 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002627 case OMPD_target_teams_distribute_parallel_for_simd:
2628 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2629 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2630 AllowedNameModifiers.push_back(OMPD_target);
2631 AllowedNameModifiers.push_back(OMPD_parallel);
2632 break;
Kelvin Lida681182017-01-10 18:08:18 +00002633 case OMPD_target_teams_distribute_simd:
2634 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2635 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2636 AllowedNameModifiers.push_back(OMPD_target);
2637 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002638 case OMPD_declare_target:
2639 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002640 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002641 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002642 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002643 llvm_unreachable("OpenMP Directive is not allowed");
2644 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002645 llvm_unreachable("Unknown OpenMP directive");
2646 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002647
Alexey Bataev4acb8592014-07-07 13:01:15 +00002648 for (auto P : VarsWithInheritedDSA) {
2649 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2650 << P.first << P.second->getSourceRange();
2651 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002652 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2653
2654 if (!AllowedNameModifiers.empty())
2655 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2656 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002657
Alexey Bataeved09d242014-05-28 05:53:51 +00002658 if (ErrorFound)
2659 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002660 return Res;
2661}
2662
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002663Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2664 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002665 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002666 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2667 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002668 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002669 assert(Linears.size() == LinModifiers.size());
2670 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002671 if (!DG || DG.get().isNull())
2672 return DeclGroupPtrTy();
2673
2674 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002675 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002676 return DG;
2677 }
2678 auto *ADecl = DG.get().getSingleDecl();
2679 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2680 ADecl = FTD->getTemplatedDecl();
2681
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002682 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2683 if (!FD) {
2684 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002685 return DeclGroupPtrTy();
2686 }
2687
Alexey Bataev2af33e32016-04-07 12:45:37 +00002688 // OpenMP [2.8.2, declare simd construct, Description]
2689 // The parameter of the simdlen clause must be a constant positive integer
2690 // expression.
2691 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002692 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002693 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002694 // OpenMP [2.8.2, declare simd construct, Description]
2695 // The special this pointer can be used as if was one of the arguments to the
2696 // function in any of the linear, aligned, or uniform clauses.
2697 // The uniform clause declares one or more arguments to have an invariant
2698 // value for all concurrent invocations of the function in the execution of a
2699 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002700 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2701 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002702 for (auto *E : Uniforms) {
2703 E = E->IgnoreParenImpCasts();
2704 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2705 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2706 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2707 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002708 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2709 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002710 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002711 }
2712 if (isa<CXXThisExpr>(E)) {
2713 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002714 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002715 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002716 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2717 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002718 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002719 // OpenMP [2.8.2, declare simd construct, Description]
2720 // The aligned clause declares that the object to which each list item points
2721 // is aligned to the number of bytes expressed in the optional parameter of
2722 // the aligned clause.
2723 // The special this pointer can be used as if was one of the arguments to the
2724 // function in any of the linear, aligned, or uniform clauses.
2725 // The type of list items appearing in the aligned clause must be array,
2726 // pointer, reference to array, or reference to pointer.
2727 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2728 Expr *AlignedThis = nullptr;
2729 for (auto *E : Aligneds) {
2730 E = E->IgnoreParenImpCasts();
2731 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2732 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2733 auto *CanonPVD = PVD->getCanonicalDecl();
2734 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2735 FD->getParamDecl(PVD->getFunctionScopeIndex())
2736 ->getCanonicalDecl() == CanonPVD) {
2737 // OpenMP [2.8.1, simd construct, Restrictions]
2738 // A list-item cannot appear in more than one aligned clause.
2739 if (AlignedArgs.count(CanonPVD) > 0) {
2740 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2741 << 1 << E->getSourceRange();
2742 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2743 diag::note_omp_explicit_dsa)
2744 << getOpenMPClauseName(OMPC_aligned);
2745 continue;
2746 }
2747 AlignedArgs[CanonPVD] = E;
2748 QualType QTy = PVD->getType()
2749 .getNonReferenceType()
2750 .getUnqualifiedType()
2751 .getCanonicalType();
2752 const Type *Ty = QTy.getTypePtrOrNull();
2753 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2754 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2755 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2756 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2757 }
2758 continue;
2759 }
2760 }
2761 if (isa<CXXThisExpr>(E)) {
2762 if (AlignedThis) {
2763 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2764 << 2 << E->getSourceRange();
2765 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2766 << getOpenMPClauseName(OMPC_aligned);
2767 }
2768 AlignedThis = E;
2769 continue;
2770 }
2771 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2772 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2773 }
2774 // The optional parameter of the aligned clause, alignment, must be a constant
2775 // positive integer expression. If no optional parameter is specified,
2776 // implementation-defined default alignments for SIMD instructions on the
2777 // target platforms are assumed.
2778 SmallVector<Expr *, 4> NewAligns;
2779 for (auto *E : Alignments) {
2780 ExprResult Align;
2781 if (E)
2782 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2783 NewAligns.push_back(Align.get());
2784 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002785 // OpenMP [2.8.2, declare simd construct, Description]
2786 // The linear clause declares one or more list items to be private to a SIMD
2787 // lane and to have a linear relationship with respect to the iteration space
2788 // of a loop.
2789 // The special this pointer can be used as if was one of the arguments to the
2790 // function in any of the linear, aligned, or uniform clauses.
2791 // When a linear-step expression is specified in a linear clause it must be
2792 // either a constant integer expression or an integer-typed parameter that is
2793 // specified in a uniform clause on the directive.
2794 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2795 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2796 auto MI = LinModifiers.begin();
2797 for (auto *E : Linears) {
2798 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2799 ++MI;
2800 E = E->IgnoreParenImpCasts();
2801 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2802 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2803 auto *CanonPVD = PVD->getCanonicalDecl();
2804 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2805 FD->getParamDecl(PVD->getFunctionScopeIndex())
2806 ->getCanonicalDecl() == CanonPVD) {
2807 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2808 // A list-item cannot appear in more than one linear clause.
2809 if (LinearArgs.count(CanonPVD) > 0) {
2810 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2811 << getOpenMPClauseName(OMPC_linear)
2812 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2813 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2814 diag::note_omp_explicit_dsa)
2815 << getOpenMPClauseName(OMPC_linear);
2816 continue;
2817 }
2818 // Each argument can appear in at most one uniform or linear clause.
2819 if (UniformedArgs.count(CanonPVD) > 0) {
2820 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2821 << getOpenMPClauseName(OMPC_linear)
2822 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2823 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2824 diag::note_omp_explicit_dsa)
2825 << getOpenMPClauseName(OMPC_uniform);
2826 continue;
2827 }
2828 LinearArgs[CanonPVD] = E;
2829 if (E->isValueDependent() || E->isTypeDependent() ||
2830 E->isInstantiationDependent() ||
2831 E->containsUnexpandedParameterPack())
2832 continue;
2833 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2834 PVD->getOriginalType());
2835 continue;
2836 }
2837 }
2838 if (isa<CXXThisExpr>(E)) {
2839 if (UniformedLinearThis) {
2840 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2841 << getOpenMPClauseName(OMPC_linear)
2842 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2843 << E->getSourceRange();
2844 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2845 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2846 : OMPC_linear);
2847 continue;
2848 }
2849 UniformedLinearThis = E;
2850 if (E->isValueDependent() || E->isTypeDependent() ||
2851 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2852 continue;
2853 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2854 E->getType());
2855 continue;
2856 }
2857 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2858 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2859 }
2860 Expr *Step = nullptr;
2861 Expr *NewStep = nullptr;
2862 SmallVector<Expr *, 4> NewSteps;
2863 for (auto *E : Steps) {
2864 // Skip the same step expression, it was checked already.
2865 if (Step == E || !E) {
2866 NewSteps.push_back(E ? NewStep : nullptr);
2867 continue;
2868 }
2869 Step = E;
2870 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2871 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2872 auto *CanonPVD = PVD->getCanonicalDecl();
2873 if (UniformedArgs.count(CanonPVD) == 0) {
2874 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2875 << Step->getSourceRange();
2876 } else if (E->isValueDependent() || E->isTypeDependent() ||
2877 E->isInstantiationDependent() ||
2878 E->containsUnexpandedParameterPack() ||
2879 CanonPVD->getType()->hasIntegerRepresentation())
2880 NewSteps.push_back(Step);
2881 else {
2882 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2883 << Step->getSourceRange();
2884 }
2885 continue;
2886 }
2887 NewStep = Step;
2888 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2889 !Step->isInstantiationDependent() &&
2890 !Step->containsUnexpandedParameterPack()) {
2891 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2892 .get();
2893 if (NewStep)
2894 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2895 }
2896 NewSteps.push_back(NewStep);
2897 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002898 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2899 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002900 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002901 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2902 const_cast<Expr **>(Linears.data()), Linears.size(),
2903 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2904 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002905 ADecl->addAttr(NewAttr);
2906 return ConvertDeclToDeclGroup(ADecl);
2907}
2908
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002909StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2910 Stmt *AStmt,
2911 SourceLocation StartLoc,
2912 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002913 if (!AStmt)
2914 return StmtError();
2915
Alexey Bataev9959db52014-05-06 10:08:46 +00002916 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2917 // 1.2.2 OpenMP Language Terminology
2918 // Structured block - An executable statement with a single entry at the
2919 // top and a single exit at the bottom.
2920 // The point of exit cannot be a branch out of the structured block.
2921 // longjmp() and throw() must not violate the entry/exit criteria.
2922 CS->getCapturedDecl()->setNothrow();
2923
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002924 getCurFunction()->setHasBranchProtectedScope();
2925
Alexey Bataev25e5b442015-09-15 12:52:43 +00002926 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2927 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002928}
2929
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002930namespace {
2931/// \brief Helper class for checking canonical form of the OpenMP loops and
2932/// extracting iteration space of each loop in the loop nest, that will be used
2933/// for IR generation.
2934class OpenMPIterationSpaceChecker {
2935 /// \brief Reference to Sema.
2936 Sema &SemaRef;
2937 /// \brief A location for diagnostics (when there is no some better location).
2938 SourceLocation DefaultLoc;
2939 /// \brief A location for diagnostics (when increment is not compatible).
2940 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002941 /// \brief A source location for referring to loop init later.
2942 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002943 /// \brief A source location for referring to condition later.
2944 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002945 /// \brief A source location for referring to increment later.
2946 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002947 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002948 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002949 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002950 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002951 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002952 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002953 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002954 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002955 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002956 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002957 /// \brief This flag is true when condition is one of:
2958 /// Var < UB
2959 /// Var <= UB
2960 /// UB > Var
2961 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002962 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002963 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002964 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002965 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002966 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002967
2968public:
2969 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002970 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002971 /// \brief Check init-expr for canonical loop form and save loop counter
2972 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002973 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002974 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2975 /// for less/greater and for strict/non-strict comparison.
2976 bool CheckCond(Expr *S);
2977 /// \brief Check incr-expr for canonical loop form and return true if it
2978 /// does not conform, otherwise save loop step (#Step).
2979 bool CheckInc(Expr *S);
2980 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002981 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002982 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002983 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002984 /// \brief Source range of the loop init.
2985 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2986 /// \brief Source range of the loop condition.
2987 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2988 /// \brief Source range of the loop increment.
2989 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2990 /// \brief True if the step should be subtracted.
2991 bool ShouldSubtractStep() const { return SubtractStep; }
2992 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002993 Expr *
2994 BuildNumIterations(Scope *S, const bool LimitedType,
2995 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002996 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002997 Expr *BuildPreCond(Scope *S, Expr *Cond,
2998 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002999 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003000 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3001 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003002 /// \brief Build reference expression to the private counter be used for
3003 /// codegen.
3004 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003005 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003006 Expr *BuildCounterInit() const;
3007 /// \brief Build step of the counter be used for codegen.
3008 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003009 /// \brief Return true if any expression is dependent.
3010 bool Dependent() const;
3011
3012private:
3013 /// \brief Check the right-hand side of an assignment in the increment
3014 /// expression.
3015 bool CheckIncRHS(Expr *RHS);
3016 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003017 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003018 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003019 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003020 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003021 /// \brief Helper to set loop increment.
3022 bool SetStep(Expr *NewStep, bool Subtract);
3023};
3024
3025bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003026 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003027 assert(!LB && !UB && !Step);
3028 return false;
3029 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003030 return LCDecl->getType()->isDependentType() ||
3031 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3032 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003033}
3034
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003035static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003036 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3037 E = ExprTemp->getSubExpr();
3038
3039 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3040 E = MTE->GetTemporaryExpr();
3041
3042 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3043 E = Binder->getSubExpr();
3044
3045 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3046 E = ICE->getSubExprAsWritten();
3047 return E->IgnoreParens();
3048}
3049
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003050bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3051 Expr *NewLCRefExpr,
3052 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003053 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003054 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003055 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003056 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003057 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003058 LCDecl = getCanonicalDecl(NewLCDecl);
3059 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003060 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3061 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003062 if ((Ctor->isCopyOrMoveConstructor() ||
3063 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3064 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003065 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003066 LB = NewLB;
3067 return false;
3068}
3069
3070bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003071 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003072 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003073 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3074 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003075 if (!NewUB)
3076 return true;
3077 UB = NewUB;
3078 TestIsLessOp = LessOp;
3079 TestIsStrictOp = StrictOp;
3080 ConditionSrcRange = SR;
3081 ConditionLoc = SL;
3082 return false;
3083}
3084
3085bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3086 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003087 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003088 if (!NewStep)
3089 return true;
3090 if (!NewStep->isValueDependent()) {
3091 // Check that the step is integer expression.
3092 SourceLocation StepLoc = NewStep->getLocStart();
3093 ExprResult Val =
3094 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3095 if (Val.isInvalid())
3096 return true;
3097 NewStep = Val.get();
3098
3099 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3100 // If test-expr is of form var relational-op b and relational-op is < or
3101 // <= then incr-expr must cause var to increase on each iteration of the
3102 // loop. If test-expr is of form var relational-op b and relational-op is
3103 // > or >= then incr-expr must cause var to decrease on each iteration of
3104 // the loop.
3105 // If test-expr is of form b relational-op var and relational-op is < or
3106 // <= then incr-expr must cause var to decrease on each iteration of the
3107 // loop. If test-expr is of form b relational-op var and relational-op is
3108 // > or >= then incr-expr must cause var to increase on each iteration of
3109 // the loop.
3110 llvm::APSInt Result;
3111 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3112 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3113 bool IsConstNeg =
3114 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003115 bool IsConstPos =
3116 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003117 bool IsConstZero = IsConstant && !Result.getBoolValue();
3118 if (UB && (IsConstZero ||
3119 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003120 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003121 SemaRef.Diag(NewStep->getExprLoc(),
3122 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003123 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003124 SemaRef.Diag(ConditionLoc,
3125 diag::note_omp_loop_cond_requres_compatible_incr)
3126 << TestIsLessOp << ConditionSrcRange;
3127 return true;
3128 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003129 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003130 NewStep =
3131 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3132 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003133 Subtract = !Subtract;
3134 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003135 }
3136
3137 Step = NewStep;
3138 SubtractStep = Subtract;
3139 return false;
3140}
3141
Alexey Bataev9c821032015-04-30 04:23:23 +00003142bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003143 // Check init-expr for canonical loop form and save loop counter
3144 // variable - #Var and its initialization value - #LB.
3145 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3146 // var = lb
3147 // integer-type var = lb
3148 // random-access-iterator-type var = lb
3149 // pointer-type var = lb
3150 //
3151 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003152 if (EmitDiags) {
3153 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3154 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003155 return true;
3156 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003157 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3158 if (!ExprTemp->cleanupsHaveSideEffects())
3159 S = ExprTemp->getSubExpr();
3160
Alexander Musmana5f070a2014-10-01 06:03:56 +00003161 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003162 if (Expr *E = dyn_cast<Expr>(S))
3163 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003164 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003165 if (BO->getOpcode() == BO_Assign) {
3166 auto *LHS = BO->getLHS()->IgnoreParens();
3167 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3168 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3169 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3170 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3171 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3172 }
3173 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3174 if (ME->isArrow() &&
3175 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3176 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3177 }
3178 }
David Majnemer9d168222016-08-05 17:44:54 +00003179 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003180 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003181 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003182 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003183 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003184 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003185 SemaRef.Diag(S->getLocStart(),
3186 diag::ext_omp_loop_not_canonical_init)
3187 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003188 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003189 }
3190 }
3191 }
David Majnemer9d168222016-08-05 17:44:54 +00003192 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003193 if (CE->getOperator() == OO_Equal) {
3194 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003195 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003196 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3197 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3198 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3199 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3200 }
3201 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3202 if (ME->isArrow() &&
3203 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3204 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3205 }
3206 }
3207 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003208
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003209 if (Dependent() || SemaRef.CurContext->isDependentContext())
3210 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003211 if (EmitDiags) {
3212 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3213 << S->getSourceRange();
3214 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003215 return true;
3216}
3217
Alexey Bataev23b69422014-06-18 07:08:49 +00003218/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003219/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003220static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003221 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003222 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003223 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003224 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3225 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003226 if ((Ctor->isCopyOrMoveConstructor() ||
3227 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3228 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003229 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003230 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3231 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3232 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3233 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3234 return getCanonicalDecl(ME->getMemberDecl());
3235 return getCanonicalDecl(VD);
3236 }
3237 }
3238 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3239 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3240 return getCanonicalDecl(ME->getMemberDecl());
3241 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003242}
3243
3244bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3245 // Check test-expr for canonical form, save upper-bound UB, flags for
3246 // less/greater and for strict/non-strict comparison.
3247 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3248 // var relational-op b
3249 // b relational-op var
3250 //
3251 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003252 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003253 return true;
3254 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003255 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003256 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003257 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003258 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003259 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003260 return SetUB(BO->getRHS(),
3261 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3262 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3263 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003264 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003265 return SetUB(BO->getLHS(),
3266 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3267 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3268 BO->getSourceRange(), BO->getOperatorLoc());
3269 }
David Majnemer9d168222016-08-05 17:44:54 +00003270 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003271 if (CE->getNumArgs() == 2) {
3272 auto Op = CE->getOperator();
3273 switch (Op) {
3274 case OO_Greater:
3275 case OO_GreaterEqual:
3276 case OO_Less:
3277 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003278 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003279 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3280 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3281 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003282 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003283 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3284 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3285 CE->getOperatorLoc());
3286 break;
3287 default:
3288 break;
3289 }
3290 }
3291 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003292 if (Dependent() || SemaRef.CurContext->isDependentContext())
3293 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003294 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003295 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003296 return true;
3297}
3298
3299bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3300 // RHS of canonical loop form increment can be:
3301 // var + incr
3302 // incr + var
3303 // var - incr
3304 //
3305 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003306 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003307 if (BO->isAdditiveOp()) {
3308 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003309 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003310 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003311 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003312 return SetStep(BO->getLHS(), false);
3313 }
David Majnemer9d168222016-08-05 17:44:54 +00003314 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003315 bool IsAdd = CE->getOperator() == OO_Plus;
3316 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003317 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003318 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003319 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003320 return SetStep(CE->getArg(0), false);
3321 }
3322 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003323 if (Dependent() || SemaRef.CurContext->isDependentContext())
3324 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003325 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003326 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003327 return true;
3328}
3329
3330bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3331 // Check incr-expr for canonical loop form and return true if it
3332 // does not conform.
3333 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3334 // ++var
3335 // var++
3336 // --var
3337 // var--
3338 // var += incr
3339 // var -= incr
3340 // var = var + incr
3341 // var = incr + var
3342 // var = var - incr
3343 //
3344 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003345 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003346 return true;
3347 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003348 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3349 if (!ExprTemp->cleanupsHaveSideEffects())
3350 S = ExprTemp->getSubExpr();
3351
Alexander Musmana5f070a2014-10-01 06:03:56 +00003352 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003353 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003354 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003355 if (UO->isIncrementDecrementOp() &&
3356 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003357 return SetStep(SemaRef
3358 .ActOnIntegerConstant(UO->getLocStart(),
3359 (UO->isDecrementOp() ? -1 : 1))
3360 .get(),
3361 false);
3362 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003363 switch (BO->getOpcode()) {
3364 case BO_AddAssign:
3365 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003366 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003367 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3368 break;
3369 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003370 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003371 return CheckIncRHS(BO->getRHS());
3372 break;
3373 default:
3374 break;
3375 }
David Majnemer9d168222016-08-05 17:44:54 +00003376 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003377 switch (CE->getOperator()) {
3378 case OO_PlusPlus:
3379 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003380 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003381 return SetStep(SemaRef
3382 .ActOnIntegerConstant(
3383 CE->getLocStart(),
3384 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3385 .get(),
3386 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003387 break;
3388 case OO_PlusEqual:
3389 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003390 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003391 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3392 break;
3393 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003394 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003395 return CheckIncRHS(CE->getArg(1));
3396 break;
3397 default:
3398 break;
3399 }
3400 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003401 if (Dependent() || SemaRef.CurContext->isDependentContext())
3402 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003403 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003404 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003405 return true;
3406}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003407
Alexey Bataev5a3af132016-03-29 08:58:54 +00003408static ExprResult
3409tryBuildCapture(Sema &SemaRef, Expr *Capture,
3410 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003411 if (SemaRef.CurContext->isDependentContext())
3412 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003413 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3414 return SemaRef.PerformImplicitConversion(
3415 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3416 /*AllowExplicit=*/true);
3417 auto I = Captures.find(Capture);
3418 if (I != Captures.end())
3419 return buildCapture(SemaRef, Capture, I->second);
3420 DeclRefExpr *Ref = nullptr;
3421 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3422 Captures[Capture] = Ref;
3423 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003424}
3425
Alexander Musmana5f070a2014-10-01 06:03:56 +00003426/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003427Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3428 Scope *S, const bool LimitedType,
3429 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003430 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003431 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003432 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003433 SemaRef.getLangOpts().CPlusPlus) {
3434 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003435 auto *UBExpr = TestIsLessOp ? UB : LB;
3436 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003437 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3438 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003439 if (!Upper || !Lower)
3440 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003441
3442 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3443
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003444 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003445 // BuildBinOp already emitted error, this one is to point user to upper
3446 // and lower bound, and to tell what is passed to 'operator-'.
3447 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3448 << Upper->getSourceRange() << Lower->getSourceRange();
3449 return nullptr;
3450 }
3451 }
3452
3453 if (!Diff.isUsable())
3454 return nullptr;
3455
3456 // Upper - Lower [- 1]
3457 if (TestIsStrictOp)
3458 Diff = SemaRef.BuildBinOp(
3459 S, DefaultLoc, BO_Sub, Diff.get(),
3460 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3461 if (!Diff.isUsable())
3462 return nullptr;
3463
3464 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003465 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3466 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003467 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003468 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003469 if (!Diff.isUsable())
3470 return nullptr;
3471
3472 // Parentheses (for dumping/debugging purposes only).
3473 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3474 if (!Diff.isUsable())
3475 return nullptr;
3476
3477 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003478 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003479 if (!Diff.isUsable())
3480 return nullptr;
3481
Alexander Musman174b3ca2014-10-06 11:16:29 +00003482 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003483 QualType Type = Diff.get()->getType();
3484 auto &C = SemaRef.Context;
3485 bool UseVarType = VarType->hasIntegerRepresentation() &&
3486 C.getTypeSize(Type) > C.getTypeSize(VarType);
3487 if (!Type->isIntegerType() || UseVarType) {
3488 unsigned NewSize =
3489 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3490 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3491 : Type->hasSignedIntegerRepresentation();
3492 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003493 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3494 Diff = SemaRef.PerformImplicitConversion(
3495 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3496 if (!Diff.isUsable())
3497 return nullptr;
3498 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003499 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003500 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003501 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3502 if (NewSize != C.getTypeSize(Type)) {
3503 if (NewSize < C.getTypeSize(Type)) {
3504 assert(NewSize == 64 && "incorrect loop var size");
3505 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3506 << InitSrcRange << ConditionSrcRange;
3507 }
3508 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003509 NewSize, Type->hasSignedIntegerRepresentation() ||
3510 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003511 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3512 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3513 Sema::AA_Converting, true);
3514 if (!Diff.isUsable())
3515 return nullptr;
3516 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003517 }
3518 }
3519
Alexander Musmana5f070a2014-10-01 06:03:56 +00003520 return Diff.get();
3521}
3522
Alexey Bataev5a3af132016-03-29 08:58:54 +00003523Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3524 Scope *S, Expr *Cond,
3525 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003526 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3527 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3528 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003529
Alexey Bataev5a3af132016-03-29 08:58:54 +00003530 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3531 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3532 if (!NewLB.isUsable() || !NewUB.isUsable())
3533 return nullptr;
3534
Alexey Bataev62dbb972015-04-22 11:59:37 +00003535 auto CondExpr = SemaRef.BuildBinOp(
3536 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3537 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003538 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003539 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003540 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3541 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003542 CondExpr = SemaRef.PerformImplicitConversion(
3543 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3544 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003545 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003546 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3547 // Otherwise use original loop conditon and evaluate it in runtime.
3548 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3549}
3550
Alexander Musmana5f070a2014-10-01 06:03:56 +00003551/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003552DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003553 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003554 auto *VD = dyn_cast<VarDecl>(LCDecl);
3555 if (!VD) {
3556 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3557 auto *Ref = buildDeclRefExpr(
3558 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003559 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3560 // If the loop control decl is explicitly marked as private, do not mark it
3561 // as captured again.
3562 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3563 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003564 return Ref;
3565 }
3566 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003567 DefaultLoc);
3568}
3569
3570Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003571 if (LCDecl && !LCDecl->isInvalidDecl()) {
3572 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003573 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003574 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3575 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003576 if (PrivateVar->isInvalidDecl())
3577 return nullptr;
3578 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3579 }
3580 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003581}
3582
Samuel Antao4c8035b2016-12-12 18:00:20 +00003583/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003584Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3585
3586/// \brief Build step of the counter be used for codegen.
3587Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3588
3589/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003590struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003591 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003592 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003593 /// \brief This expression calculates the number of iterations in the loop.
3594 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003595 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003596 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003597 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003598 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003599 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003600 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003601 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003602 /// \brief This is step for the #CounterVar used to generate its update:
3603 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003604 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003605 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003606 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003607 /// \brief Source range of the loop init.
3608 SourceRange InitSrcRange;
3609 /// \brief Source range of the loop condition.
3610 SourceRange CondSrcRange;
3611 /// \brief Source range of the loop increment.
3612 SourceRange IncSrcRange;
3613};
3614
Alexey Bataev23b69422014-06-18 07:08:49 +00003615} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003616
Alexey Bataev9c821032015-04-30 04:23:23 +00003617void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3618 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3619 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003620 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3621 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003622 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3623 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003624 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3625 if (auto *D = ISC.GetLoopDecl()) {
3626 auto *VD = dyn_cast<VarDecl>(D);
3627 if (!VD) {
3628 if (auto *Private = IsOpenMPCapturedDecl(D))
3629 VD = Private;
3630 else {
3631 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3632 /*WithInit=*/false);
3633 VD = cast<VarDecl>(Ref->getDecl());
3634 }
3635 }
3636 DSAStack->addLoopControlVariable(D, VD);
3637 }
3638 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003639 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003640 }
3641}
3642
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003643/// \brief Called on a for stmt to check and extract its iteration space
3644/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003645static bool CheckOpenMPIterationSpace(
3646 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3647 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003648 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003649 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003650 LoopIterationSpace &ResultIterSpace,
3651 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652 // OpenMP [2.6, Canonical Loop Form]
3653 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003654 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003655 if (!For) {
3656 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003657 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3658 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3659 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3660 if (NestedLoopCount > 1) {
3661 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3662 SemaRef.Diag(DSA.getConstructLoc(),
3663 diag::note_omp_collapse_ordered_expr)
3664 << 2 << CollapseLoopCountExpr->getSourceRange()
3665 << OrderedLoopCountExpr->getSourceRange();
3666 else if (CollapseLoopCountExpr)
3667 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3668 diag::note_omp_collapse_ordered_expr)
3669 << 0 << CollapseLoopCountExpr->getSourceRange();
3670 else
3671 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3672 diag::note_omp_collapse_ordered_expr)
3673 << 1 << OrderedLoopCountExpr->getSourceRange();
3674 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003675 return true;
3676 }
3677 assert(For->getBody());
3678
3679 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3680
3681 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003682 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003683 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003684 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003685
3686 bool HasErrors = false;
3687
3688 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003689 if (auto *LCDecl = ISC.GetLoopDecl()) {
3690 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003691
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003692 // OpenMP [2.6, Canonical Loop Form]
3693 // Var is one of the following:
3694 // A variable of signed or unsigned integer type.
3695 // For C++, a variable of a random access iterator type.
3696 // For C, a variable of a pointer type.
3697 auto VarType = LCDecl->getType().getNonReferenceType();
3698 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3699 !VarType->isPointerType() &&
3700 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3701 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3702 << SemaRef.getLangOpts().CPlusPlus;
3703 HasErrors = true;
3704 }
3705
3706 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3707 // a Construct
3708 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3709 // parallel for construct is (are) private.
3710 // The loop iteration variable in the associated for-loop of a simd
3711 // construct with just one associated for-loop is linear with a
3712 // constant-linear-step that is the increment of the associated for-loop.
3713 // Exclude loop var from the list of variables with implicitly defined data
3714 // sharing attributes.
3715 VarsWithImplicitDSA.erase(LCDecl);
3716
3717 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3718 // in a Construct, C/C++].
3719 // The loop iteration variable in the associated for-loop of a simd
3720 // construct with just one associated for-loop may be listed in a linear
3721 // clause with a constant-linear-step that is the increment of the
3722 // associated for-loop.
3723 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3724 // parallel for construct may be listed in a private or lastprivate clause.
3725 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3726 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3727 // declared in the loop and it is predetermined as a private.
3728 auto PredeterminedCKind =
3729 isOpenMPSimdDirective(DKind)
3730 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3731 : OMPC_private;
3732 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3733 DVar.CKind != PredeterminedCKind) ||
3734 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3735 isOpenMPDistributeDirective(DKind)) &&
3736 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3737 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3738 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3739 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3740 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3741 << getOpenMPClauseName(PredeterminedCKind);
3742 if (DVar.RefExpr == nullptr)
3743 DVar.CKind = PredeterminedCKind;
3744 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3745 HasErrors = true;
3746 } else if (LoopDeclRefExpr != nullptr) {
3747 // Make the loop iteration variable private (for worksharing constructs),
3748 // linear (for simd directives with the only one associated loop) or
3749 // lastprivate (for simd directives with several collapsed or ordered
3750 // loops).
3751 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003752 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3753 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003754 /*FromParent=*/false);
3755 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3756 }
3757
3758 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3759
3760 // Check test-expr.
3761 HasErrors |= ISC.CheckCond(For->getCond());
3762
3763 // Check incr-expr.
3764 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003765 }
3766
Alexander Musmana5f070a2014-10-01 06:03:56 +00003767 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003768 return HasErrors;
3769
Alexander Musmana5f070a2014-10-01 06:03:56 +00003770 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003771 ResultIterSpace.PreCond =
3772 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003773 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003774 DSA.getCurScope(),
3775 (isOpenMPWorksharingDirective(DKind) ||
3776 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3777 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003778 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003779 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003780 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3781 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3782 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3783 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3784 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3785 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3786
Alexey Bataev62dbb972015-04-22 11:59:37 +00003787 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3788 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003789 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003790 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791 ResultIterSpace.CounterInit == nullptr ||
3792 ResultIterSpace.CounterStep == nullptr);
3793
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003794 return HasErrors;
3795}
3796
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003797/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003798static ExprResult
3799BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3800 ExprResult Start,
3801 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003802 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003803 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3804 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003805 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003806 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003807 VarRef.get()->getType())) {
3808 NewStart = SemaRef.PerformImplicitConversion(
3809 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3810 /*AllowExplicit=*/true);
3811 if (!NewStart.isUsable())
3812 return ExprError();
3813 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003814
3815 auto Init =
3816 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3817 return Init;
3818}
3819
Alexander Musmana5f070a2014-10-01 06:03:56 +00003820/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003821static ExprResult
3822BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3823 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3824 ExprResult Step, bool Subtract,
3825 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003826 // Add parentheses (for debugging purposes only).
3827 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3828 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3829 !Step.isUsable())
3830 return ExprError();
3831
Alexey Bataev5a3af132016-03-29 08:58:54 +00003832 ExprResult NewStep = Step;
3833 if (Captures)
3834 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003835 if (NewStep.isInvalid())
3836 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003837 ExprResult Update =
3838 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003839 if (!Update.isUsable())
3840 return ExprError();
3841
Alexey Bataevc0214e02016-02-16 12:13:49 +00003842 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3843 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003844 ExprResult NewStart = Start;
3845 if (Captures)
3846 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003847 if (NewStart.isInvalid())
3848 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003849
Alexey Bataevc0214e02016-02-16 12:13:49 +00003850 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3851 ExprResult SavedUpdate = Update;
3852 ExprResult UpdateVal;
3853 if (VarRef.get()->getType()->isOverloadableType() ||
3854 NewStart.get()->getType()->isOverloadableType() ||
3855 Update.get()->getType()->isOverloadableType()) {
3856 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3857 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3858 Update =
3859 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3860 if (Update.isUsable()) {
3861 UpdateVal =
3862 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3863 VarRef.get(), SavedUpdate.get());
3864 if (UpdateVal.isUsable()) {
3865 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3866 UpdateVal.get());
3867 }
3868 }
3869 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3870 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003871
Alexey Bataevc0214e02016-02-16 12:13:49 +00003872 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3873 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3874 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3875 NewStart.get(), SavedUpdate.get());
3876 if (!Update.isUsable())
3877 return ExprError();
3878
Alexey Bataev11481f52016-02-17 10:29:05 +00003879 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3880 VarRef.get()->getType())) {
3881 Update = SemaRef.PerformImplicitConversion(
3882 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3883 if (!Update.isUsable())
3884 return ExprError();
3885 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003886
3887 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3888 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003889 return Update;
3890}
3891
3892/// \brief Convert integer expression \a E to make it have at least \a Bits
3893/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003894static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003895 if (E == nullptr)
3896 return ExprError();
3897 auto &C = SemaRef.Context;
3898 QualType OldType = E->getType();
3899 unsigned HasBits = C.getTypeSize(OldType);
3900 if (HasBits >= Bits)
3901 return ExprResult(E);
3902 // OK to convert to signed, because new type has more bits than old.
3903 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3904 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3905 true);
3906}
3907
3908/// \brief Check if the given expression \a E is a constant integer that fits
3909/// into \a Bits bits.
3910static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3911 if (E == nullptr)
3912 return false;
3913 llvm::APSInt Result;
3914 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3915 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3916 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003917}
3918
Alexey Bataev5a3af132016-03-29 08:58:54 +00003919/// Build preinits statement for the given declarations.
3920static Stmt *buildPreInits(ASTContext &Context,
3921 SmallVectorImpl<Decl *> &PreInits) {
3922 if (!PreInits.empty()) {
3923 return new (Context) DeclStmt(
3924 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3925 SourceLocation(), SourceLocation());
3926 }
3927 return nullptr;
3928}
3929
3930/// Build preinits statement for the given declarations.
3931static Stmt *buildPreInits(ASTContext &Context,
3932 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3933 if (!Captures.empty()) {
3934 SmallVector<Decl *, 16> PreInits;
3935 for (auto &Pair : Captures)
3936 PreInits.push_back(Pair.second->getDecl());
3937 return buildPreInits(Context, PreInits);
3938 }
3939 return nullptr;
3940}
3941
3942/// Build postupdate expression for the given list of postupdates expressions.
3943static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3944 Expr *PostUpdate = nullptr;
3945 if (!PostUpdates.empty()) {
3946 for (auto *E : PostUpdates) {
3947 Expr *ConvE = S.BuildCStyleCastExpr(
3948 E->getExprLoc(),
3949 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3950 E->getExprLoc(), E)
3951 .get();
3952 PostUpdate = PostUpdate
3953 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3954 PostUpdate, ConvE)
3955 .get()
3956 : ConvE;
3957 }
3958 }
3959 return PostUpdate;
3960}
3961
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003962/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003963/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3964/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003965static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003966CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3967 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3968 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003969 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003970 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003971 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003972 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003973 // Found 'collapse' clause - calculate collapse number.
3974 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003975 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003976 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003977 }
3978 if (OrderedLoopCountExpr) {
3979 // Found 'ordered' clause - calculate collapse number.
3980 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003981 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3982 if (Result.getLimitedValue() < NestedLoopCount) {
3983 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3984 diag::err_omp_wrong_ordered_loop_count)
3985 << OrderedLoopCountExpr->getSourceRange();
3986 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3987 diag::note_collapse_loop_count)
3988 << CollapseLoopCountExpr->getSourceRange();
3989 }
3990 NestedLoopCount = Result.getLimitedValue();
3991 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003992 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003993 // This is helper routine for loop directives (e.g., 'for', 'simd',
3994 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003995 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003996 SmallVector<LoopIterationSpace, 4> IterSpaces;
3997 IterSpaces.resize(NestedLoopCount);
3998 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003999 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004000 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004001 NestedLoopCount, CollapseLoopCountExpr,
4002 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004003 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004004 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004005 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004006 // OpenMP [2.8.1, simd construct, Restrictions]
4007 // All loops associated with the construct must be perfectly nested; that
4008 // is, there must be no intervening code nor any OpenMP directive between
4009 // any two loops.
4010 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004011 }
4012
Alexander Musmana5f070a2014-10-01 06:03:56 +00004013 Built.clear(/* size */ NestedLoopCount);
4014
4015 if (SemaRef.CurContext->isDependentContext())
4016 return NestedLoopCount;
4017
4018 // An example of what is generated for the following code:
4019 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004020 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004021 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004022 // for (k = 0; k < NK; ++k)
4023 // for (j = J0; j < NJ; j+=2) {
4024 // <loop body>
4025 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004026 //
4027 // We generate the code below.
4028 // Note: the loop body may be outlined in CodeGen.
4029 // Note: some counters may be C++ classes, operator- is used to find number of
4030 // iterations and operator+= to calculate counter value.
4031 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4032 // or i64 is currently supported).
4033 //
4034 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4035 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4036 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4037 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4038 // // similar updates for vars in clauses (e.g. 'linear')
4039 // <loop body (using local i and j)>
4040 // }
4041 // i = NI; // assign final values of counters
4042 // j = NJ;
4043 //
4044
4045 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4046 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004047 // Precondition tests if there is at least one iteration (all conditions are
4048 // true).
4049 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004050 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004051 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004052 32 /* Bits */, SemaRef
4053 .PerformImplicitConversion(
4054 N0->IgnoreImpCasts(), N0->getType(),
4055 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004056 .get(),
4057 SemaRef);
4058 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004059 64 /* Bits */, SemaRef
4060 .PerformImplicitConversion(
4061 N0->IgnoreImpCasts(), N0->getType(),
4062 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004063 .get(),
4064 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004065
4066 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4067 return NestedLoopCount;
4068
4069 auto &C = SemaRef.Context;
4070 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4071
4072 Scope *CurScope = DSA.getCurScope();
4073 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004074 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004075 PreCond =
4076 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4077 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004078 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004079 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004080 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004081 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4082 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004083 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004084 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004085 SemaRef
4086 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4087 Sema::AA_Converting,
4088 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004089 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004090 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004091 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004092 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004093 SemaRef
4094 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4095 Sema::AA_Converting,
4096 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004097 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004098 }
4099
4100 // Choose either the 32-bit or 64-bit version.
4101 ExprResult LastIteration = LastIteration64;
4102 if (LastIteration32.isUsable() &&
4103 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4104 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4105 FitsInto(
4106 32 /* Bits */,
4107 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4108 LastIteration64.get(), SemaRef)))
4109 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004110 QualType VType = LastIteration.get()->getType();
4111 QualType RealVType = VType;
4112 QualType StrideVType = VType;
4113 if (isOpenMPTaskLoopDirective(DKind)) {
4114 VType =
4115 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4116 StrideVType =
4117 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4118 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004119
4120 if (!LastIteration.isUsable())
4121 return 0;
4122
4123 // Save the number of iterations.
4124 ExprResult NumIterations = LastIteration;
4125 {
4126 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004127 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4128 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004129 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4130 if (!LastIteration.isUsable())
4131 return 0;
4132 }
4133
4134 // Calculate the last iteration number beforehand instead of doing this on
4135 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4136 llvm::APSInt Result;
4137 bool IsConstant =
4138 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4139 ExprResult CalcLastIteration;
4140 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004141 ExprResult SaveRef =
4142 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004143 LastIteration = SaveRef;
4144
4145 // Prepare SaveRef + 1.
4146 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004147 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004148 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4149 if (!NumIterations.isUsable())
4150 return 0;
4151 }
4152
4153 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4154
David Majnemer9d168222016-08-05 17:44:54 +00004155 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004156 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004157 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4158 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004159 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004160 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4161 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004162 SemaRef.AddInitializerToDecl(LBDecl,
4163 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4164 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004165
4166 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004167 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4168 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004169 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004170 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004171
4172 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4173 // This will be used to implement clause 'lastprivate'.
4174 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004175 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4176 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004177 SemaRef.AddInitializerToDecl(ILDecl,
4178 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4179 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004180
4181 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004182 VarDecl *STDecl =
4183 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4184 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004185 SemaRef.AddInitializerToDecl(STDecl,
4186 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4187 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004188
4189 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004190 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004191 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4192 UB.get(), LastIteration.get());
4193 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4194 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4195 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4196 CondOp.get());
4197 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004198
4199 // If we have a combined directive that combines 'distribute', 'for' or
4200 // 'simd' we need to be able to access the bounds of the schedule of the
4201 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4202 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4203 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004204
Carlo Bertolliffafe102017-04-20 00:39:39 +00004205 // Lower bound variable, initialized with zero.
4206 VarDecl *CombLBDecl =
4207 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4208 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4209 SemaRef.AddInitializerToDecl(
4210 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4211 /*DirectInit*/ false);
4212
4213 // Upper bound variable, initialized with last iteration number.
4214 VarDecl *CombUBDecl =
4215 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4216 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4217 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4218 /*DirectInit*/ false);
4219
4220 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4221 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4222 ExprResult CombCondOp =
4223 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4224 LastIteration.get(), CombUB.get());
4225 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4226 CombCondOp.get());
4227 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4228
4229 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004230 // We expect to have at least 2 more parameters than the 'parallel'
4231 // directive does - the lower and upper bounds of the previous schedule.
4232 assert(CD->getNumParams() >= 4 &&
4233 "Unexpected number of parameters in loop combined directive");
4234
4235 // Set the proper type for the bounds given what we learned from the
4236 // enclosed loops.
4237 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4238 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4239
4240 // Previous lower and upper bounds are obtained from the region
4241 // parameters.
4242 PrevLB =
4243 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4244 PrevUB =
4245 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4246 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004247 }
4248
4249 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004250 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004251 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004252 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004253 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4254 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004255 Expr *RHS =
4256 (isOpenMPWorksharingDirective(DKind) ||
4257 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4258 ? LB.get()
4259 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004260 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4261 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004262
4263 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4264 Expr *CombRHS =
4265 (isOpenMPWorksharingDirective(DKind) ||
4266 isOpenMPTaskLoopDirective(DKind) ||
4267 isOpenMPDistributeDirective(DKind))
4268 ? CombLB.get()
4269 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4270 CombInit =
4271 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4272 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4273 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004274 }
4275
Alexander Musmanc6388682014-12-15 07:07:06 +00004276 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004277 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004278 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004279 (isOpenMPWorksharingDirective(DKind) ||
4280 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004281 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4282 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4283 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004284 ExprResult CombCond;
4285 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4286 CombCond =
4287 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4288 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004289 // Loop increment (IV = IV + 1)
4290 SourceLocation IncLoc;
4291 ExprResult Inc =
4292 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4293 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4294 if (!Inc.isUsable())
4295 return 0;
4296 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004297 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4298 if (!Inc.isUsable())
4299 return 0;
4300
4301 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4302 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004303 // In combined construct, add combined version that use CombLB and CombUB
4304 // base variables for the update
4305 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004306 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4307 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004308 // LB + ST
4309 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4310 if (!NextLB.isUsable())
4311 return 0;
4312 // LB = LB + ST
4313 NextLB =
4314 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4315 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4316 if (!NextLB.isUsable())
4317 return 0;
4318 // UB + ST
4319 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4320 if (!NextUB.isUsable())
4321 return 0;
4322 // UB = UB + ST
4323 NextUB =
4324 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4325 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4326 if (!NextUB.isUsable())
4327 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004328 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4329 CombNextLB =
4330 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4331 if (!NextLB.isUsable())
4332 return 0;
4333 // LB = LB + ST
4334 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4335 CombNextLB.get());
4336 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4337 if (!CombNextLB.isUsable())
4338 return 0;
4339 // UB + ST
4340 CombNextUB =
4341 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4342 if (!CombNextUB.isUsable())
4343 return 0;
4344 // UB = UB + ST
4345 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4346 CombNextUB.get());
4347 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4348 if (!CombNextUB.isUsable())
4349 return 0;
4350 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004351 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004352
Carlo Bertolliffafe102017-04-20 00:39:39 +00004353 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004354 // directive with for as IV = IV + ST; ensure upper bound expression based
4355 // on PrevUB instead of NumIterations - used to implement 'for' when found
4356 // in combination with 'distribute', like in 'distribute parallel for'
4357 SourceLocation DistIncLoc;
4358 ExprResult DistCond, DistInc, PrevEUB;
4359 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4360 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4361 assert(DistCond.isUsable() && "distribute cond expr was not built");
4362
4363 DistInc =
4364 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4365 assert(DistInc.isUsable() && "distribute inc expr was not built");
4366 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4367 DistInc.get());
4368 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4369 assert(DistInc.isUsable() && "distribute inc expr was not built");
4370
4371 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4372 // construct
4373 SourceLocation DistEUBLoc;
4374 ExprResult IsUBGreater =
4375 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4376 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4377 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4378 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4379 CondOp.get());
4380 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4381 }
4382
Alexander Musmana5f070a2014-10-01 06:03:56 +00004383 // Build updates and final values of the loop counters.
4384 bool HasErrors = false;
4385 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004386 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004387 Built.Updates.resize(NestedLoopCount);
4388 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004389 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004390 {
4391 ExprResult Div;
4392 // Go from inner nested loop to outer.
4393 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4394 LoopIterationSpace &IS = IterSpaces[Cnt];
4395 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4396 // Build: Iter = (IV / Div) % IS.NumIters
4397 // where Div is product of previous iterations' IS.NumIters.
4398 ExprResult Iter;
4399 if (Div.isUsable()) {
4400 Iter =
4401 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4402 } else {
4403 Iter = IV;
4404 assert((Cnt == (int)NestedLoopCount - 1) &&
4405 "unusable div expected on first iteration only");
4406 }
4407
4408 if (Cnt != 0 && Iter.isUsable())
4409 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4410 IS.NumIterations);
4411 if (!Iter.isUsable()) {
4412 HasErrors = true;
4413 break;
4414 }
4415
Alexey Bataev39f915b82015-05-08 10:41:21 +00004416 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004417 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4418 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4419 IS.CounterVar->getExprLoc(),
4420 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004421 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004422 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004423 if (!Init.isUsable()) {
4424 HasErrors = true;
4425 break;
4426 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004427 ExprResult Update = BuildCounterUpdate(
4428 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4429 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004430 if (!Update.isUsable()) {
4431 HasErrors = true;
4432 break;
4433 }
4434
4435 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4436 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004437 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004438 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004439 if (!Final.isUsable()) {
4440 HasErrors = true;
4441 break;
4442 }
4443
4444 // Build Div for the next iteration: Div <- Div * IS.NumIters
4445 if (Cnt != 0) {
4446 if (Div.isUnset())
4447 Div = IS.NumIterations;
4448 else
4449 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4450 IS.NumIterations);
4451
4452 // Add parentheses (for debugging purposes only).
4453 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004454 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004455 if (!Div.isUsable()) {
4456 HasErrors = true;
4457 break;
4458 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004459 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004460 }
4461 if (!Update.isUsable() || !Final.isUsable()) {
4462 HasErrors = true;
4463 break;
4464 }
4465 // Save results
4466 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004467 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004468 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004469 Built.Updates[Cnt] = Update.get();
4470 Built.Finals[Cnt] = Final.get();
4471 }
4472 }
4473
4474 if (HasErrors)
4475 return 0;
4476
4477 // Save results
4478 Built.IterationVarRef = IV.get();
4479 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004480 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004481 Built.CalcLastIteration =
4482 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004483 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004484 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004485 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004486 Built.Init = Init.get();
4487 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004488 Built.LB = LB.get();
4489 Built.UB = UB.get();
4490 Built.IL = IL.get();
4491 Built.ST = ST.get();
4492 Built.EUB = EUB.get();
4493 Built.NLB = NextLB.get();
4494 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004495 Built.PrevLB = PrevLB.get();
4496 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004497 Built.DistInc = DistInc.get();
4498 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004499 Built.DistCombinedFields.LB = CombLB.get();
4500 Built.DistCombinedFields.UB = CombUB.get();
4501 Built.DistCombinedFields.EUB = CombEUB.get();
4502 Built.DistCombinedFields.Init = CombInit.get();
4503 Built.DistCombinedFields.Cond = CombCond.get();
4504 Built.DistCombinedFields.NLB = CombNextLB.get();
4505 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004506
Alexey Bataev8b427062016-05-25 12:36:08 +00004507 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4508 // Fill data for doacross depend clauses.
4509 for (auto Pair : DSA.getDoacrossDependClauses()) {
4510 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4511 Pair.first->setCounterValue(CounterVal);
4512 else {
4513 if (NestedLoopCount != Pair.second.size() ||
4514 NestedLoopCount != LoopMultipliers.size() + 1) {
4515 // Erroneous case - clause has some problems.
4516 Pair.first->setCounterValue(CounterVal);
4517 continue;
4518 }
4519 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4520 auto I = Pair.second.rbegin();
4521 auto IS = IterSpaces.rbegin();
4522 auto ILM = LoopMultipliers.rbegin();
4523 Expr *UpCounterVal = CounterVal;
4524 Expr *Multiplier = nullptr;
4525 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4526 if (I->first) {
4527 assert(IS->CounterStep);
4528 Expr *NormalizedOffset =
4529 SemaRef
4530 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4531 I->first, IS->CounterStep)
4532 .get();
4533 if (Multiplier) {
4534 NormalizedOffset =
4535 SemaRef
4536 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4537 NormalizedOffset, Multiplier)
4538 .get();
4539 }
4540 assert(I->second == OO_Plus || I->second == OO_Minus);
4541 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004542 UpCounterVal = SemaRef
4543 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4544 UpCounterVal, NormalizedOffset)
4545 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004546 }
4547 Multiplier = *ILM;
4548 ++I;
4549 ++IS;
4550 ++ILM;
4551 }
4552 Pair.first->setCounterValue(UpCounterVal);
4553 }
4554 }
4555
Alexey Bataevabfc0692014-06-25 06:52:00 +00004556 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004557}
4558
Alexey Bataev10e775f2015-07-30 11:36:16 +00004559static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004560 auto CollapseClauses =
4561 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4562 if (CollapseClauses.begin() != CollapseClauses.end())
4563 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004564 return nullptr;
4565}
4566
Alexey Bataev10e775f2015-07-30 11:36:16 +00004567static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004568 auto OrderedClauses =
4569 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4570 if (OrderedClauses.begin() != OrderedClauses.end())
4571 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004572 return nullptr;
4573}
4574
Kelvin Lic5609492016-07-15 04:39:07 +00004575static bool checkSimdlenSafelenSpecified(Sema &S,
4576 const ArrayRef<OMPClause *> Clauses) {
4577 OMPSafelenClause *Safelen = nullptr;
4578 OMPSimdlenClause *Simdlen = nullptr;
4579
4580 for (auto *Clause : Clauses) {
4581 if (Clause->getClauseKind() == OMPC_safelen)
4582 Safelen = cast<OMPSafelenClause>(Clause);
4583 else if (Clause->getClauseKind() == OMPC_simdlen)
4584 Simdlen = cast<OMPSimdlenClause>(Clause);
4585 if (Safelen && Simdlen)
4586 break;
4587 }
4588
4589 if (Simdlen && Safelen) {
4590 llvm::APSInt SimdlenRes, SafelenRes;
4591 auto SimdlenLength = Simdlen->getSimdlen();
4592 auto SafelenLength = Safelen->getSafelen();
4593 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4594 SimdlenLength->isInstantiationDependent() ||
4595 SimdlenLength->containsUnexpandedParameterPack())
4596 return false;
4597 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4598 SafelenLength->isInstantiationDependent() ||
4599 SafelenLength->containsUnexpandedParameterPack())
4600 return false;
4601 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4602 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4603 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4604 // If both simdlen and safelen clauses are specified, the value of the
4605 // simdlen parameter must be less than or equal to the value of the safelen
4606 // parameter.
4607 if (SimdlenRes > SafelenRes) {
4608 S.Diag(SimdlenLength->getExprLoc(),
4609 diag::err_omp_wrong_simdlen_safelen_values)
4610 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4611 return true;
4612 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004613 }
4614 return false;
4615}
4616
Alexey Bataev4acb8592014-07-07 13:01:15 +00004617StmtResult Sema::ActOnOpenMPSimdDirective(
4618 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4619 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004620 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004621 if (!AStmt)
4622 return StmtError();
4623
4624 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004625 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004626 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4627 // define the nested loops number.
4628 unsigned NestedLoopCount = CheckOpenMPLoop(
4629 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4630 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004631 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004632 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004633
Alexander Musmana5f070a2014-10-01 06:03:56 +00004634 assert((CurContext->isDependentContext() || B.builtAll()) &&
4635 "omp simd loop exprs were not built");
4636
Alexander Musman3276a272015-03-21 10:12:56 +00004637 if (!CurContext->isDependentContext()) {
4638 // Finalize the clauses that need pre-built expressions for CodeGen.
4639 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004640 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004641 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004642 B.NumIterations, *this, CurScope,
4643 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004644 return StmtError();
4645 }
4646 }
4647
Kelvin Lic5609492016-07-15 04:39:07 +00004648 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004649 return StmtError();
4650
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004651 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004652 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4653 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004654}
4655
Alexey Bataev4acb8592014-07-07 13:01:15 +00004656StmtResult Sema::ActOnOpenMPForDirective(
4657 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4658 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004659 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004660 if (!AStmt)
4661 return StmtError();
4662
4663 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004664 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004665 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4666 // define the nested loops number.
4667 unsigned NestedLoopCount = CheckOpenMPLoop(
4668 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4669 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004670 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004671 return StmtError();
4672
Alexander Musmana5f070a2014-10-01 06:03:56 +00004673 assert((CurContext->isDependentContext() || B.builtAll()) &&
4674 "omp for loop exprs were not built");
4675
Alexey Bataev54acd402015-08-04 11:18:19 +00004676 if (!CurContext->isDependentContext()) {
4677 // Finalize the clauses that need pre-built expressions for CodeGen.
4678 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004679 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004680 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004681 B.NumIterations, *this, CurScope,
4682 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004683 return StmtError();
4684 }
4685 }
4686
Alexey Bataevf29276e2014-06-18 04:14:57 +00004687 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004688 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004689 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004690}
4691
Alexander Musmanf82886e2014-09-18 05:12:34 +00004692StmtResult Sema::ActOnOpenMPForSimdDirective(
4693 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4694 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004695 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004696 if (!AStmt)
4697 return StmtError();
4698
4699 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004700 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004701 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4702 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004703 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004704 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4705 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4706 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004707 if (NestedLoopCount == 0)
4708 return StmtError();
4709
Alexander Musmanc6388682014-12-15 07:07:06 +00004710 assert((CurContext->isDependentContext() || B.builtAll()) &&
4711 "omp for simd loop exprs were not built");
4712
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004713 if (!CurContext->isDependentContext()) {
4714 // Finalize the clauses that need pre-built expressions for CodeGen.
4715 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004716 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004717 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004718 B.NumIterations, *this, CurScope,
4719 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004720 return StmtError();
4721 }
4722 }
4723
Kelvin Lic5609492016-07-15 04:39:07 +00004724 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004725 return StmtError();
4726
Alexander Musmanf82886e2014-09-18 05:12:34 +00004727 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004728 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4729 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004730}
4731
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004732StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4733 Stmt *AStmt,
4734 SourceLocation StartLoc,
4735 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004736 if (!AStmt)
4737 return StmtError();
4738
4739 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004740 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004741 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004742 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004743 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004744 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004745 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004746 return StmtError();
4747 // All associated statements must be '#pragma omp section' except for
4748 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004749 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004750 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4751 if (SectionStmt)
4752 Diag(SectionStmt->getLocStart(),
4753 diag::err_omp_sections_substmt_not_section);
4754 return StmtError();
4755 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004756 cast<OMPSectionDirective>(SectionStmt)
4757 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004758 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004759 } else {
4760 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4761 return StmtError();
4762 }
4763
4764 getCurFunction()->setHasBranchProtectedScope();
4765
Alexey Bataev25e5b442015-09-15 12:52:43 +00004766 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4767 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004768}
4769
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004770StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4771 SourceLocation StartLoc,
4772 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004773 if (!AStmt)
4774 return StmtError();
4775
4776 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004777
4778 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004779 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004780
Alexey Bataev25e5b442015-09-15 12:52:43 +00004781 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4782 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004783}
4784
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004785StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4786 Stmt *AStmt,
4787 SourceLocation StartLoc,
4788 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004789 if (!AStmt)
4790 return StmtError();
4791
4792 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004793
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004794 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004795
Alexey Bataev3255bf32015-01-19 05:20:46 +00004796 // OpenMP [2.7.3, single Construct, Restrictions]
4797 // The copyprivate clause must not be used with the nowait clause.
4798 OMPClause *Nowait = nullptr;
4799 OMPClause *Copyprivate = nullptr;
4800 for (auto *Clause : Clauses) {
4801 if (Clause->getClauseKind() == OMPC_nowait)
4802 Nowait = Clause;
4803 else if (Clause->getClauseKind() == OMPC_copyprivate)
4804 Copyprivate = Clause;
4805 if (Copyprivate && Nowait) {
4806 Diag(Copyprivate->getLocStart(),
4807 diag::err_omp_single_copyprivate_with_nowait);
4808 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4809 return StmtError();
4810 }
4811 }
4812
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004813 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4814}
4815
Alexander Musman80c22892014-07-17 08:54:58 +00004816StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4817 SourceLocation StartLoc,
4818 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004819 if (!AStmt)
4820 return StmtError();
4821
4822 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004823
4824 getCurFunction()->setHasBranchProtectedScope();
4825
4826 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4827}
4828
Alexey Bataev28c75412015-12-15 08:19:24 +00004829StmtResult Sema::ActOnOpenMPCriticalDirective(
4830 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4831 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004832 if (!AStmt)
4833 return StmtError();
4834
4835 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004836
Alexey Bataev28c75412015-12-15 08:19:24 +00004837 bool ErrorFound = false;
4838 llvm::APSInt Hint;
4839 SourceLocation HintLoc;
4840 bool DependentHint = false;
4841 for (auto *C : Clauses) {
4842 if (C->getClauseKind() == OMPC_hint) {
4843 if (!DirName.getName()) {
4844 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4845 ErrorFound = true;
4846 }
4847 Expr *E = cast<OMPHintClause>(C)->getHint();
4848 if (E->isTypeDependent() || E->isValueDependent() ||
4849 E->isInstantiationDependent())
4850 DependentHint = true;
4851 else {
4852 Hint = E->EvaluateKnownConstInt(Context);
4853 HintLoc = C->getLocStart();
4854 }
4855 }
4856 }
4857 if (ErrorFound)
4858 return StmtError();
4859 auto Pair = DSAStack->getCriticalWithHint(DirName);
4860 if (Pair.first && DirName.getName() && !DependentHint) {
4861 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4862 Diag(StartLoc, diag::err_omp_critical_with_hint);
4863 if (HintLoc.isValid()) {
4864 Diag(HintLoc, diag::note_omp_critical_hint_here)
4865 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4866 } else
4867 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4868 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4869 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4870 << 1
4871 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4872 /*Radix=*/10, /*Signed=*/false);
4873 } else
4874 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4875 }
4876 }
4877
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004878 getCurFunction()->setHasBranchProtectedScope();
4879
Alexey Bataev28c75412015-12-15 08:19:24 +00004880 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4881 Clauses, AStmt);
4882 if (!Pair.first && DirName.getName() && !DependentHint)
4883 DSAStack->addCriticalWithHint(Dir, Hint);
4884 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004885}
4886
Alexey Bataev4acb8592014-07-07 13:01:15 +00004887StmtResult Sema::ActOnOpenMPParallelForDirective(
4888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4889 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004891 if (!AStmt)
4892 return StmtError();
4893
Alexey Bataev4acb8592014-07-07 13:01:15 +00004894 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4895 // 1.2.2 OpenMP Language Terminology
4896 // Structured block - An executable statement with a single entry at the
4897 // top and a single exit at the bottom.
4898 // The point of exit cannot be a branch out of the structured block.
4899 // longjmp() and throw() must not violate the entry/exit criteria.
4900 CS->getCapturedDecl()->setNothrow();
4901
Alexander Musmanc6388682014-12-15 07:07:06 +00004902 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004903 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4904 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004905 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004906 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4907 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4908 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004909 if (NestedLoopCount == 0)
4910 return StmtError();
4911
Alexander Musmana5f070a2014-10-01 06:03:56 +00004912 assert((CurContext->isDependentContext() || B.builtAll()) &&
4913 "omp parallel for loop exprs were not built");
4914
Alexey Bataev54acd402015-08-04 11:18:19 +00004915 if (!CurContext->isDependentContext()) {
4916 // Finalize the clauses that need pre-built expressions for CodeGen.
4917 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004918 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004919 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004920 B.NumIterations, *this, CurScope,
4921 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004922 return StmtError();
4923 }
4924 }
4925
Alexey Bataev4acb8592014-07-07 13:01:15 +00004926 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004927 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004928 NestedLoopCount, Clauses, AStmt, B,
4929 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004930}
4931
Alexander Musmane4e893b2014-09-23 09:33:00 +00004932StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4934 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004935 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004936 if (!AStmt)
4937 return StmtError();
4938
Alexander Musmane4e893b2014-09-23 09:33:00 +00004939 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4940 // 1.2.2 OpenMP Language Terminology
4941 // Structured block - An executable statement with a single entry at the
4942 // top and a single exit at the bottom.
4943 // The point of exit cannot be a branch out of the structured block.
4944 // longjmp() and throw() must not violate the entry/exit criteria.
4945 CS->getCapturedDecl()->setNothrow();
4946
Alexander Musmanc6388682014-12-15 07:07:06 +00004947 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004948 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4949 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004950 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004951 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4952 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4953 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004954 if (NestedLoopCount == 0)
4955 return StmtError();
4956
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004957 if (!CurContext->isDependentContext()) {
4958 // Finalize the clauses that need pre-built expressions for CodeGen.
4959 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004960 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004961 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004962 B.NumIterations, *this, CurScope,
4963 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004964 return StmtError();
4965 }
4966 }
4967
Kelvin Lic5609492016-07-15 04:39:07 +00004968 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004969 return StmtError();
4970
Alexander Musmane4e893b2014-09-23 09:33:00 +00004971 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004972 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004973 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004974}
4975
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004976StmtResult
4977Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4978 Stmt *AStmt, SourceLocation StartLoc,
4979 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004980 if (!AStmt)
4981 return StmtError();
4982
4983 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004984 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004985 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004986 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004987 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004988 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004989 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004990 return StmtError();
4991 // All associated statements must be '#pragma omp section' except for
4992 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004993 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004994 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4995 if (SectionStmt)
4996 Diag(SectionStmt->getLocStart(),
4997 diag::err_omp_parallel_sections_substmt_not_section);
4998 return StmtError();
4999 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005000 cast<OMPSectionDirective>(SectionStmt)
5001 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005002 }
5003 } else {
5004 Diag(AStmt->getLocStart(),
5005 diag::err_omp_parallel_sections_not_compound_stmt);
5006 return StmtError();
5007 }
5008
5009 getCurFunction()->setHasBranchProtectedScope();
5010
Alexey Bataev25e5b442015-09-15 12:52:43 +00005011 return OMPParallelSectionsDirective::Create(
5012 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005013}
5014
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005015StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5016 Stmt *AStmt, SourceLocation StartLoc,
5017 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005018 if (!AStmt)
5019 return StmtError();
5020
David Majnemer9d168222016-08-05 17:44:54 +00005021 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005022 // 1.2.2 OpenMP Language Terminology
5023 // Structured block - An executable statement with a single entry at the
5024 // top and a single exit at the bottom.
5025 // The point of exit cannot be a branch out of the structured block.
5026 // longjmp() and throw() must not violate the entry/exit criteria.
5027 CS->getCapturedDecl()->setNothrow();
5028
5029 getCurFunction()->setHasBranchProtectedScope();
5030
Alexey Bataev25e5b442015-09-15 12:52:43 +00005031 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5032 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005033}
5034
Alexey Bataev68446b72014-07-18 07:47:19 +00005035StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5036 SourceLocation EndLoc) {
5037 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5038}
5039
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005040StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5041 SourceLocation EndLoc) {
5042 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5043}
5044
Alexey Bataev2df347a2014-07-18 10:17:07 +00005045StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5046 SourceLocation EndLoc) {
5047 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5048}
5049
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005050StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5051 SourceLocation StartLoc,
5052 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005053 if (!AStmt)
5054 return StmtError();
5055
5056 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005057
5058 getCurFunction()->setHasBranchProtectedScope();
5059
5060 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5061}
5062
Alexey Bataev6125da92014-07-21 11:26:11 +00005063StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5064 SourceLocation StartLoc,
5065 SourceLocation EndLoc) {
5066 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5067 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5068}
5069
Alexey Bataev346265e2015-09-25 10:37:12 +00005070StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5071 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005072 SourceLocation StartLoc,
5073 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005074 OMPClause *DependFound = nullptr;
5075 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005076 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005077 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005078 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005079 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005080 for (auto *C : Clauses) {
5081 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5082 DependFound = C;
5083 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5084 if (DependSourceClause) {
5085 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5086 << getOpenMPDirectiveName(OMPD_ordered)
5087 << getOpenMPClauseName(OMPC_depend) << 2;
5088 ErrorFound = true;
5089 } else
5090 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005091 if (DependSinkClause) {
5092 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5093 << 0;
5094 ErrorFound = true;
5095 }
5096 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5097 if (DependSourceClause) {
5098 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5099 << 1;
5100 ErrorFound = true;
5101 }
5102 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005103 }
5104 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005105 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005106 else if (C->getClauseKind() == OMPC_simd)
5107 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005108 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005109 if (!ErrorFound && !SC &&
5110 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005111 // OpenMP [2.8.1,simd Construct, Restrictions]
5112 // An ordered construct with the simd clause is the only OpenMP construct
5113 // that can appear in the simd region.
5114 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005115 ErrorFound = true;
5116 } else if (DependFound && (TC || SC)) {
5117 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5118 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5119 ErrorFound = true;
5120 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5121 Diag(DependFound->getLocStart(),
5122 diag::err_omp_ordered_directive_without_param);
5123 ErrorFound = true;
5124 } else if (TC || Clauses.empty()) {
5125 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5126 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5127 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5128 << (TC != nullptr);
5129 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5130 ErrorFound = true;
5131 }
5132 }
5133 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005134 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005135
5136 if (AStmt) {
5137 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5138
5139 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005140 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005141
5142 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005143}
5144
Alexey Bataev1d160b12015-03-13 12:27:31 +00005145namespace {
5146/// \brief Helper class for checking expression in 'omp atomic [update]'
5147/// construct.
5148class OpenMPAtomicUpdateChecker {
5149 /// \brief Error results for atomic update expressions.
5150 enum ExprAnalysisErrorCode {
5151 /// \brief A statement is not an expression statement.
5152 NotAnExpression,
5153 /// \brief Expression is not builtin binary or unary operation.
5154 NotABinaryOrUnaryExpression,
5155 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5156 NotAnUnaryIncDecExpression,
5157 /// \brief An expression is not of scalar type.
5158 NotAScalarType,
5159 /// \brief A binary operation is not an assignment operation.
5160 NotAnAssignmentOp,
5161 /// \brief RHS part of the binary operation is not a binary expression.
5162 NotABinaryExpression,
5163 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5164 /// expression.
5165 NotABinaryOperator,
5166 /// \brief RHS binary operation does not have reference to the updated LHS
5167 /// part.
5168 NotAnUpdateExpression,
5169 /// \brief No errors is found.
5170 NoError
5171 };
5172 /// \brief Reference to Sema.
5173 Sema &SemaRef;
5174 /// \brief A location for note diagnostics (when error is found).
5175 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005176 /// \brief 'x' lvalue part of the source atomic expression.
5177 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005178 /// \brief 'expr' rvalue part of the source atomic expression.
5179 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005180 /// \brief Helper expression of the form
5181 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5182 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5183 Expr *UpdateExpr;
5184 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5185 /// important for non-associative operations.
5186 bool IsXLHSInRHSPart;
5187 BinaryOperatorKind Op;
5188 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005189 /// \brief true if the source expression is a postfix unary operation, false
5190 /// if it is a prefix unary operation.
5191 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005192
5193public:
5194 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005195 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005196 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005197 /// \brief Check specified statement that it is suitable for 'atomic update'
5198 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005199 /// expression. If DiagId and NoteId == 0, then only check is performed
5200 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005201 /// \param DiagId Diagnostic which should be emitted if error is found.
5202 /// \param NoteId Diagnostic note for the main error message.
5203 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005204 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005205 /// \brief Return the 'x' lvalue part of the source atomic expression.
5206 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005207 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5208 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005209 /// \brief Return the update expression used in calculation of the updated
5210 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5211 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5212 Expr *getUpdateExpr() const { return UpdateExpr; }
5213 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5214 /// false otherwise.
5215 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5216
Alexey Bataevb78ca832015-04-01 03:33:17 +00005217 /// \brief true if the source expression is a postfix unary operation, false
5218 /// if it is a prefix unary operation.
5219 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5220
Alexey Bataev1d160b12015-03-13 12:27:31 +00005221private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005222 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5223 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005224};
5225} // namespace
5226
5227bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5228 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5229 ExprAnalysisErrorCode ErrorFound = NoError;
5230 SourceLocation ErrorLoc, NoteLoc;
5231 SourceRange ErrorRange, NoteRange;
5232 // Allowed constructs are:
5233 // x = x binop expr;
5234 // x = expr binop x;
5235 if (AtomicBinOp->getOpcode() == BO_Assign) {
5236 X = AtomicBinOp->getLHS();
5237 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5238 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5239 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5240 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5241 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005242 Op = AtomicInnerBinOp->getOpcode();
5243 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005244 auto *LHS = AtomicInnerBinOp->getLHS();
5245 auto *RHS = AtomicInnerBinOp->getRHS();
5246 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5247 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5248 /*Canonical=*/true);
5249 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5250 /*Canonical=*/true);
5251 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5252 /*Canonical=*/true);
5253 if (XId == LHSId) {
5254 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005255 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005256 } else if (XId == RHSId) {
5257 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005258 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005259 } else {
5260 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5261 ErrorRange = AtomicInnerBinOp->getSourceRange();
5262 NoteLoc = X->getExprLoc();
5263 NoteRange = X->getSourceRange();
5264 ErrorFound = NotAnUpdateExpression;
5265 }
5266 } else {
5267 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5268 ErrorRange = AtomicInnerBinOp->getSourceRange();
5269 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5270 NoteRange = SourceRange(NoteLoc, NoteLoc);
5271 ErrorFound = NotABinaryOperator;
5272 }
5273 } else {
5274 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5275 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5276 ErrorFound = NotABinaryExpression;
5277 }
5278 } else {
5279 ErrorLoc = AtomicBinOp->getExprLoc();
5280 ErrorRange = AtomicBinOp->getSourceRange();
5281 NoteLoc = AtomicBinOp->getOperatorLoc();
5282 NoteRange = SourceRange(NoteLoc, NoteLoc);
5283 ErrorFound = NotAnAssignmentOp;
5284 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005285 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005286 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5287 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5288 return true;
5289 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005290 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005291 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005292}
5293
5294bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5295 unsigned NoteId) {
5296 ExprAnalysisErrorCode ErrorFound = NoError;
5297 SourceLocation ErrorLoc, NoteLoc;
5298 SourceRange ErrorRange, NoteRange;
5299 // Allowed constructs are:
5300 // x++;
5301 // x--;
5302 // ++x;
5303 // --x;
5304 // x binop= expr;
5305 // x = x binop expr;
5306 // x = expr binop x;
5307 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5308 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5309 if (AtomicBody->getType()->isScalarType() ||
5310 AtomicBody->isInstantiationDependent()) {
5311 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5312 AtomicBody->IgnoreParenImpCasts())) {
5313 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005314 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005315 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005316 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005317 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005318 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005319 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005320 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5321 AtomicBody->IgnoreParenImpCasts())) {
5322 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005323 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005324 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005325 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5326 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005327 // Check for Unary Operation
5328 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005329 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005330 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5331 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005332 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005333 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5334 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005335 } else {
5336 ErrorFound = NotAnUnaryIncDecExpression;
5337 ErrorLoc = AtomicUnaryOp->getExprLoc();
5338 ErrorRange = AtomicUnaryOp->getSourceRange();
5339 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5340 NoteRange = SourceRange(NoteLoc, NoteLoc);
5341 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005342 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005343 ErrorFound = NotABinaryOrUnaryExpression;
5344 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5345 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5346 }
5347 } else {
5348 ErrorFound = NotAScalarType;
5349 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5350 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5351 }
5352 } else {
5353 ErrorFound = NotAnExpression;
5354 NoteLoc = ErrorLoc = S->getLocStart();
5355 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5356 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005357 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005358 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5359 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5360 return true;
5361 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005362 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005363 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005364 // Build an update expression of form 'OpaqueValueExpr(x) binop
5365 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5366 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5367 auto *OVEX = new (SemaRef.getASTContext())
5368 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5369 auto *OVEExpr = new (SemaRef.getASTContext())
5370 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5371 auto Update =
5372 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5373 IsXLHSInRHSPart ? OVEExpr : OVEX);
5374 if (Update.isInvalid())
5375 return true;
5376 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5377 Sema::AA_Casting);
5378 if (Update.isInvalid())
5379 return true;
5380 UpdateExpr = Update.get();
5381 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005382 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005383}
5384
Alexey Bataev0162e452014-07-22 10:10:35 +00005385StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5386 Stmt *AStmt,
5387 SourceLocation StartLoc,
5388 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005389 if (!AStmt)
5390 return StmtError();
5391
David Majnemer9d168222016-08-05 17:44:54 +00005392 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005393 // 1.2.2 OpenMP Language Terminology
5394 // Structured block - An executable statement with a single entry at the
5395 // top and a single exit at the bottom.
5396 // The point of exit cannot be a branch out of the structured block.
5397 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005398 OpenMPClauseKind AtomicKind = OMPC_unknown;
5399 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005400 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005401 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005402 C->getClauseKind() == OMPC_update ||
5403 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005404 if (AtomicKind != OMPC_unknown) {
5405 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5406 << SourceRange(C->getLocStart(), C->getLocEnd());
5407 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5408 << getOpenMPClauseName(AtomicKind);
5409 } else {
5410 AtomicKind = C->getClauseKind();
5411 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005412 }
5413 }
5414 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005415
Alexey Bataev459dec02014-07-24 06:46:57 +00005416 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005417 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5418 Body = EWC->getSubExpr();
5419
Alexey Bataev62cec442014-11-18 10:14:22 +00005420 Expr *X = nullptr;
5421 Expr *V = nullptr;
5422 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005423 Expr *UE = nullptr;
5424 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005425 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005426 // OpenMP [2.12.6, atomic Construct]
5427 // In the next expressions:
5428 // * x and v (as applicable) are both l-value expressions with scalar type.
5429 // * During the execution of an atomic region, multiple syntactic
5430 // occurrences of x must designate the same storage location.
5431 // * Neither of v and expr (as applicable) may access the storage location
5432 // designated by x.
5433 // * Neither of x and expr (as applicable) may access the storage location
5434 // designated by v.
5435 // * expr is an expression with scalar type.
5436 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5437 // * binop, binop=, ++, and -- are not overloaded operators.
5438 // * The expression x binop expr must be numerically equivalent to x binop
5439 // (expr). This requirement is satisfied if the operators in expr have
5440 // precedence greater than binop, or by using parentheses around expr or
5441 // subexpressions of expr.
5442 // * The expression expr binop x must be numerically equivalent to (expr)
5443 // binop x. This requirement is satisfied if the operators in expr have
5444 // precedence equal to or greater than binop, or by using parentheses around
5445 // expr or subexpressions of expr.
5446 // * For forms that allow multiple occurrences of x, the number of times
5447 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005448 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005449 enum {
5450 NotAnExpression,
5451 NotAnAssignmentOp,
5452 NotAScalarType,
5453 NotAnLValue,
5454 NoError
5455 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005456 SourceLocation ErrorLoc, NoteLoc;
5457 SourceRange ErrorRange, NoteRange;
5458 // If clause is read:
5459 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005460 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5461 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005462 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5463 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5464 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5465 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5466 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5467 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5468 if (!X->isLValue() || !V->isLValue()) {
5469 auto NotLValueExpr = X->isLValue() ? V : X;
5470 ErrorFound = NotAnLValue;
5471 ErrorLoc = AtomicBinOp->getExprLoc();
5472 ErrorRange = AtomicBinOp->getSourceRange();
5473 NoteLoc = NotLValueExpr->getExprLoc();
5474 NoteRange = NotLValueExpr->getSourceRange();
5475 }
5476 } else if (!X->isInstantiationDependent() ||
5477 !V->isInstantiationDependent()) {
5478 auto NotScalarExpr =
5479 (X->isInstantiationDependent() || X->getType()->isScalarType())
5480 ? V
5481 : X;
5482 ErrorFound = NotAScalarType;
5483 ErrorLoc = AtomicBinOp->getExprLoc();
5484 ErrorRange = AtomicBinOp->getSourceRange();
5485 NoteLoc = NotScalarExpr->getExprLoc();
5486 NoteRange = NotScalarExpr->getSourceRange();
5487 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005488 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005489 ErrorFound = NotAnAssignmentOp;
5490 ErrorLoc = AtomicBody->getExprLoc();
5491 ErrorRange = AtomicBody->getSourceRange();
5492 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5493 : AtomicBody->getExprLoc();
5494 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5495 : AtomicBody->getSourceRange();
5496 }
5497 } else {
5498 ErrorFound = NotAnExpression;
5499 NoteLoc = ErrorLoc = Body->getLocStart();
5500 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005501 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005502 if (ErrorFound != NoError) {
5503 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5504 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005505 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5506 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005507 return StmtError();
5508 } else if (CurContext->isDependentContext())
5509 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005510 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005511 enum {
5512 NotAnExpression,
5513 NotAnAssignmentOp,
5514 NotAScalarType,
5515 NotAnLValue,
5516 NoError
5517 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005518 SourceLocation ErrorLoc, NoteLoc;
5519 SourceRange ErrorRange, NoteRange;
5520 // If clause is write:
5521 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005522 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5523 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005524 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5525 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005526 X = AtomicBinOp->getLHS();
5527 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005528 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5529 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5530 if (!X->isLValue()) {
5531 ErrorFound = NotAnLValue;
5532 ErrorLoc = AtomicBinOp->getExprLoc();
5533 ErrorRange = AtomicBinOp->getSourceRange();
5534 NoteLoc = X->getExprLoc();
5535 NoteRange = X->getSourceRange();
5536 }
5537 } else if (!X->isInstantiationDependent() ||
5538 !E->isInstantiationDependent()) {
5539 auto NotScalarExpr =
5540 (X->isInstantiationDependent() || X->getType()->isScalarType())
5541 ? E
5542 : X;
5543 ErrorFound = NotAScalarType;
5544 ErrorLoc = AtomicBinOp->getExprLoc();
5545 ErrorRange = AtomicBinOp->getSourceRange();
5546 NoteLoc = NotScalarExpr->getExprLoc();
5547 NoteRange = NotScalarExpr->getSourceRange();
5548 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005549 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005550 ErrorFound = NotAnAssignmentOp;
5551 ErrorLoc = AtomicBody->getExprLoc();
5552 ErrorRange = AtomicBody->getSourceRange();
5553 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5554 : AtomicBody->getExprLoc();
5555 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5556 : AtomicBody->getSourceRange();
5557 }
5558 } else {
5559 ErrorFound = NotAnExpression;
5560 NoteLoc = ErrorLoc = Body->getLocStart();
5561 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005562 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005563 if (ErrorFound != NoError) {
5564 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5565 << ErrorRange;
5566 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5567 << NoteRange;
5568 return StmtError();
5569 } else if (CurContext->isDependentContext())
5570 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005571 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005572 // If clause is update:
5573 // x++;
5574 // x--;
5575 // ++x;
5576 // --x;
5577 // x binop= expr;
5578 // x = x binop expr;
5579 // x = expr binop x;
5580 OpenMPAtomicUpdateChecker Checker(*this);
5581 if (Checker.checkStatement(
5582 Body, (AtomicKind == OMPC_update)
5583 ? diag::err_omp_atomic_update_not_expression_statement
5584 : diag::err_omp_atomic_not_expression_statement,
5585 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005586 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005587 if (!CurContext->isDependentContext()) {
5588 E = Checker.getExpr();
5589 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005590 UE = Checker.getUpdateExpr();
5591 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005592 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005593 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005594 enum {
5595 NotAnAssignmentOp,
5596 NotACompoundStatement,
5597 NotTwoSubstatements,
5598 NotASpecificExpression,
5599 NoError
5600 } ErrorFound = NoError;
5601 SourceLocation ErrorLoc, NoteLoc;
5602 SourceRange ErrorRange, NoteRange;
5603 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5604 // If clause is a capture:
5605 // v = x++;
5606 // v = x--;
5607 // v = ++x;
5608 // v = --x;
5609 // v = x binop= expr;
5610 // v = x = x binop expr;
5611 // v = x = expr binop x;
5612 auto *AtomicBinOp =
5613 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5614 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5615 V = AtomicBinOp->getLHS();
5616 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5617 OpenMPAtomicUpdateChecker Checker(*this);
5618 if (Checker.checkStatement(
5619 Body, diag::err_omp_atomic_capture_not_expression_statement,
5620 diag::note_omp_atomic_update))
5621 return StmtError();
5622 E = Checker.getExpr();
5623 X = Checker.getX();
5624 UE = Checker.getUpdateExpr();
5625 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5626 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005627 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005628 ErrorLoc = AtomicBody->getExprLoc();
5629 ErrorRange = AtomicBody->getSourceRange();
5630 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5631 : AtomicBody->getExprLoc();
5632 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5633 : AtomicBody->getSourceRange();
5634 ErrorFound = NotAnAssignmentOp;
5635 }
5636 if (ErrorFound != NoError) {
5637 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5638 << ErrorRange;
5639 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5640 return StmtError();
5641 } else if (CurContext->isDependentContext()) {
5642 UE = V = E = X = nullptr;
5643 }
5644 } else {
5645 // If clause is a capture:
5646 // { v = x; x = expr; }
5647 // { v = x; x++; }
5648 // { v = x; x--; }
5649 // { v = x; ++x; }
5650 // { v = x; --x; }
5651 // { v = x; x binop= expr; }
5652 // { v = x; x = x binop expr; }
5653 // { v = x; x = expr binop x; }
5654 // { x++; v = x; }
5655 // { x--; v = x; }
5656 // { ++x; v = x; }
5657 // { --x; v = x; }
5658 // { x binop= expr; v = x; }
5659 // { x = x binop expr; v = x; }
5660 // { x = expr binop x; v = x; }
5661 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5662 // Check that this is { expr1; expr2; }
5663 if (CS->size() == 2) {
5664 auto *First = CS->body_front();
5665 auto *Second = CS->body_back();
5666 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5667 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5668 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5669 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5670 // Need to find what subexpression is 'v' and what is 'x'.
5671 OpenMPAtomicUpdateChecker Checker(*this);
5672 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5673 BinaryOperator *BinOp = nullptr;
5674 if (IsUpdateExprFound) {
5675 BinOp = dyn_cast<BinaryOperator>(First);
5676 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5677 }
5678 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5679 // { v = x; x++; }
5680 // { v = x; x--; }
5681 // { v = x; ++x; }
5682 // { v = x; --x; }
5683 // { v = x; x binop= expr; }
5684 // { v = x; x = x binop expr; }
5685 // { v = x; x = expr binop x; }
5686 // Check that the first expression has form v = x.
5687 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5688 llvm::FoldingSetNodeID XId, PossibleXId;
5689 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5690 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5691 IsUpdateExprFound = XId == PossibleXId;
5692 if (IsUpdateExprFound) {
5693 V = BinOp->getLHS();
5694 X = Checker.getX();
5695 E = Checker.getExpr();
5696 UE = Checker.getUpdateExpr();
5697 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005698 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005699 }
5700 }
5701 if (!IsUpdateExprFound) {
5702 IsUpdateExprFound = !Checker.checkStatement(First);
5703 BinOp = nullptr;
5704 if (IsUpdateExprFound) {
5705 BinOp = dyn_cast<BinaryOperator>(Second);
5706 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5707 }
5708 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5709 // { x++; v = x; }
5710 // { x--; v = x; }
5711 // { ++x; v = x; }
5712 // { --x; v = x; }
5713 // { x binop= expr; v = x; }
5714 // { x = x binop expr; v = x; }
5715 // { x = expr binop x; v = x; }
5716 // Check that the second expression has form v = x.
5717 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5718 llvm::FoldingSetNodeID XId, PossibleXId;
5719 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5720 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5721 IsUpdateExprFound = XId == PossibleXId;
5722 if (IsUpdateExprFound) {
5723 V = BinOp->getLHS();
5724 X = Checker.getX();
5725 E = Checker.getExpr();
5726 UE = Checker.getUpdateExpr();
5727 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005728 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005729 }
5730 }
5731 }
5732 if (!IsUpdateExprFound) {
5733 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005734 auto *FirstExpr = dyn_cast<Expr>(First);
5735 auto *SecondExpr = dyn_cast<Expr>(Second);
5736 if (!FirstExpr || !SecondExpr ||
5737 !(FirstExpr->isInstantiationDependent() ||
5738 SecondExpr->isInstantiationDependent())) {
5739 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5740 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005741 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005742 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5743 : First->getLocStart();
5744 NoteRange = ErrorRange = FirstBinOp
5745 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005746 : SourceRange(ErrorLoc, ErrorLoc);
5747 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005748 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5749 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5750 ErrorFound = NotAnAssignmentOp;
5751 NoteLoc = ErrorLoc = SecondBinOp
5752 ? SecondBinOp->getOperatorLoc()
5753 : Second->getLocStart();
5754 NoteRange = ErrorRange =
5755 SecondBinOp ? SecondBinOp->getSourceRange()
5756 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005757 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005758 auto *PossibleXRHSInFirst =
5759 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5760 auto *PossibleXLHSInSecond =
5761 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5762 llvm::FoldingSetNodeID X1Id, X2Id;
5763 PossibleXRHSInFirst->Profile(X1Id, Context,
5764 /*Canonical=*/true);
5765 PossibleXLHSInSecond->Profile(X2Id, Context,
5766 /*Canonical=*/true);
5767 IsUpdateExprFound = X1Id == X2Id;
5768 if (IsUpdateExprFound) {
5769 V = FirstBinOp->getLHS();
5770 X = SecondBinOp->getLHS();
5771 E = SecondBinOp->getRHS();
5772 UE = nullptr;
5773 IsXLHSInRHSPart = false;
5774 IsPostfixUpdate = true;
5775 } else {
5776 ErrorFound = NotASpecificExpression;
5777 ErrorLoc = FirstBinOp->getExprLoc();
5778 ErrorRange = FirstBinOp->getSourceRange();
5779 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5780 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5781 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005782 }
5783 }
5784 }
5785 }
5786 } else {
5787 NoteLoc = ErrorLoc = Body->getLocStart();
5788 NoteRange = ErrorRange =
5789 SourceRange(Body->getLocStart(), Body->getLocStart());
5790 ErrorFound = NotTwoSubstatements;
5791 }
5792 } else {
5793 NoteLoc = ErrorLoc = Body->getLocStart();
5794 NoteRange = ErrorRange =
5795 SourceRange(Body->getLocStart(), Body->getLocStart());
5796 ErrorFound = NotACompoundStatement;
5797 }
5798 if (ErrorFound != NoError) {
5799 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5800 << ErrorRange;
5801 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5802 return StmtError();
5803 } else if (CurContext->isDependentContext()) {
5804 UE = V = E = X = nullptr;
5805 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005806 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005807 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005808
5809 getCurFunction()->setHasBranchProtectedScope();
5810
Alexey Bataev62cec442014-11-18 10:14:22 +00005811 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005812 X, V, E, UE, IsXLHSInRHSPart,
5813 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005814}
5815
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005816StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5817 Stmt *AStmt,
5818 SourceLocation StartLoc,
5819 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005820 if (!AStmt)
5821 return StmtError();
5822
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005823 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5824 // 1.2.2 OpenMP Language Terminology
5825 // Structured block - An executable statement with a single entry at the
5826 // top and a single exit at the bottom.
5827 // The point of exit cannot be a branch out of the structured block.
5828 // longjmp() and throw() must not violate the entry/exit criteria.
5829 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005830
Alexey Bataev13314bf2014-10-09 04:18:56 +00005831 // OpenMP [2.16, Nesting of Regions]
5832 // If specified, a teams construct must be contained within a target
5833 // construct. That target construct must contain no statements or directives
5834 // outside of the teams construct.
5835 if (DSAStack->hasInnerTeamsRegion()) {
5836 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5837 bool OMPTeamsFound = true;
5838 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5839 auto I = CS->body_begin();
5840 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005841 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005842 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5843 OMPTeamsFound = false;
5844 break;
5845 }
5846 ++I;
5847 }
5848 assert(I != CS->body_end() && "Not found statement");
5849 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005850 } else {
5851 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5852 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005853 }
5854 if (!OMPTeamsFound) {
5855 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5856 Diag(DSAStack->getInnerTeamsRegionLoc(),
5857 diag::note_omp_nested_teams_construct_here);
5858 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5859 << isa<OMPExecutableDirective>(S);
5860 return StmtError();
5861 }
5862 }
5863
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005864 getCurFunction()->setHasBranchProtectedScope();
5865
5866 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5867}
5868
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005869StmtResult
5870Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5871 Stmt *AStmt, SourceLocation StartLoc,
5872 SourceLocation EndLoc) {
5873 if (!AStmt)
5874 return StmtError();
5875
5876 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5877 // 1.2.2 OpenMP Language Terminology
5878 // Structured block - An executable statement with a single entry at the
5879 // top and a single exit at the bottom.
5880 // The point of exit cannot be a branch out of the structured block.
5881 // longjmp() and throw() must not violate the entry/exit criteria.
5882 CS->getCapturedDecl()->setNothrow();
5883
5884 getCurFunction()->setHasBranchProtectedScope();
5885
5886 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5887 AStmt);
5888}
5889
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005890StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5891 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5892 SourceLocation EndLoc,
5893 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5894 if (!AStmt)
5895 return StmtError();
5896
5897 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5898 // 1.2.2 OpenMP Language Terminology
5899 // Structured block - An executable statement with a single entry at the
5900 // top and a single exit at the bottom.
5901 // The point of exit cannot be a branch out of the structured block.
5902 // longjmp() and throw() must not violate the entry/exit criteria.
5903 CS->getCapturedDecl()->setNothrow();
5904
5905 OMPLoopDirective::HelperExprs B;
5906 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5907 // define the nested loops number.
5908 unsigned NestedLoopCount =
5909 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5910 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5911 VarsWithImplicitDSA, B);
5912 if (NestedLoopCount == 0)
5913 return StmtError();
5914
5915 assert((CurContext->isDependentContext() || B.builtAll()) &&
5916 "omp target parallel for loop exprs were not built");
5917
5918 if (!CurContext->isDependentContext()) {
5919 // Finalize the clauses that need pre-built expressions for CodeGen.
5920 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005921 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005922 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005923 B.NumIterations, *this, CurScope,
5924 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005925 return StmtError();
5926 }
5927 }
5928
5929 getCurFunction()->setHasBranchProtectedScope();
5930 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5931 NestedLoopCount, Clauses, AStmt,
5932 B, DSAStack->isCancelRegion());
5933}
5934
Samuel Antaodf67fc42016-01-19 19:15:56 +00005935/// \brief Check for existence of a map clause in the list of clauses.
5936static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5937 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5938 I != E; ++I) {
5939 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5940 return true;
5941 }
5942 }
5943
5944 return false;
5945}
5946
Michael Wong65f367f2015-07-21 13:44:28 +00005947StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5948 Stmt *AStmt,
5949 SourceLocation StartLoc,
5950 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005951 if (!AStmt)
5952 return StmtError();
5953
5954 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5955
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005956 // OpenMP [2.10.1, Restrictions, p. 97]
5957 // At least one map clause must appear on the directive.
5958 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005959 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5960 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005961 return StmtError();
5962 }
5963
Michael Wong65f367f2015-07-21 13:44:28 +00005964 getCurFunction()->setHasBranchProtectedScope();
5965
5966 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5967 AStmt);
5968}
5969
Samuel Antaodf67fc42016-01-19 19:15:56 +00005970StmtResult
5971Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5972 SourceLocation StartLoc,
5973 SourceLocation EndLoc) {
5974 // OpenMP [2.10.2, Restrictions, p. 99]
5975 // At least one map clause must appear on the directive.
5976 if (!HasMapClause(Clauses)) {
5977 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5978 << getOpenMPDirectiveName(OMPD_target_enter_data);
5979 return StmtError();
5980 }
5981
5982 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5983 Clauses);
5984}
5985
Samuel Antao72590762016-01-19 20:04:50 +00005986StmtResult
5987Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5988 SourceLocation StartLoc,
5989 SourceLocation EndLoc) {
5990 // OpenMP [2.10.3, Restrictions, p. 102]
5991 // At least one map clause must appear on the directive.
5992 if (!HasMapClause(Clauses)) {
5993 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5994 << getOpenMPDirectiveName(OMPD_target_exit_data);
5995 return StmtError();
5996 }
5997
5998 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5999}
6000
Samuel Antao686c70c2016-05-26 17:30:50 +00006001StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6002 SourceLocation StartLoc,
6003 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006004 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00006005 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00006006 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00006007 seenMotionClause = true;
6008 }
Samuel Antao686c70c2016-05-26 17:30:50 +00006009 if (!seenMotionClause) {
6010 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6011 return StmtError();
6012 }
6013 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6014}
6015
Alexey Bataev13314bf2014-10-09 04:18:56 +00006016StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6017 Stmt *AStmt, SourceLocation StartLoc,
6018 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006019 if (!AStmt)
6020 return StmtError();
6021
Alexey Bataev13314bf2014-10-09 04:18:56 +00006022 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6023 // 1.2.2 OpenMP Language Terminology
6024 // Structured block - An executable statement with a single entry at the
6025 // top and a single exit at the bottom.
6026 // The point of exit cannot be a branch out of the structured block.
6027 // longjmp() and throw() must not violate the entry/exit criteria.
6028 CS->getCapturedDecl()->setNothrow();
6029
6030 getCurFunction()->setHasBranchProtectedScope();
6031
6032 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6033}
6034
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006035StmtResult
6036Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6037 SourceLocation EndLoc,
6038 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006039 if (DSAStack->isParentNowaitRegion()) {
6040 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6041 return StmtError();
6042 }
6043 if (DSAStack->isParentOrderedRegion()) {
6044 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6045 return StmtError();
6046 }
6047 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6048 CancelRegion);
6049}
6050
Alexey Bataev87933c72015-09-18 08:07:34 +00006051StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6052 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006053 SourceLocation EndLoc,
6054 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006055 if (DSAStack->isParentNowaitRegion()) {
6056 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6057 return StmtError();
6058 }
6059 if (DSAStack->isParentOrderedRegion()) {
6060 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6061 return StmtError();
6062 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006063 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006064 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6065 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006066}
6067
Alexey Bataev382967a2015-12-08 12:06:20 +00006068static bool checkGrainsizeNumTasksClauses(Sema &S,
6069 ArrayRef<OMPClause *> Clauses) {
6070 OMPClause *PrevClause = nullptr;
6071 bool ErrorFound = false;
6072 for (auto *C : Clauses) {
6073 if (C->getClauseKind() == OMPC_grainsize ||
6074 C->getClauseKind() == OMPC_num_tasks) {
6075 if (!PrevClause)
6076 PrevClause = C;
6077 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6078 S.Diag(C->getLocStart(),
6079 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6080 << getOpenMPClauseName(C->getClauseKind())
6081 << getOpenMPClauseName(PrevClause->getClauseKind());
6082 S.Diag(PrevClause->getLocStart(),
6083 diag::note_omp_previous_grainsize_num_tasks)
6084 << getOpenMPClauseName(PrevClause->getClauseKind());
6085 ErrorFound = true;
6086 }
6087 }
6088 }
6089 return ErrorFound;
6090}
6091
Alexey Bataev49f6e782015-12-01 04:18:41 +00006092StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6093 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6094 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006095 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006096 if (!AStmt)
6097 return StmtError();
6098
6099 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6100 OMPLoopDirective::HelperExprs B;
6101 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6102 // define the nested loops number.
6103 unsigned NestedLoopCount =
6104 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006105 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006106 VarsWithImplicitDSA, B);
6107 if (NestedLoopCount == 0)
6108 return StmtError();
6109
6110 assert((CurContext->isDependentContext() || B.builtAll()) &&
6111 "omp for loop exprs were not built");
6112
Alexey Bataev382967a2015-12-08 12:06:20 +00006113 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6114 // The grainsize clause and num_tasks clause are mutually exclusive and may
6115 // not appear on the same taskloop directive.
6116 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6117 return StmtError();
6118
Alexey Bataev49f6e782015-12-01 04:18:41 +00006119 getCurFunction()->setHasBranchProtectedScope();
6120 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6121 NestedLoopCount, Clauses, AStmt, B);
6122}
6123
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006124StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6125 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6126 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006127 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006128 if (!AStmt)
6129 return StmtError();
6130
6131 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6132 OMPLoopDirective::HelperExprs B;
6133 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6134 // define the nested loops number.
6135 unsigned NestedLoopCount =
6136 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6137 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6138 VarsWithImplicitDSA, B);
6139 if (NestedLoopCount == 0)
6140 return StmtError();
6141
6142 assert((CurContext->isDependentContext() || B.builtAll()) &&
6143 "omp for loop exprs were not built");
6144
Alexey Bataev5a3af132016-03-29 08:58:54 +00006145 if (!CurContext->isDependentContext()) {
6146 // Finalize the clauses that need pre-built expressions for CodeGen.
6147 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006148 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006149 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006150 B.NumIterations, *this, CurScope,
6151 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006152 return StmtError();
6153 }
6154 }
6155
Alexey Bataev382967a2015-12-08 12:06:20 +00006156 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6157 // The grainsize clause and num_tasks clause are mutually exclusive and may
6158 // not appear on the same taskloop directive.
6159 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6160 return StmtError();
6161
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006162 getCurFunction()->setHasBranchProtectedScope();
6163 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6164 NestedLoopCount, Clauses, AStmt, B);
6165}
6166
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006167StmtResult Sema::ActOnOpenMPDistributeDirective(
6168 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6169 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006170 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006171 if (!AStmt)
6172 return StmtError();
6173
6174 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6175 OMPLoopDirective::HelperExprs B;
6176 // In presence of clause 'collapse' with number of loops, it will
6177 // define the nested loops number.
6178 unsigned NestedLoopCount =
6179 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6180 nullptr /*ordered not a clause on distribute*/, AStmt,
6181 *this, *DSAStack, VarsWithImplicitDSA, B);
6182 if (NestedLoopCount == 0)
6183 return StmtError();
6184
6185 assert((CurContext->isDependentContext() || B.builtAll()) &&
6186 "omp for loop exprs were not built");
6187
6188 getCurFunction()->setHasBranchProtectedScope();
6189 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6190 NestedLoopCount, Clauses, AStmt, B);
6191}
6192
Carlo Bertolli9925f152016-06-27 14:55:37 +00006193StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6195 SourceLocation EndLoc,
6196 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6197 if (!AStmt)
6198 return StmtError();
6199
6200 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6201 // 1.2.2 OpenMP Language Terminology
6202 // Structured block - An executable statement with a single entry at the
6203 // top and a single exit at the bottom.
6204 // The point of exit cannot be a branch out of the structured block.
6205 // longjmp() and throw() must not violate the entry/exit criteria.
6206 CS->getCapturedDecl()->setNothrow();
6207
6208 OMPLoopDirective::HelperExprs B;
6209 // In presence of clause 'collapse' with number of loops, it will
6210 // define the nested loops number.
6211 unsigned NestedLoopCount = CheckOpenMPLoop(
6212 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6213 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6214 VarsWithImplicitDSA, B);
6215 if (NestedLoopCount == 0)
6216 return StmtError();
6217
6218 assert((CurContext->isDependentContext() || B.builtAll()) &&
6219 "omp for loop exprs were not built");
6220
6221 getCurFunction()->setHasBranchProtectedScope();
6222 return OMPDistributeParallelForDirective::Create(
6223 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6224}
6225
Kelvin Li4a39add2016-07-05 05:00:15 +00006226StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6227 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6228 SourceLocation EndLoc,
6229 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6230 if (!AStmt)
6231 return StmtError();
6232
6233 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6234 // 1.2.2 OpenMP Language Terminology
6235 // Structured block - An executable statement with a single entry at the
6236 // top and a single exit at the bottom.
6237 // The point of exit cannot be a branch out of the structured block.
6238 // longjmp() and throw() must not violate the entry/exit criteria.
6239 CS->getCapturedDecl()->setNothrow();
6240
6241 OMPLoopDirective::HelperExprs B;
6242 // In presence of clause 'collapse' with number of loops, it will
6243 // define the nested loops number.
6244 unsigned NestedLoopCount = CheckOpenMPLoop(
6245 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6246 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6247 VarsWithImplicitDSA, B);
6248 if (NestedLoopCount == 0)
6249 return StmtError();
6250
6251 assert((CurContext->isDependentContext() || B.builtAll()) &&
6252 "omp for loop exprs were not built");
6253
Kelvin Lic5609492016-07-15 04:39:07 +00006254 if (checkSimdlenSafelenSpecified(*this, Clauses))
6255 return StmtError();
6256
Kelvin Li4a39add2016-07-05 05:00:15 +00006257 getCurFunction()->setHasBranchProtectedScope();
6258 return OMPDistributeParallelForSimdDirective::Create(
6259 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6260}
6261
Kelvin Li787f3fc2016-07-06 04:45:38 +00006262StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6263 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6264 SourceLocation EndLoc,
6265 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6266 if (!AStmt)
6267 return StmtError();
6268
6269 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6270 // 1.2.2 OpenMP Language Terminology
6271 // Structured block - An executable statement with a single entry at the
6272 // top and a single exit at the bottom.
6273 // The point of exit cannot be a branch out of the structured block.
6274 // longjmp() and throw() must not violate the entry/exit criteria.
6275 CS->getCapturedDecl()->setNothrow();
6276
6277 OMPLoopDirective::HelperExprs B;
6278 // In presence of clause 'collapse' with number of loops, it will
6279 // define the nested loops number.
6280 unsigned NestedLoopCount =
6281 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6282 nullptr /*ordered not a clause on distribute*/, AStmt,
6283 *this, *DSAStack, VarsWithImplicitDSA, B);
6284 if (NestedLoopCount == 0)
6285 return StmtError();
6286
6287 assert((CurContext->isDependentContext() || B.builtAll()) &&
6288 "omp for loop exprs were not built");
6289
Kelvin Lic5609492016-07-15 04:39:07 +00006290 if (checkSimdlenSafelenSpecified(*this, Clauses))
6291 return StmtError();
6292
Kelvin Li787f3fc2016-07-06 04:45:38 +00006293 getCurFunction()->setHasBranchProtectedScope();
6294 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6295 NestedLoopCount, Clauses, AStmt, B);
6296}
6297
Kelvin Lia579b912016-07-14 02:54:56 +00006298StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6300 SourceLocation EndLoc,
6301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6302 if (!AStmt)
6303 return StmtError();
6304
6305 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6306 // 1.2.2 OpenMP Language Terminology
6307 // Structured block - An executable statement with a single entry at the
6308 // top and a single exit at the bottom.
6309 // The point of exit cannot be a branch out of the structured block.
6310 // longjmp() and throw() must not violate the entry/exit criteria.
6311 CS->getCapturedDecl()->setNothrow();
6312
6313 OMPLoopDirective::HelperExprs B;
6314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6315 // define the nested loops number.
6316 unsigned NestedLoopCount = CheckOpenMPLoop(
6317 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6318 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6319 VarsWithImplicitDSA, B);
6320 if (NestedLoopCount == 0)
6321 return StmtError();
6322
6323 assert((CurContext->isDependentContext() || B.builtAll()) &&
6324 "omp target parallel for simd loop exprs were not built");
6325
6326 if (!CurContext->isDependentContext()) {
6327 // Finalize the clauses that need pre-built expressions for CodeGen.
6328 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006329 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6331 B.NumIterations, *this, CurScope,
6332 DSAStack))
6333 return StmtError();
6334 }
6335 }
Kelvin Lic5609492016-07-15 04:39:07 +00006336 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006337 return StmtError();
6338
6339 getCurFunction()->setHasBranchProtectedScope();
6340 return OMPTargetParallelForSimdDirective::Create(
6341 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6342}
6343
Kelvin Li986330c2016-07-20 22:57:10 +00006344StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6345 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6346 SourceLocation EndLoc,
6347 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6348 if (!AStmt)
6349 return StmtError();
6350
6351 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6352 // 1.2.2 OpenMP Language Terminology
6353 // Structured block - An executable statement with a single entry at the
6354 // top and a single exit at the bottom.
6355 // The point of exit cannot be a branch out of the structured block.
6356 // longjmp() and throw() must not violate the entry/exit criteria.
6357 CS->getCapturedDecl()->setNothrow();
6358
6359 OMPLoopDirective::HelperExprs B;
6360 // In presence of clause 'collapse' with number of loops, it will define the
6361 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006362 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006363 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6364 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6365 VarsWithImplicitDSA, B);
6366 if (NestedLoopCount == 0)
6367 return StmtError();
6368
6369 assert((CurContext->isDependentContext() || B.builtAll()) &&
6370 "omp target simd loop exprs were not built");
6371
6372 if (!CurContext->isDependentContext()) {
6373 // Finalize the clauses that need pre-built expressions for CodeGen.
6374 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006375 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006376 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6377 B.NumIterations, *this, CurScope,
6378 DSAStack))
6379 return StmtError();
6380 }
6381 }
6382
6383 if (checkSimdlenSafelenSpecified(*this, Clauses))
6384 return StmtError();
6385
6386 getCurFunction()->setHasBranchProtectedScope();
6387 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6388 NestedLoopCount, Clauses, AStmt, B);
6389}
6390
Kelvin Li02532872016-08-05 14:37:37 +00006391StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6392 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6393 SourceLocation EndLoc,
6394 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6395 if (!AStmt)
6396 return StmtError();
6397
6398 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6399 // 1.2.2 OpenMP Language Terminology
6400 // Structured block - An executable statement with a single entry at the
6401 // top and a single exit at the bottom.
6402 // The point of exit cannot be a branch out of the structured block.
6403 // longjmp() and throw() must not violate the entry/exit criteria.
6404 CS->getCapturedDecl()->setNothrow();
6405
6406 OMPLoopDirective::HelperExprs B;
6407 // In presence of clause 'collapse' with number of loops, it will
6408 // define the nested loops number.
6409 unsigned NestedLoopCount =
6410 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6411 nullptr /*ordered not a clause on distribute*/, AStmt,
6412 *this, *DSAStack, VarsWithImplicitDSA, B);
6413 if (NestedLoopCount == 0)
6414 return StmtError();
6415
6416 assert((CurContext->isDependentContext() || B.builtAll()) &&
6417 "omp teams distribute loop exprs were not built");
6418
6419 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006420 return OMPTeamsDistributeDirective::Create(
6421 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006422}
6423
Kelvin Li4e325f72016-10-25 12:50:55 +00006424StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6426 SourceLocation EndLoc,
6427 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6428 if (!AStmt)
6429 return StmtError();
6430
6431 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6432 // 1.2.2 OpenMP Language Terminology
6433 // Structured block - An executable statement with a single entry at the
6434 // top and a single exit at the bottom.
6435 // The point of exit cannot be a branch out of the structured block.
6436 // longjmp() and throw() must not violate the entry/exit criteria.
6437 CS->getCapturedDecl()->setNothrow();
6438
6439 OMPLoopDirective::HelperExprs B;
6440 // In presence of clause 'collapse' with number of loops, it will
6441 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006442 unsigned NestedLoopCount = CheckOpenMPLoop(
6443 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6444 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6445 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006446
6447 if (NestedLoopCount == 0)
6448 return StmtError();
6449
6450 assert((CurContext->isDependentContext() || B.builtAll()) &&
6451 "omp teams distribute simd loop exprs were not built");
6452
6453 if (!CurContext->isDependentContext()) {
6454 // Finalize the clauses that need pre-built expressions for CodeGen.
6455 for (auto C : Clauses) {
6456 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6457 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6458 B.NumIterations, *this, CurScope,
6459 DSAStack))
6460 return StmtError();
6461 }
6462 }
6463
6464 if (checkSimdlenSafelenSpecified(*this, Clauses))
6465 return StmtError();
6466
6467 getCurFunction()->setHasBranchProtectedScope();
6468 return OMPTeamsDistributeSimdDirective::Create(
6469 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6470}
6471
Kelvin Li579e41c2016-11-30 23:51:03 +00006472StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6473 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6474 SourceLocation EndLoc,
6475 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6476 if (!AStmt)
6477 return StmtError();
6478
6479 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6480 // 1.2.2 OpenMP Language Terminology
6481 // Structured block - An executable statement with a single entry at the
6482 // top and a single exit at the bottom.
6483 // The point of exit cannot be a branch out of the structured block.
6484 // longjmp() and throw() must not violate the entry/exit criteria.
6485 CS->getCapturedDecl()->setNothrow();
6486
6487 OMPLoopDirective::HelperExprs B;
6488 // In presence of clause 'collapse' with number of loops, it will
6489 // define the nested loops number.
6490 auto NestedLoopCount = CheckOpenMPLoop(
6491 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6492 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6493 VarsWithImplicitDSA, B);
6494
6495 if (NestedLoopCount == 0)
6496 return StmtError();
6497
6498 assert((CurContext->isDependentContext() || B.builtAll()) &&
6499 "omp for loop exprs were not built");
6500
6501 if (!CurContext->isDependentContext()) {
6502 // Finalize the clauses that need pre-built expressions for CodeGen.
6503 for (auto C : Clauses) {
6504 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6505 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6506 B.NumIterations, *this, CurScope,
6507 DSAStack))
6508 return StmtError();
6509 }
6510 }
6511
6512 if (checkSimdlenSafelenSpecified(*this, Clauses))
6513 return StmtError();
6514
6515 getCurFunction()->setHasBranchProtectedScope();
6516 return OMPTeamsDistributeParallelForSimdDirective::Create(
6517 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6518}
6519
Kelvin Li7ade93f2016-12-09 03:24:30 +00006520StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6522 SourceLocation EndLoc,
6523 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6524 if (!AStmt)
6525 return StmtError();
6526
6527 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6528 // 1.2.2 OpenMP Language Terminology
6529 // Structured block - An executable statement with a single entry at the
6530 // top and a single exit at the bottom.
6531 // The point of exit cannot be a branch out of the structured block.
6532 // longjmp() and throw() must not violate the entry/exit criteria.
6533 CS->getCapturedDecl()->setNothrow();
6534
6535 OMPLoopDirective::HelperExprs B;
6536 // In presence of clause 'collapse' with number of loops, it will
6537 // define the nested loops number.
6538 unsigned NestedLoopCount = CheckOpenMPLoop(
6539 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6540 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6541 VarsWithImplicitDSA, B);
6542
6543 if (NestedLoopCount == 0)
6544 return StmtError();
6545
6546 assert((CurContext->isDependentContext() || B.builtAll()) &&
6547 "omp for loop exprs were not built");
6548
6549 if (!CurContext->isDependentContext()) {
6550 // Finalize the clauses that need pre-built expressions for CodeGen.
6551 for (auto C : Clauses) {
6552 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6553 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6554 B.NumIterations, *this, CurScope,
6555 DSAStack))
6556 return StmtError();
6557 }
6558 }
6559
6560 getCurFunction()->setHasBranchProtectedScope();
6561 return OMPTeamsDistributeParallelForDirective::Create(
6562 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6563}
6564
Kelvin Libf594a52016-12-17 05:48:59 +00006565StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6566 Stmt *AStmt,
6567 SourceLocation StartLoc,
6568 SourceLocation EndLoc) {
6569 if (!AStmt)
6570 return StmtError();
6571
6572 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6573 // 1.2.2 OpenMP Language Terminology
6574 // Structured block - An executable statement with a single entry at the
6575 // top and a single exit at the bottom.
6576 // The point of exit cannot be a branch out of the structured block.
6577 // longjmp() and throw() must not violate the entry/exit criteria.
6578 CS->getCapturedDecl()->setNothrow();
6579
6580 getCurFunction()->setHasBranchProtectedScope();
6581
6582 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6583 AStmt);
6584}
6585
Kelvin Li83c451e2016-12-25 04:52:54 +00006586StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6588 SourceLocation EndLoc,
6589 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6590 if (!AStmt)
6591 return StmtError();
6592
6593 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6594 // 1.2.2 OpenMP Language Terminology
6595 // Structured block - An executable statement with a single entry at the
6596 // top and a single exit at the bottom.
6597 // The point of exit cannot be a branch out of the structured block.
6598 // longjmp() and throw() must not violate the entry/exit criteria.
6599 CS->getCapturedDecl()->setNothrow();
6600
6601 OMPLoopDirective::HelperExprs B;
6602 // In presence of clause 'collapse' with number of loops, it will
6603 // define the nested loops number.
6604 auto NestedLoopCount = CheckOpenMPLoop(
6605 OMPD_target_teams_distribute,
6606 getCollapseNumberExpr(Clauses),
6607 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6608 VarsWithImplicitDSA, B);
6609 if (NestedLoopCount == 0)
6610 return StmtError();
6611
6612 assert((CurContext->isDependentContext() || B.builtAll()) &&
6613 "omp target teams distribute loop exprs were not built");
6614
6615 getCurFunction()->setHasBranchProtectedScope();
6616 return OMPTargetTeamsDistributeDirective::Create(
6617 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6618}
6619
Kelvin Li80e8f562016-12-29 22:16:30 +00006620StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6622 SourceLocation EndLoc,
6623 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6624 if (!AStmt)
6625 return StmtError();
6626
6627 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6628 // 1.2.2 OpenMP Language Terminology
6629 // Structured block - An executable statement with a single entry at the
6630 // top and a single exit at the bottom.
6631 // The point of exit cannot be a branch out of the structured block.
6632 // longjmp() and throw() must not violate the entry/exit criteria.
6633 CS->getCapturedDecl()->setNothrow();
6634
6635 OMPLoopDirective::HelperExprs B;
6636 // In presence of clause 'collapse' with number of loops, it will
6637 // define the nested loops number.
6638 auto NestedLoopCount = CheckOpenMPLoop(
6639 OMPD_target_teams_distribute_parallel_for,
6640 getCollapseNumberExpr(Clauses),
6641 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6642 VarsWithImplicitDSA, B);
6643 if (NestedLoopCount == 0)
6644 return StmtError();
6645
6646 assert((CurContext->isDependentContext() || B.builtAll()) &&
6647 "omp target teams distribute parallel for loop exprs were not built");
6648
6649 if (!CurContext->isDependentContext()) {
6650 // Finalize the clauses that need pre-built expressions for CodeGen.
6651 for (auto C : Clauses) {
6652 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6653 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6654 B.NumIterations, *this, CurScope,
6655 DSAStack))
6656 return StmtError();
6657 }
6658 }
6659
6660 getCurFunction()->setHasBranchProtectedScope();
6661 return OMPTargetTeamsDistributeParallelForDirective::Create(
6662 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6663}
6664
Kelvin Li1851df52017-01-03 05:23:48 +00006665StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6667 SourceLocation EndLoc,
6668 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6669 if (!AStmt)
6670 return StmtError();
6671
6672 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6673 // 1.2.2 OpenMP Language Terminology
6674 // Structured block - An executable statement with a single entry at the
6675 // top and a single exit at the bottom.
6676 // The point of exit cannot be a branch out of the structured block.
6677 // longjmp() and throw() must not violate the entry/exit criteria.
6678 CS->getCapturedDecl()->setNothrow();
6679
6680 OMPLoopDirective::HelperExprs B;
6681 // In presence of clause 'collapse' with number of loops, it will
6682 // define the nested loops number.
6683 auto NestedLoopCount = CheckOpenMPLoop(
6684 OMPD_target_teams_distribute_parallel_for_simd,
6685 getCollapseNumberExpr(Clauses),
6686 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6687 VarsWithImplicitDSA, B);
6688 if (NestedLoopCount == 0)
6689 return StmtError();
6690
6691 assert((CurContext->isDependentContext() || B.builtAll()) &&
6692 "omp target teams distribute parallel for simd loop exprs were not "
6693 "built");
6694
6695 if (!CurContext->isDependentContext()) {
6696 // Finalize the clauses that need pre-built expressions for CodeGen.
6697 for (auto C : Clauses) {
6698 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6699 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6700 B.NumIterations, *this, CurScope,
6701 DSAStack))
6702 return StmtError();
6703 }
6704 }
6705
6706 getCurFunction()->setHasBranchProtectedScope();
6707 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6708 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6709}
6710
Kelvin Lida681182017-01-10 18:08:18 +00006711StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6713 SourceLocation EndLoc,
6714 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6715 if (!AStmt)
6716 return StmtError();
6717
6718 auto *CS = cast<CapturedStmt>(AStmt);
6719 // 1.2.2 OpenMP Language Terminology
6720 // Structured block - An executable statement with a single entry at the
6721 // top and a single exit at the bottom.
6722 // The point of exit cannot be a branch out of the structured block.
6723 // longjmp() and throw() must not violate the entry/exit criteria.
6724 CS->getCapturedDecl()->setNothrow();
6725
6726 OMPLoopDirective::HelperExprs B;
6727 // In presence of clause 'collapse' with number of loops, it will
6728 // define the nested loops number.
6729 auto NestedLoopCount = CheckOpenMPLoop(
6730 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6731 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6732 VarsWithImplicitDSA, B);
6733 if (NestedLoopCount == 0)
6734 return StmtError();
6735
6736 assert((CurContext->isDependentContext() || B.builtAll()) &&
6737 "omp target teams distribute simd loop exprs were not built");
6738
6739 getCurFunction()->setHasBranchProtectedScope();
6740 return OMPTargetTeamsDistributeSimdDirective::Create(
6741 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6742}
6743
Alexey Bataeved09d242014-05-28 05:53:51 +00006744OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006745 SourceLocation StartLoc,
6746 SourceLocation LParenLoc,
6747 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006748 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006749 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006750 case OMPC_final:
6751 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6752 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006753 case OMPC_num_threads:
6754 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6755 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006756 case OMPC_safelen:
6757 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6758 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006759 case OMPC_simdlen:
6760 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6761 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006762 case OMPC_collapse:
6763 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6764 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006765 case OMPC_ordered:
6766 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6767 break;
Michael Wonge710d542015-08-07 16:16:36 +00006768 case OMPC_device:
6769 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6770 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006771 case OMPC_num_teams:
6772 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6773 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006774 case OMPC_thread_limit:
6775 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6776 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006777 case OMPC_priority:
6778 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6779 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006780 case OMPC_grainsize:
6781 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6782 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006783 case OMPC_num_tasks:
6784 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6785 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006786 case OMPC_hint:
6787 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6788 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006789 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006790 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006791 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006792 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006793 case OMPC_private:
6794 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006795 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006796 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006797 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006798 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006799 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006800 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006801 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006802 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006803 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006804 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006805 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006806 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006807 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006808 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006809 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006810 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006811 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006812 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006813 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006814 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006815 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006816 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006817 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006818 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006819 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006820 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006821 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006822 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006823 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006824 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006825 llvm_unreachable("Clause is not allowed.");
6826 }
6827 return Res;
6828}
6829
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006830// An OpenMP directive such as 'target parallel' has two captured regions:
6831// for the 'target' and 'parallel' respectively. This function returns
6832// the region in which to capture expressions associated with a clause.
6833// A return value of OMPD_unknown signifies that the expression should not
6834// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006835static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6836 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6837 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006838 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6839
6840 switch (CKind) {
6841 case OMPC_if:
6842 switch (DKind) {
6843 case OMPD_target_parallel:
6844 // If this clause applies to the nested 'parallel' region, capture within
6845 // the 'target' region, otherwise do not capture.
6846 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6847 CaptureRegion = OMPD_target;
6848 break;
6849 case OMPD_cancel:
6850 case OMPD_parallel:
6851 case OMPD_parallel_sections:
6852 case OMPD_parallel_for:
6853 case OMPD_parallel_for_simd:
6854 case OMPD_target:
6855 case OMPD_target_simd:
6856 case OMPD_target_parallel_for:
6857 case OMPD_target_parallel_for_simd:
6858 case OMPD_target_teams:
6859 case OMPD_target_teams_distribute:
6860 case OMPD_target_teams_distribute_simd:
6861 case OMPD_target_teams_distribute_parallel_for:
6862 case OMPD_target_teams_distribute_parallel_for_simd:
6863 case OMPD_teams_distribute_parallel_for:
6864 case OMPD_teams_distribute_parallel_for_simd:
6865 case OMPD_distribute_parallel_for:
6866 case OMPD_distribute_parallel_for_simd:
6867 case OMPD_task:
6868 case OMPD_taskloop:
6869 case OMPD_taskloop_simd:
6870 case OMPD_target_data:
6871 case OMPD_target_enter_data:
6872 case OMPD_target_exit_data:
6873 case OMPD_target_update:
6874 // Do not capture if-clause expressions.
6875 break;
6876 case OMPD_threadprivate:
6877 case OMPD_taskyield:
6878 case OMPD_barrier:
6879 case OMPD_taskwait:
6880 case OMPD_cancellation_point:
6881 case OMPD_flush:
6882 case OMPD_declare_reduction:
6883 case OMPD_declare_simd:
6884 case OMPD_declare_target:
6885 case OMPD_end_declare_target:
6886 case OMPD_teams:
6887 case OMPD_simd:
6888 case OMPD_for:
6889 case OMPD_for_simd:
6890 case OMPD_sections:
6891 case OMPD_section:
6892 case OMPD_single:
6893 case OMPD_master:
6894 case OMPD_critical:
6895 case OMPD_taskgroup:
6896 case OMPD_distribute:
6897 case OMPD_ordered:
6898 case OMPD_atomic:
6899 case OMPD_distribute_simd:
6900 case OMPD_teams_distribute:
6901 case OMPD_teams_distribute_simd:
6902 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6903 case OMPD_unknown:
6904 llvm_unreachable("Unknown OpenMP directive");
6905 }
6906 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006907 case OMPC_num_threads:
6908 switch (DKind) {
6909 case OMPD_target_parallel:
6910 CaptureRegion = OMPD_target;
6911 break;
6912 case OMPD_cancel:
6913 case OMPD_parallel:
6914 case OMPD_parallel_sections:
6915 case OMPD_parallel_for:
6916 case OMPD_parallel_for_simd:
6917 case OMPD_target:
6918 case OMPD_target_simd:
6919 case OMPD_target_parallel_for:
6920 case OMPD_target_parallel_for_simd:
6921 case OMPD_target_teams:
6922 case OMPD_target_teams_distribute:
6923 case OMPD_target_teams_distribute_simd:
6924 case OMPD_target_teams_distribute_parallel_for:
6925 case OMPD_target_teams_distribute_parallel_for_simd:
6926 case OMPD_teams_distribute_parallel_for:
6927 case OMPD_teams_distribute_parallel_for_simd:
6928 case OMPD_distribute_parallel_for:
6929 case OMPD_distribute_parallel_for_simd:
6930 case OMPD_task:
6931 case OMPD_taskloop:
6932 case OMPD_taskloop_simd:
6933 case OMPD_target_data:
6934 case OMPD_target_enter_data:
6935 case OMPD_target_exit_data:
6936 case OMPD_target_update:
6937 // Do not capture num_threads-clause expressions.
6938 break;
6939 case OMPD_threadprivate:
6940 case OMPD_taskyield:
6941 case OMPD_barrier:
6942 case OMPD_taskwait:
6943 case OMPD_cancellation_point:
6944 case OMPD_flush:
6945 case OMPD_declare_reduction:
6946 case OMPD_declare_simd:
6947 case OMPD_declare_target:
6948 case OMPD_end_declare_target:
6949 case OMPD_teams:
6950 case OMPD_simd:
6951 case OMPD_for:
6952 case OMPD_for_simd:
6953 case OMPD_sections:
6954 case OMPD_section:
6955 case OMPD_single:
6956 case OMPD_master:
6957 case OMPD_critical:
6958 case OMPD_taskgroup:
6959 case OMPD_distribute:
6960 case OMPD_ordered:
6961 case OMPD_atomic:
6962 case OMPD_distribute_simd:
6963 case OMPD_teams_distribute:
6964 case OMPD_teams_distribute_simd:
6965 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6966 case OMPD_unknown:
6967 llvm_unreachable("Unknown OpenMP directive");
6968 }
6969 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00006970 case OMPC_num_teams:
6971 switch (DKind) {
6972 case OMPD_target_teams:
6973 CaptureRegion = OMPD_target;
6974 break;
6975 case OMPD_cancel:
6976 case OMPD_parallel:
6977 case OMPD_parallel_sections:
6978 case OMPD_parallel_for:
6979 case OMPD_parallel_for_simd:
6980 case OMPD_target:
6981 case OMPD_target_simd:
6982 case OMPD_target_parallel:
6983 case OMPD_target_parallel_for:
6984 case OMPD_target_parallel_for_simd:
6985 case OMPD_target_teams_distribute:
6986 case OMPD_target_teams_distribute_simd:
6987 case OMPD_target_teams_distribute_parallel_for:
6988 case OMPD_target_teams_distribute_parallel_for_simd:
6989 case OMPD_teams_distribute_parallel_for:
6990 case OMPD_teams_distribute_parallel_for_simd:
6991 case OMPD_distribute_parallel_for:
6992 case OMPD_distribute_parallel_for_simd:
6993 case OMPD_task:
6994 case OMPD_taskloop:
6995 case OMPD_taskloop_simd:
6996 case OMPD_target_data:
6997 case OMPD_target_enter_data:
6998 case OMPD_target_exit_data:
6999 case OMPD_target_update:
7000 case OMPD_teams:
7001 case OMPD_teams_distribute:
7002 case OMPD_teams_distribute_simd:
7003 // Do not capture num_teams-clause expressions.
7004 break;
7005 case OMPD_threadprivate:
7006 case OMPD_taskyield:
7007 case OMPD_barrier:
7008 case OMPD_taskwait:
7009 case OMPD_cancellation_point:
7010 case OMPD_flush:
7011 case OMPD_declare_reduction:
7012 case OMPD_declare_simd:
7013 case OMPD_declare_target:
7014 case OMPD_end_declare_target:
7015 case OMPD_simd:
7016 case OMPD_for:
7017 case OMPD_for_simd:
7018 case OMPD_sections:
7019 case OMPD_section:
7020 case OMPD_single:
7021 case OMPD_master:
7022 case OMPD_critical:
7023 case OMPD_taskgroup:
7024 case OMPD_distribute:
7025 case OMPD_ordered:
7026 case OMPD_atomic:
7027 case OMPD_distribute_simd:
7028 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7029 case OMPD_unknown:
7030 llvm_unreachable("Unknown OpenMP directive");
7031 }
7032 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007033 case OMPC_thread_limit:
7034 switch (DKind) {
7035 case OMPD_target_teams:
7036 CaptureRegion = OMPD_target;
7037 break;
7038 case OMPD_cancel:
7039 case OMPD_parallel:
7040 case OMPD_parallel_sections:
7041 case OMPD_parallel_for:
7042 case OMPD_parallel_for_simd:
7043 case OMPD_target:
7044 case OMPD_target_simd:
7045 case OMPD_target_parallel:
7046 case OMPD_target_parallel_for:
7047 case OMPD_target_parallel_for_simd:
7048 case OMPD_target_teams_distribute:
7049 case OMPD_target_teams_distribute_simd:
7050 case OMPD_target_teams_distribute_parallel_for:
7051 case OMPD_target_teams_distribute_parallel_for_simd:
7052 case OMPD_teams_distribute_parallel_for:
7053 case OMPD_teams_distribute_parallel_for_simd:
7054 case OMPD_distribute_parallel_for:
7055 case OMPD_distribute_parallel_for_simd:
7056 case OMPD_task:
7057 case OMPD_taskloop:
7058 case OMPD_taskloop_simd:
7059 case OMPD_target_data:
7060 case OMPD_target_enter_data:
7061 case OMPD_target_exit_data:
7062 case OMPD_target_update:
7063 case OMPD_teams:
7064 case OMPD_teams_distribute:
7065 case OMPD_teams_distribute_simd:
7066 // Do not capture thread_limit-clause expressions.
7067 break;
7068 case OMPD_threadprivate:
7069 case OMPD_taskyield:
7070 case OMPD_barrier:
7071 case OMPD_taskwait:
7072 case OMPD_cancellation_point:
7073 case OMPD_flush:
7074 case OMPD_declare_reduction:
7075 case OMPD_declare_simd:
7076 case OMPD_declare_target:
7077 case OMPD_end_declare_target:
7078 case OMPD_simd:
7079 case OMPD_for:
7080 case OMPD_for_simd:
7081 case OMPD_sections:
7082 case OMPD_section:
7083 case OMPD_single:
7084 case OMPD_master:
7085 case OMPD_critical:
7086 case OMPD_taskgroup:
7087 case OMPD_distribute:
7088 case OMPD_ordered:
7089 case OMPD_atomic:
7090 case OMPD_distribute_simd:
7091 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7092 case OMPD_unknown:
7093 llvm_unreachable("Unknown OpenMP directive");
7094 }
7095 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007096 case OMPC_schedule:
7097 case OMPC_dist_schedule:
7098 case OMPC_firstprivate:
7099 case OMPC_lastprivate:
7100 case OMPC_reduction:
7101 case OMPC_linear:
7102 case OMPC_default:
7103 case OMPC_proc_bind:
7104 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007105 case OMPC_safelen:
7106 case OMPC_simdlen:
7107 case OMPC_collapse:
7108 case OMPC_private:
7109 case OMPC_shared:
7110 case OMPC_aligned:
7111 case OMPC_copyin:
7112 case OMPC_copyprivate:
7113 case OMPC_ordered:
7114 case OMPC_nowait:
7115 case OMPC_untied:
7116 case OMPC_mergeable:
7117 case OMPC_threadprivate:
7118 case OMPC_flush:
7119 case OMPC_read:
7120 case OMPC_write:
7121 case OMPC_update:
7122 case OMPC_capture:
7123 case OMPC_seq_cst:
7124 case OMPC_depend:
7125 case OMPC_device:
7126 case OMPC_threads:
7127 case OMPC_simd:
7128 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007129 case OMPC_priority:
7130 case OMPC_grainsize:
7131 case OMPC_nogroup:
7132 case OMPC_num_tasks:
7133 case OMPC_hint:
7134 case OMPC_defaultmap:
7135 case OMPC_unknown:
7136 case OMPC_uniform:
7137 case OMPC_to:
7138 case OMPC_from:
7139 case OMPC_use_device_ptr:
7140 case OMPC_is_device_ptr:
7141 llvm_unreachable("Unexpected OpenMP clause.");
7142 }
7143 return CaptureRegion;
7144}
7145
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007146OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7147 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007148 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007149 SourceLocation NameModifierLoc,
7150 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007151 SourceLocation EndLoc) {
7152 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007153 Stmt *HelperValStmt = nullptr;
7154 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007155 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7156 !Condition->isInstantiationDependent() &&
7157 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007158 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007159 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007160 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007161
Richard Smith03a4aa32016-06-23 19:02:52 +00007162 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007163
7164 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7165 CaptureRegion =
7166 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7167 if (CaptureRegion != OMPD_unknown) {
7168 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7169 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7170 HelperValStmt = buildPreInits(Context, Captures);
7171 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007172 }
7173
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007174 return new (Context)
7175 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7176 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007177}
7178
Alexey Bataev3778b602014-07-17 07:32:53 +00007179OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7180 SourceLocation StartLoc,
7181 SourceLocation LParenLoc,
7182 SourceLocation EndLoc) {
7183 Expr *ValExpr = Condition;
7184 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7185 !Condition->isInstantiationDependent() &&
7186 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007187 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007188 if (Val.isInvalid())
7189 return nullptr;
7190
Richard Smith03a4aa32016-06-23 19:02:52 +00007191 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007192 }
7193
7194 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7195}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007196ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7197 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007198 if (!Op)
7199 return ExprError();
7200
7201 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7202 public:
7203 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007204 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007205 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7206 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007207 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7208 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007209 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7210 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007211 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7212 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007213 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7214 QualType T,
7215 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007216 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7217 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007218 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7219 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007220 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007221 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007222 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007223 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7224 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007225 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7226 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007227 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7228 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007229 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007230 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007231 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007232 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7233 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007234 llvm_unreachable("conversion functions are permitted");
7235 }
7236 } ConvertDiagnoser;
7237 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7238}
7239
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007240static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007241 OpenMPClauseKind CKind,
7242 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007243 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7244 !ValExpr->isInstantiationDependent()) {
7245 SourceLocation Loc = ValExpr->getExprLoc();
7246 ExprResult Value =
7247 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7248 if (Value.isInvalid())
7249 return false;
7250
7251 ValExpr = Value.get();
7252 // The expression must evaluate to a non-negative integer value.
7253 llvm::APSInt Result;
7254 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007255 Result.isSigned() &&
7256 !((!StrictlyPositive && Result.isNonNegative()) ||
7257 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007258 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007259 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7260 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007261 return false;
7262 }
7263 }
7264 return true;
7265}
7266
Alexey Bataev568a8332014-03-06 06:15:19 +00007267OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7268 SourceLocation StartLoc,
7269 SourceLocation LParenLoc,
7270 SourceLocation EndLoc) {
7271 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007272 Stmt *HelperValStmt = nullptr;
7273 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007274
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007275 // OpenMP [2.5, Restrictions]
7276 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007277 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7278 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007279 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007280
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007281 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7282 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7283 if (CaptureRegion != OMPD_unknown) {
7284 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7285 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7286 HelperValStmt = buildPreInits(Context, Captures);
7287 }
7288
7289 return new (Context) OMPNumThreadsClause(
7290 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007291}
7292
Alexey Bataev62c87d22014-03-21 04:51:18 +00007293ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007294 OpenMPClauseKind CKind,
7295 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007296 if (!E)
7297 return ExprError();
7298 if (E->isValueDependent() || E->isTypeDependent() ||
7299 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007300 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007301 llvm::APSInt Result;
7302 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7303 if (ICE.isInvalid())
7304 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007305 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7306 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007307 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007308 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7309 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007310 return ExprError();
7311 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007312 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7313 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7314 << E->getSourceRange();
7315 return ExprError();
7316 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007317 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7318 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007319 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007320 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007321 return ICE;
7322}
7323
7324OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7325 SourceLocation LParenLoc,
7326 SourceLocation EndLoc) {
7327 // OpenMP [2.8.1, simd construct, Description]
7328 // The parameter of the safelen clause must be a constant
7329 // positive integer expression.
7330 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7331 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007332 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007333 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007334 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007335}
7336
Alexey Bataev66b15b52015-08-21 11:14:16 +00007337OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7338 SourceLocation LParenLoc,
7339 SourceLocation EndLoc) {
7340 // OpenMP [2.8.1, simd construct, Description]
7341 // The parameter of the simdlen clause must be a constant
7342 // positive integer expression.
7343 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7344 if (Simdlen.isInvalid())
7345 return nullptr;
7346 return new (Context)
7347 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7348}
7349
Alexander Musman64d33f12014-06-04 07:53:32 +00007350OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7351 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007352 SourceLocation LParenLoc,
7353 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007354 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007355 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007356 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007357 // The parameter of the collapse clause must be a constant
7358 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007359 ExprResult NumForLoopsResult =
7360 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7361 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007362 return nullptr;
7363 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007364 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007365}
7366
Alexey Bataev10e775f2015-07-30 11:36:16 +00007367OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7368 SourceLocation EndLoc,
7369 SourceLocation LParenLoc,
7370 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007371 // OpenMP [2.7.1, loop construct, Description]
7372 // OpenMP [2.8.1, simd construct, Description]
7373 // OpenMP [2.9.6, distribute construct, Description]
7374 // The parameter of the ordered clause must be a constant
7375 // positive integer expression if any.
7376 if (NumForLoops && LParenLoc.isValid()) {
7377 ExprResult NumForLoopsResult =
7378 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7379 if (NumForLoopsResult.isInvalid())
7380 return nullptr;
7381 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007382 } else
7383 NumForLoops = nullptr;
7384 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007385 return new (Context)
7386 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7387}
7388
Alexey Bataeved09d242014-05-28 05:53:51 +00007389OMPClause *Sema::ActOnOpenMPSimpleClause(
7390 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7391 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007392 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007393 switch (Kind) {
7394 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007395 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007396 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7397 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007398 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007399 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007400 Res = ActOnOpenMPProcBindClause(
7401 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7402 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007403 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007404 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007405 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007406 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007407 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007408 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007409 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007410 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007411 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007412 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007413 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007414 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007415 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007416 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007417 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007418 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007419 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007420 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007421 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007422 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007423 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007424 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007425 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007426 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007427 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007428 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007429 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007430 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007431 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007432 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007433 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007434 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007435 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007436 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007437 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007438 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007439 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007440 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007441 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007442 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007443 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007444 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007445 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007446 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007447 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007448 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007449 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007450 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007451 llvm_unreachable("Clause is not allowed.");
7452 }
7453 return Res;
7454}
7455
Alexey Bataev6402bca2015-12-28 07:25:51 +00007456static std::string
7457getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7458 ArrayRef<unsigned> Exclude = llvm::None) {
7459 std::string Values;
7460 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7461 unsigned Skipped = Exclude.size();
7462 auto S = Exclude.begin(), E = Exclude.end();
7463 for (unsigned i = First; i < Last; ++i) {
7464 if (std::find(S, E, i) != E) {
7465 --Skipped;
7466 continue;
7467 }
7468 Values += "'";
7469 Values += getOpenMPSimpleClauseTypeName(K, i);
7470 Values += "'";
7471 if (i == Bound - Skipped)
7472 Values += " or ";
7473 else if (i != Bound + 1 - Skipped)
7474 Values += ", ";
7475 }
7476 return Values;
7477}
7478
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007479OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7480 SourceLocation KindKwLoc,
7481 SourceLocation StartLoc,
7482 SourceLocation LParenLoc,
7483 SourceLocation EndLoc) {
7484 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007485 static_assert(OMPC_DEFAULT_unknown > 0,
7486 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007487 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007488 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7489 /*Last=*/OMPC_DEFAULT_unknown)
7490 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007491 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007492 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007493 switch (Kind) {
7494 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007495 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007496 break;
7497 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007498 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007499 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007500 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007501 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007502 break;
7503 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007504 return new (Context)
7505 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007506}
7507
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007508OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7509 SourceLocation KindKwLoc,
7510 SourceLocation StartLoc,
7511 SourceLocation LParenLoc,
7512 SourceLocation EndLoc) {
7513 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007514 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007515 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7516 /*Last=*/OMPC_PROC_BIND_unknown)
7517 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007518 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007519 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007520 return new (Context)
7521 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007522}
7523
Alexey Bataev56dafe82014-06-20 07:16:17 +00007524OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007525 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007526 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007527 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007528 SourceLocation EndLoc) {
7529 OMPClause *Res = nullptr;
7530 switch (Kind) {
7531 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007532 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7533 assert(Argument.size() == NumberOfElements &&
7534 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007535 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007536 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7537 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7538 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7539 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7540 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007541 break;
7542 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007543 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7544 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7545 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7546 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007547 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007548 case OMPC_dist_schedule:
7549 Res = ActOnOpenMPDistScheduleClause(
7550 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7551 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7552 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007553 case OMPC_defaultmap:
7554 enum { Modifier, DefaultmapKind };
7555 Res = ActOnOpenMPDefaultmapClause(
7556 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7557 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007558 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7559 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007560 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007561 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007562 case OMPC_num_threads:
7563 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007564 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007565 case OMPC_collapse:
7566 case OMPC_default:
7567 case OMPC_proc_bind:
7568 case OMPC_private:
7569 case OMPC_firstprivate:
7570 case OMPC_lastprivate:
7571 case OMPC_shared:
7572 case OMPC_reduction:
7573 case OMPC_linear:
7574 case OMPC_aligned:
7575 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007576 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007577 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007578 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007579 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007580 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007581 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007582 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007583 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007584 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007585 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007586 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007587 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007588 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007589 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007590 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007591 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007592 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007593 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007594 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007595 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007596 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007597 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007598 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007599 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007600 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007601 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007602 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007603 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007604 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007605 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007606 llvm_unreachable("Clause is not allowed.");
7607 }
7608 return Res;
7609}
7610
Alexey Bataev6402bca2015-12-28 07:25:51 +00007611static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7612 OpenMPScheduleClauseModifier M2,
7613 SourceLocation M1Loc, SourceLocation M2Loc) {
7614 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7615 SmallVector<unsigned, 2> Excluded;
7616 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7617 Excluded.push_back(M2);
7618 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7619 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7620 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7621 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7622 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7623 << getListOfPossibleValues(OMPC_schedule,
7624 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7625 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7626 Excluded)
7627 << getOpenMPClauseName(OMPC_schedule);
7628 return true;
7629 }
7630 return false;
7631}
7632
Alexey Bataev56dafe82014-06-20 07:16:17 +00007633OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007634 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007635 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007636 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7637 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7638 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7639 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7640 return nullptr;
7641 // OpenMP, 2.7.1, Loop Construct, Restrictions
7642 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7643 // but not both.
7644 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7645 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7646 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7647 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7648 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7649 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7650 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7651 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7652 return nullptr;
7653 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007654 if (Kind == OMPC_SCHEDULE_unknown) {
7655 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007656 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7657 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7658 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7659 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7660 Exclude);
7661 } else {
7662 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7663 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007664 }
7665 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7666 << Values << getOpenMPClauseName(OMPC_schedule);
7667 return nullptr;
7668 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007669 // OpenMP, 2.7.1, Loop Construct, Restrictions
7670 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7671 // schedule(guided).
7672 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7673 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7674 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7675 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7676 diag::err_omp_schedule_nonmonotonic_static);
7677 return nullptr;
7678 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007679 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007680 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007681 if (ChunkSize) {
7682 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7683 !ChunkSize->isInstantiationDependent() &&
7684 !ChunkSize->containsUnexpandedParameterPack()) {
7685 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7686 ExprResult Val =
7687 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7688 if (Val.isInvalid())
7689 return nullptr;
7690
7691 ValExpr = Val.get();
7692
7693 // OpenMP [2.7.1, Restrictions]
7694 // chunk_size must be a loop invariant integer expression with a positive
7695 // value.
7696 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007697 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7698 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7699 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007700 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007701 return nullptr;
7702 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007703 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7704 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007705 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7706 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7707 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007708 }
7709 }
7710 }
7711
Alexey Bataev6402bca2015-12-28 07:25:51 +00007712 return new (Context)
7713 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007714 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007715}
7716
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007717OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7718 SourceLocation StartLoc,
7719 SourceLocation EndLoc) {
7720 OMPClause *Res = nullptr;
7721 switch (Kind) {
7722 case OMPC_ordered:
7723 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7724 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007725 case OMPC_nowait:
7726 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7727 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007728 case OMPC_untied:
7729 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7730 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007731 case OMPC_mergeable:
7732 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7733 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007734 case OMPC_read:
7735 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7736 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007737 case OMPC_write:
7738 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7739 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007740 case OMPC_update:
7741 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7742 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007743 case OMPC_capture:
7744 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7745 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007746 case OMPC_seq_cst:
7747 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7748 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007749 case OMPC_threads:
7750 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7751 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007752 case OMPC_simd:
7753 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7754 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007755 case OMPC_nogroup:
7756 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7757 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007758 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007759 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007760 case OMPC_num_threads:
7761 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007762 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007763 case OMPC_collapse:
7764 case OMPC_schedule:
7765 case OMPC_private:
7766 case OMPC_firstprivate:
7767 case OMPC_lastprivate:
7768 case OMPC_shared:
7769 case OMPC_reduction:
7770 case OMPC_linear:
7771 case OMPC_aligned:
7772 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007773 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007774 case OMPC_default:
7775 case OMPC_proc_bind:
7776 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007777 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007778 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007779 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007780 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007781 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007782 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007783 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007784 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007785 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007786 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007787 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007788 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007789 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007790 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007791 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007792 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007793 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007794 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007795 llvm_unreachable("Clause is not allowed.");
7796 }
7797 return Res;
7798}
7799
Alexey Bataev236070f2014-06-20 11:19:47 +00007800OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7801 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007802 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007803 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7804}
7805
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007806OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7807 SourceLocation EndLoc) {
7808 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7809}
7810
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007811OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7812 SourceLocation EndLoc) {
7813 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7814}
7815
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007816OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7817 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007818 return new (Context) OMPReadClause(StartLoc, EndLoc);
7819}
7820
Alexey Bataevdea47612014-07-23 07:46:59 +00007821OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7822 SourceLocation EndLoc) {
7823 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7824}
7825
Alexey Bataev67a4f222014-07-23 10:25:33 +00007826OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7827 SourceLocation EndLoc) {
7828 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7829}
7830
Alexey Bataev459dec02014-07-24 06:46:57 +00007831OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7832 SourceLocation EndLoc) {
7833 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7834}
7835
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007836OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7837 SourceLocation EndLoc) {
7838 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7839}
7840
Alexey Bataev346265e2015-09-25 10:37:12 +00007841OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7842 SourceLocation EndLoc) {
7843 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7844}
7845
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007846OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7847 SourceLocation EndLoc) {
7848 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7849}
7850
Alexey Bataevb825de12015-12-07 10:51:44 +00007851OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7852 SourceLocation EndLoc) {
7853 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7854}
7855
Alexey Bataevc5e02582014-06-16 07:08:35 +00007856OMPClause *Sema::ActOnOpenMPVarListClause(
7857 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7858 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7859 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007860 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007861 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7862 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7863 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007864 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007865 switch (Kind) {
7866 case OMPC_private:
7867 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7868 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007869 case OMPC_firstprivate:
7870 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7871 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007872 case OMPC_lastprivate:
7873 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7874 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007875 case OMPC_shared:
7876 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7877 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007878 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007879 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7880 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007881 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007882 case OMPC_linear:
7883 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007884 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007885 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007886 case OMPC_aligned:
7887 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7888 ColonLoc, EndLoc);
7889 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007890 case OMPC_copyin:
7891 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7892 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007893 case OMPC_copyprivate:
7894 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7895 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007896 case OMPC_flush:
7897 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7898 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007899 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007900 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007901 StartLoc, LParenLoc, EndLoc);
7902 break;
7903 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007904 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7905 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7906 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007907 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007908 case OMPC_to:
7909 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7910 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007911 case OMPC_from:
7912 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7913 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007914 case OMPC_use_device_ptr:
7915 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7916 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007917 case OMPC_is_device_ptr:
7918 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7919 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007920 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007921 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007922 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007923 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007924 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007925 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007926 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007927 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007928 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007929 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007930 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007931 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007932 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007933 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007934 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007935 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007936 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007937 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007938 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007939 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007940 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007941 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007942 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007943 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007944 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007945 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007946 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007947 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007948 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007949 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007950 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007951 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007952 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007953 llvm_unreachable("Clause is not allowed.");
7954 }
7955 return Res;
7956}
7957
Alexey Bataev90c228f2016-02-08 09:29:13 +00007958ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007959 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007960 ExprResult Res = BuildDeclRefExpr(
7961 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7962 if (!Res.isUsable())
7963 return ExprError();
7964 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7965 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7966 if (!Res.isUsable())
7967 return ExprError();
7968 }
7969 if (VK != VK_LValue && Res.get()->isGLValue()) {
7970 Res = DefaultLvalueConversion(Res.get());
7971 if (!Res.isUsable())
7972 return ExprError();
7973 }
7974 return Res;
7975}
7976
Alexey Bataev60da77e2016-02-29 05:54:20 +00007977static std::pair<ValueDecl *, bool>
7978getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7979 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007980 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7981 RefExpr->containsUnexpandedParameterPack())
7982 return std::make_pair(nullptr, true);
7983
Alexey Bataevd985eda2016-02-10 11:29:16 +00007984 // OpenMP [3.1, C/C++]
7985 // A list item is a variable name.
7986 // OpenMP [2.9.3.3, Restrictions, p.1]
7987 // A variable that is part of another variable (as an array or
7988 // structure element) cannot appear in a private clause.
7989 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007990 enum {
7991 NoArrayExpr = -1,
7992 ArraySubscript = 0,
7993 OMPArraySection = 1
7994 } IsArrayExpr = NoArrayExpr;
7995 if (AllowArraySection) {
7996 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7997 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7998 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7999 Base = TempASE->getBase()->IgnoreParenImpCasts();
8000 RefExpr = Base;
8001 IsArrayExpr = ArraySubscript;
8002 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8003 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8004 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8005 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8006 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8007 Base = TempASE->getBase()->IgnoreParenImpCasts();
8008 RefExpr = Base;
8009 IsArrayExpr = OMPArraySection;
8010 }
8011 }
8012 ELoc = RefExpr->getExprLoc();
8013 ERange = RefExpr->getSourceRange();
8014 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008015 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8016 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8017 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8018 (S.getCurrentThisType().isNull() || !ME ||
8019 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8020 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008021 if (IsArrayExpr != NoArrayExpr)
8022 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8023 << ERange;
8024 else {
8025 S.Diag(ELoc,
8026 AllowArraySection
8027 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8028 : diag::err_omp_expected_var_name_member_expr)
8029 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8030 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008031 return std::make_pair(nullptr, false);
8032 }
8033 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
8034}
8035
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008036OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8037 SourceLocation StartLoc,
8038 SourceLocation LParenLoc,
8039 SourceLocation EndLoc) {
8040 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008041 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008042 for (auto &RefExpr : VarList) {
8043 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008044 SourceLocation ELoc;
8045 SourceRange ERange;
8046 Expr *SimpleRefExpr = RefExpr;
8047 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008048 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008049 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008050 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008051 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008052 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008053 ValueDecl *D = Res.first;
8054 if (!D)
8055 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008056
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008057 QualType Type = D->getType();
8058 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008059
8060 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8061 // A variable that appears in a private clause must not have an incomplete
8062 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008063 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008064 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008065 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008066
Alexey Bataev758e55e2013-09-06 18:03:48 +00008067 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8068 // in a Construct]
8069 // Variables with the predetermined data-sharing attributes may not be
8070 // listed in data-sharing attributes clauses, except for the cases
8071 // listed below. For these exceptions only, listing a predetermined
8072 // variable in a data-sharing attribute clause is allowed and overrides
8073 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008074 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008075 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008076 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8077 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008078 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008079 continue;
8080 }
8081
Kelvin Libf594a52016-12-17 05:48:59 +00008082 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008083 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008084 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008085 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008086 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8087 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008088 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008089 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008090 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008091 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008092 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008093 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008094 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008095 continue;
8096 }
8097
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008098 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8099 // A list item cannot appear in both a map clause and a data-sharing
8100 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008101 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008102 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008103 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008104 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008105 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008106 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008107 CurrDir == OMPD_target_parallel_for_simd ||
8108 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008109 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008110 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008111 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008112 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8113 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8114 ConflictKind = WhereFoundClauseKind;
8115 return true;
8116 })) {
8117 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008118 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008119 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008120 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008121 ReportOriginalDSA(*this, DSAStack, D, DVar);
8122 continue;
8123 }
8124 }
8125
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008126 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8127 // A variable of class type (or array thereof) that appears in a private
8128 // clause requires an accessible, unambiguous default constructor for the
8129 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008130 // Generate helper private variable and initialize it with the default
8131 // value. The address of the original variable is replaced by the address of
8132 // the new private variable in CodeGen. This new variable is not added to
8133 // IdResolver, so the code in the OpenMP region uses original variable for
8134 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008135 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008136 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8137 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008138 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008139 if (VDPrivate->isInvalidDecl())
8140 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008141 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008142 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008143
Alexey Bataev90c228f2016-02-08 09:29:13 +00008144 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008145 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008146 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008147 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008148 Vars.push_back((VD || CurContext->isDependentContext())
8149 ? RefExpr->IgnoreParens()
8150 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008151 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008152 }
8153
Alexey Bataeved09d242014-05-28 05:53:51 +00008154 if (Vars.empty())
8155 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008156
Alexey Bataev03b340a2014-10-21 03:16:40 +00008157 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8158 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008159}
8160
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008161namespace {
8162class DiagsUninitializedSeveretyRAII {
8163private:
8164 DiagnosticsEngine &Diags;
8165 SourceLocation SavedLoc;
8166 bool IsIgnored;
8167
8168public:
8169 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8170 bool IsIgnored)
8171 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8172 if (!IsIgnored) {
8173 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8174 /*Map*/ diag::Severity::Ignored, Loc);
8175 }
8176 }
8177 ~DiagsUninitializedSeveretyRAII() {
8178 if (!IsIgnored)
8179 Diags.popMappings(SavedLoc);
8180 }
8181};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008182}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008183
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008184OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8185 SourceLocation StartLoc,
8186 SourceLocation LParenLoc,
8187 SourceLocation EndLoc) {
8188 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008189 SmallVector<Expr *, 8> PrivateCopies;
8190 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008191 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008192 bool IsImplicitClause =
8193 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8194 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8195
Alexey Bataeved09d242014-05-28 05:53:51 +00008196 for (auto &RefExpr : VarList) {
8197 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008198 SourceLocation ELoc;
8199 SourceRange ERange;
8200 Expr *SimpleRefExpr = RefExpr;
8201 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008202 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008203 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008204 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008205 PrivateCopies.push_back(nullptr);
8206 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008207 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008208 ValueDecl *D = Res.first;
8209 if (!D)
8210 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008211
Alexey Bataev60da77e2016-02-29 05:54:20 +00008212 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008213 QualType Type = D->getType();
8214 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008215
8216 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8217 // A variable that appears in a private clause must not have an incomplete
8218 // type or a reference type.
8219 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008220 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008221 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008222 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008223
8224 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8225 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008226 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008227 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008228 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008229
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008230 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008231 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008232 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008233 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008234 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008235 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008236 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8237 // A list item that specifies a given variable may not appear in more
8238 // than one clause on the same directive, except that a variable may be
8239 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008240 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00008241 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008242 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008243 << getOpenMPClauseName(DVar.CKind)
8244 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008245 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008246 continue;
8247 }
8248
8249 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8250 // in a Construct]
8251 // Variables with the predetermined data-sharing attributes may not be
8252 // listed in data-sharing attributes clauses, except for the cases
8253 // listed below. For these exceptions only, listing a predetermined
8254 // variable in a data-sharing attribute clause is allowed and overrides
8255 // the variable's predetermined data-sharing attributes.
8256 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8257 // in a Construct, C/C++, p.2]
8258 // Variables with const-qualified type having no mutable member may be
8259 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008260 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008261 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8262 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008263 << getOpenMPClauseName(DVar.CKind)
8264 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008265 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008266 continue;
8267 }
8268
Alexey Bataevf29276e2014-06-18 04:14:57 +00008269 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008270 // OpenMP [2.9.3.4, Restrictions, p.2]
8271 // A list item that is private within a parallel region must not appear
8272 // in a firstprivate clause on a worksharing construct if any of the
8273 // worksharing regions arising from the worksharing construct ever bind
8274 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008275 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008276 !isOpenMPParallelDirective(CurrDir) &&
8277 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008278 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008279 if (DVar.CKind != OMPC_shared &&
8280 (isOpenMPParallelDirective(DVar.DKind) ||
8281 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008282 Diag(ELoc, diag::err_omp_required_access)
8283 << getOpenMPClauseName(OMPC_firstprivate)
8284 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008285 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008286 continue;
8287 }
8288 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008289 // OpenMP [2.9.3.4, Restrictions, p.3]
8290 // A list item that appears in a reduction clause of a parallel construct
8291 // must not appear in a firstprivate clause on a worksharing or task
8292 // construct if any of the worksharing or task regions arising from the
8293 // worksharing or task construct ever bind to any of the parallel regions
8294 // arising from the parallel construct.
8295 // OpenMP [2.9.3.4, Restrictions, p.4]
8296 // A list item that appears in a reduction clause in worksharing
8297 // construct must not appear in a firstprivate clause in a task construct
8298 // encountered during execution of any of the worksharing regions arising
8299 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008300 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008301 DVar = DSAStack->hasInnermostDSA(
8302 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8303 [](OpenMPDirectiveKind K) -> bool {
8304 return isOpenMPParallelDirective(K) ||
8305 isOpenMPWorksharingDirective(K);
8306 },
8307 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008308 if (DVar.CKind == OMPC_reduction &&
8309 (isOpenMPParallelDirective(DVar.DKind) ||
8310 isOpenMPWorksharingDirective(DVar.DKind))) {
8311 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8312 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008313 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008314 continue;
8315 }
8316 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008317
8318 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8319 // A list item that is private within a teams region must not appear in a
8320 // firstprivate clause on a distribute construct if any of the distribute
8321 // regions arising from the distribute construct ever bind to any of the
8322 // teams regions arising from the teams construct.
8323 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8324 // A list item that appears in a reduction clause of a teams construct
8325 // must not appear in a firstprivate clause on a distribute construct if
8326 // any of the distribute regions arising from the distribute construct
8327 // ever bind to any of the teams regions arising from the teams construct.
8328 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8329 // A list item may appear in a firstprivate or lastprivate clause but not
8330 // both.
8331 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008332 DVar = DSAStack->hasInnermostDSA(
8333 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8334 [](OpenMPDirectiveKind K) -> bool {
8335 return isOpenMPTeamsDirective(K);
8336 },
8337 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008338 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8339 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008340 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008341 continue;
8342 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008343 DVar = DSAStack->hasInnermostDSA(
8344 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8345 [](OpenMPDirectiveKind K) -> bool {
8346 return isOpenMPTeamsDirective(K);
8347 },
8348 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008349 if (DVar.CKind == OMPC_reduction &&
8350 isOpenMPTeamsDirective(DVar.DKind)) {
8351 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008352 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008353 continue;
8354 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008355 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008356 if (DVar.CKind == OMPC_lastprivate) {
8357 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008358 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008359 continue;
8360 }
8361 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008362 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8363 // A list item cannot appear in both a map clause and a data-sharing
8364 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008365 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008366 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008367 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008368 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008369 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008370 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008371 CurrDir == OMPD_target_parallel_for_simd ||
8372 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008373 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008374 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008375 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008376 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8377 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8378 ConflictKind = WhereFoundClauseKind;
8379 return true;
8380 })) {
8381 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008382 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008383 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008384 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8385 ReportOriginalDSA(*this, DSAStack, D, DVar);
8386 continue;
8387 }
8388 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008389 }
8390
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008391 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008392 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008393 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008394 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8395 << getOpenMPClauseName(OMPC_firstprivate) << Type
8396 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8397 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008398 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008399 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008400 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008401 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008402 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008403 continue;
8404 }
8405
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008406 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008407 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8408 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008409 // Generate helper private variable and initialize it with the value of the
8410 // original variable. The address of the original variable is replaced by
8411 // the address of the new private variable in the CodeGen. This new variable
8412 // is not added to IdResolver, so the code in the OpenMP region uses
8413 // original variable for proper diagnostics and variable capturing.
8414 Expr *VDInitRefExpr = nullptr;
8415 // For arrays generate initializer for single element and replace it by the
8416 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008417 if (Type->isArrayType()) {
8418 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008419 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008420 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008421 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008422 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008423 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008424 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008425 InitializedEntity Entity =
8426 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008427 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8428
8429 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8430 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8431 if (Result.isInvalid())
8432 VDPrivate->setInvalidDecl();
8433 else
8434 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008435 // Remove temp variable declaration.
8436 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008437 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008438 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8439 ".firstprivate.temp");
8440 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8441 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008442 AddInitializerToDecl(VDPrivate,
8443 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008444 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008445 }
8446 if (VDPrivate->isInvalidDecl()) {
8447 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008448 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008449 diag::note_omp_task_predetermined_firstprivate_here);
8450 }
8451 continue;
8452 }
8453 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008454 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008455 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8456 RefExpr->getExprLoc());
8457 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008458 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008459 if (TopDVar.CKind == OMPC_lastprivate)
8460 Ref = TopDVar.PrivateCopy;
8461 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008462 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008463 if (!IsOpenMPCapturedDecl(D))
8464 ExprCaptures.push_back(Ref->getDecl());
8465 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008466 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008467 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008468 Vars.push_back((VD || CurContext->isDependentContext())
8469 ? RefExpr->IgnoreParens()
8470 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008471 PrivateCopies.push_back(VDPrivateRefExpr);
8472 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008473 }
8474
Alexey Bataeved09d242014-05-28 05:53:51 +00008475 if (Vars.empty())
8476 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008477
8478 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008479 Vars, PrivateCopies, Inits,
8480 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008481}
8482
Alexander Musman1bb328c2014-06-04 13:06:39 +00008483OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8484 SourceLocation StartLoc,
8485 SourceLocation LParenLoc,
8486 SourceLocation EndLoc) {
8487 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008488 SmallVector<Expr *, 8> SrcExprs;
8489 SmallVector<Expr *, 8> DstExprs;
8490 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008491 SmallVector<Decl *, 4> ExprCaptures;
8492 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008493 for (auto &RefExpr : VarList) {
8494 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008495 SourceLocation ELoc;
8496 SourceRange ERange;
8497 Expr *SimpleRefExpr = RefExpr;
8498 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008499 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008500 // It will be analyzed later.
8501 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008502 SrcExprs.push_back(nullptr);
8503 DstExprs.push_back(nullptr);
8504 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008505 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008506 ValueDecl *D = Res.first;
8507 if (!D)
8508 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008509
Alexey Bataev74caaf22016-02-20 04:09:36 +00008510 QualType Type = D->getType();
8511 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008512
8513 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8514 // A variable that appears in a lastprivate clause must not have an
8515 // incomplete type or a reference type.
8516 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008517 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008518 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008519 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008520
8521 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8522 // in a Construct]
8523 // Variables with the predetermined data-sharing attributes may not be
8524 // listed in data-sharing attributes clauses, except for the cases
8525 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008526 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008527 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8528 DVar.CKind != OMPC_firstprivate &&
8529 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8530 Diag(ELoc, diag::err_omp_wrong_dsa)
8531 << getOpenMPClauseName(DVar.CKind)
8532 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008533 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008534 continue;
8535 }
8536
Alexey Bataevf29276e2014-06-18 04:14:57 +00008537 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8538 // OpenMP [2.14.3.5, Restrictions, p.2]
8539 // A list item that is private within a parallel region, or that appears in
8540 // the reduction clause of a parallel construct, must not appear in a
8541 // lastprivate clause on a worksharing construct if any of the corresponding
8542 // worksharing regions ever binds to any of the corresponding parallel
8543 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008544 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008545 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008546 !isOpenMPParallelDirective(CurrDir) &&
8547 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008548 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008549 if (DVar.CKind != OMPC_shared) {
8550 Diag(ELoc, diag::err_omp_required_access)
8551 << getOpenMPClauseName(OMPC_lastprivate)
8552 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008553 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008554 continue;
8555 }
8556 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008557
8558 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8559 // A list item may appear in a firstprivate or lastprivate clause but not
8560 // both.
8561 if (CurrDir == OMPD_distribute) {
8562 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8563 if (DVar.CKind == OMPC_firstprivate) {
8564 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8565 ReportOriginalDSA(*this, DSAStack, D, DVar);
8566 continue;
8567 }
8568 }
8569
Alexander Musman1bb328c2014-06-04 13:06:39 +00008570 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008571 // A variable of class type (or array thereof) that appears in a
8572 // lastprivate clause requires an accessible, unambiguous default
8573 // constructor for the class type, unless the list item is also specified
8574 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008575 // A variable of class type (or array thereof) that appears in a
8576 // lastprivate clause requires an accessible, unambiguous copy assignment
8577 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008578 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008579 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008580 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008581 D->hasAttrs() ? &D->getAttrs() : nullptr);
8582 auto *PseudoSrcExpr =
8583 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008584 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008585 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008586 D->hasAttrs() ? &D->getAttrs() : nullptr);
8587 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008588 // For arrays generate assignment operation for single element and replace
8589 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008590 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008591 PseudoDstExpr, PseudoSrcExpr);
8592 if (AssignmentOp.isInvalid())
8593 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008594 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008595 /*DiscardedValue=*/true);
8596 if (AssignmentOp.isInvalid())
8597 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008598
Alexey Bataev74caaf22016-02-20 04:09:36 +00008599 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008600 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008601 if (TopDVar.CKind == OMPC_firstprivate)
8602 Ref = TopDVar.PrivateCopy;
8603 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008604 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008605 if (!IsOpenMPCapturedDecl(D))
8606 ExprCaptures.push_back(Ref->getDecl());
8607 }
8608 if (TopDVar.CKind == OMPC_firstprivate ||
8609 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008610 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008611 ExprResult RefRes = DefaultLvalueConversion(Ref);
8612 if (!RefRes.isUsable())
8613 continue;
8614 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008615 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8616 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008617 if (!PostUpdateRes.isUsable())
8618 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008619 ExprPostUpdates.push_back(
8620 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008621 }
8622 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008623 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008624 Vars.push_back((VD || CurContext->isDependentContext())
8625 ? RefExpr->IgnoreParens()
8626 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008627 SrcExprs.push_back(PseudoSrcExpr);
8628 DstExprs.push_back(PseudoDstExpr);
8629 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008630 }
8631
8632 if (Vars.empty())
8633 return nullptr;
8634
8635 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008636 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008637 buildPreInits(Context, ExprCaptures),
8638 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008639}
8640
Alexey Bataev758e55e2013-09-06 18:03:48 +00008641OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8642 SourceLocation StartLoc,
8643 SourceLocation LParenLoc,
8644 SourceLocation EndLoc) {
8645 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008646 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008647 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008648 SourceLocation ELoc;
8649 SourceRange ERange;
8650 Expr *SimpleRefExpr = RefExpr;
8651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008652 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008653 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008654 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008655 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008656 ValueDecl *D = Res.first;
8657 if (!D)
8658 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008659
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008660 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008661 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8662 // in a Construct]
8663 // Variables with the predetermined data-sharing attributes may not be
8664 // listed in data-sharing attributes clauses, except for the cases
8665 // listed below. For these exceptions only, listing a predetermined
8666 // variable in a data-sharing attribute clause is allowed and overrides
8667 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008668 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008669 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8670 DVar.RefExpr) {
8671 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8672 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008673 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008674 continue;
8675 }
8676
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008677 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008678 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008679 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008680 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008681 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8682 ? RefExpr->IgnoreParens()
8683 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008684 }
8685
Alexey Bataeved09d242014-05-28 05:53:51 +00008686 if (Vars.empty())
8687 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008688
8689 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8690}
8691
Alexey Bataevc5e02582014-06-16 07:08:35 +00008692namespace {
8693class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8694 DSAStackTy *Stack;
8695
8696public:
8697 bool VisitDeclRefExpr(DeclRefExpr *E) {
8698 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008699 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008700 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8701 return false;
8702 if (DVar.CKind != OMPC_unknown)
8703 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008704 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8705 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8706 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008707 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008708 return true;
8709 return false;
8710 }
8711 return false;
8712 }
8713 bool VisitStmt(Stmt *S) {
8714 for (auto Child : S->children()) {
8715 if (Child && Visit(Child))
8716 return true;
8717 }
8718 return false;
8719 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008720 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008721};
Alexey Bataev23b69422014-06-18 07:08:49 +00008722} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008723
Alexey Bataev60da77e2016-02-29 05:54:20 +00008724namespace {
8725// Transform MemberExpression for specified FieldDecl of current class to
8726// DeclRefExpr to specified OMPCapturedExprDecl.
8727class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8728 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8729 ValueDecl *Field;
8730 DeclRefExpr *CapturedExpr;
8731
8732public:
8733 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8734 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8735
8736 ExprResult TransformMemberExpr(MemberExpr *E) {
8737 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8738 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008739 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008740 return CapturedExpr;
8741 }
8742 return BaseTransform::TransformMemberExpr(E);
8743 }
8744 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8745};
8746} // namespace
8747
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008748template <typename T>
8749static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8750 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8751 for (auto &Set : Lookups) {
8752 for (auto *D : Set) {
8753 if (auto Res = Gen(cast<ValueDecl>(D)))
8754 return Res;
8755 }
8756 }
8757 return T();
8758}
8759
8760static ExprResult
8761buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8762 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8763 const DeclarationNameInfo &ReductionId, QualType Ty,
8764 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8765 if (ReductionIdScopeSpec.isInvalid())
8766 return ExprError();
8767 SmallVector<UnresolvedSet<8>, 4> Lookups;
8768 if (S) {
8769 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8770 Lookup.suppressDiagnostics();
8771 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8772 auto *D = Lookup.getRepresentativeDecl();
8773 do {
8774 S = S->getParent();
8775 } while (S && !S->isDeclScope(D));
8776 if (S)
8777 S = S->getParent();
8778 Lookups.push_back(UnresolvedSet<8>());
8779 Lookups.back().append(Lookup.begin(), Lookup.end());
8780 Lookup.clear();
8781 }
8782 } else if (auto *ULE =
8783 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8784 Lookups.push_back(UnresolvedSet<8>());
8785 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008786 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008787 if (D == PrevD)
8788 Lookups.push_back(UnresolvedSet<8>());
8789 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8790 Lookups.back().addDecl(DRD);
8791 PrevD = D;
8792 }
8793 }
8794 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8795 Ty->containsUnexpandedParameterPack() ||
8796 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8797 return !D->isInvalidDecl() &&
8798 (D->getType()->isDependentType() ||
8799 D->getType()->isInstantiationDependentType() ||
8800 D->getType()->containsUnexpandedParameterPack());
8801 })) {
8802 UnresolvedSet<8> ResSet;
8803 for (auto &Set : Lookups) {
8804 ResSet.append(Set.begin(), Set.end());
8805 // The last item marks the end of all declarations at the specified scope.
8806 ResSet.addDecl(Set[Set.size() - 1]);
8807 }
8808 return UnresolvedLookupExpr::Create(
8809 SemaRef.Context, /*NamingClass=*/nullptr,
8810 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8811 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8812 }
8813 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8814 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8815 if (!D->isInvalidDecl() &&
8816 SemaRef.Context.hasSameType(D->getType(), Ty))
8817 return D;
8818 return nullptr;
8819 }))
8820 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8821 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8822 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8823 if (!D->isInvalidDecl() &&
8824 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8825 !Ty.isMoreQualifiedThan(D->getType()))
8826 return D;
8827 return nullptr;
8828 })) {
8829 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8830 /*DetectVirtual=*/false);
8831 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8832 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8833 VD->getType().getUnqualifiedType()))) {
8834 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8835 /*DiagID=*/0) !=
8836 Sema::AR_inaccessible) {
8837 SemaRef.BuildBasePathArray(Paths, BasePath);
8838 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8839 }
8840 }
8841 }
8842 }
8843 if (ReductionIdScopeSpec.isSet()) {
8844 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8845 return ExprError();
8846 }
8847 return ExprEmpty();
8848}
8849
Alexey Bataevc5e02582014-06-16 07:08:35 +00008850OMPClause *Sema::ActOnOpenMPReductionClause(
8851 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8852 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008853 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8854 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008855 auto DN = ReductionId.getName();
8856 auto OOK = DN.getCXXOverloadedOperator();
8857 BinaryOperatorKind BOK = BO_Comma;
8858
8859 // OpenMP [2.14.3.6, reduction clause]
8860 // C
8861 // reduction-identifier is either an identifier or one of the following
8862 // operators: +, -, *, &, |, ^, && and ||
8863 // C++
8864 // reduction-identifier is either an id-expression or one of the following
8865 // operators: +, -, *, &, |, ^, && and ||
8866 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8867 switch (OOK) {
8868 case OO_Plus:
8869 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008870 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008871 break;
8872 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008873 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008874 break;
8875 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008876 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008877 break;
8878 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008879 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008880 break;
8881 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008882 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008883 break;
8884 case OO_AmpAmp:
8885 BOK = BO_LAnd;
8886 break;
8887 case OO_PipePipe:
8888 BOK = BO_LOr;
8889 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008890 case OO_New:
8891 case OO_Delete:
8892 case OO_Array_New:
8893 case OO_Array_Delete:
8894 case OO_Slash:
8895 case OO_Percent:
8896 case OO_Tilde:
8897 case OO_Exclaim:
8898 case OO_Equal:
8899 case OO_Less:
8900 case OO_Greater:
8901 case OO_LessEqual:
8902 case OO_GreaterEqual:
8903 case OO_PlusEqual:
8904 case OO_MinusEqual:
8905 case OO_StarEqual:
8906 case OO_SlashEqual:
8907 case OO_PercentEqual:
8908 case OO_CaretEqual:
8909 case OO_AmpEqual:
8910 case OO_PipeEqual:
8911 case OO_LessLess:
8912 case OO_GreaterGreater:
8913 case OO_LessLessEqual:
8914 case OO_GreaterGreaterEqual:
8915 case OO_EqualEqual:
8916 case OO_ExclaimEqual:
8917 case OO_PlusPlus:
8918 case OO_MinusMinus:
8919 case OO_Comma:
8920 case OO_ArrowStar:
8921 case OO_Arrow:
8922 case OO_Call:
8923 case OO_Subscript:
8924 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008925 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008926 case NUM_OVERLOADED_OPERATORS:
8927 llvm_unreachable("Unexpected reduction identifier");
8928 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008929 if (auto II = DN.getAsIdentifierInfo()) {
8930 if (II->isStr("max"))
8931 BOK = BO_GT;
8932 else if (II->isStr("min"))
8933 BOK = BO_LT;
8934 }
8935 break;
8936 }
8937 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008938 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008939 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008940 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008941
8942 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008943 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008944 SmallVector<Expr *, 8> LHSs;
8945 SmallVector<Expr *, 8> RHSs;
8946 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008947 SmallVector<Decl *, 4> ExprCaptures;
8948 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008949 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8950 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008951 for (auto RefExpr : VarList) {
8952 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008953 // OpenMP [2.1, C/C++]
8954 // A list item is a variable or array section, subject to the restrictions
8955 // specified in Section 2.4 on page 42 and in each of the sections
8956 // describing clauses and directives for which a list appears.
8957 // OpenMP [2.14.3.3, Restrictions, p.1]
8958 // A variable that is part of another variable (as an array or
8959 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008960 if (!FirstIter && IR != ER)
8961 ++IR;
8962 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008963 SourceLocation ELoc;
8964 SourceRange ERange;
8965 Expr *SimpleRefExpr = RefExpr;
8966 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8967 /*AllowArraySection=*/true);
8968 if (Res.second) {
8969 // It will be analyzed later.
8970 Vars.push_back(RefExpr);
8971 Privates.push_back(nullptr);
8972 LHSs.push_back(nullptr);
8973 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008974 // Try to find 'declare reduction' corresponding construct before using
8975 // builtin/overloaded operators.
8976 QualType Type = Context.DependentTy;
8977 CXXCastPath BasePath;
8978 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8979 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8980 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8981 if (CurContext->isDependentContext() &&
8982 (DeclareReductionRef.isUnset() ||
8983 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8984 ReductionOps.push_back(DeclareReductionRef.get());
8985 else
8986 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008987 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008988 ValueDecl *D = Res.first;
8989 if (!D)
8990 continue;
8991
Alexey Bataeva1764212015-09-30 09:22:36 +00008992 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008993 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8994 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8995 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008996 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008997 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008998 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8999 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9000 Type = ATy->getElementType();
9001 else
9002 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009003 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009004 } else
9005 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9006 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009007
Alexey Bataevc5e02582014-06-16 07:08:35 +00009008 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9009 // A variable that appears in a private clause must not have an incomplete
9010 // type or a reference type.
9011 if (RequireCompleteType(ELoc, Type,
9012 diag::err_omp_reduction_incomplete_type))
9013 continue;
9014 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009015 // A list item that appears in a reduction clause must not be
9016 // const-qualified.
9017 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009018 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009019 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009020 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009021 bool IsDecl = !VD ||
9022 VD->isThisDeclarationADefinition(Context) ==
9023 VarDecl::DeclarationOnly;
9024 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00009025 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009026 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009027 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009028 continue;
9029 }
9030 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9031 // If a list-item is a reference type then it must bind to the same object
9032 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009033 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009034 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009035 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009036 DSARefChecker Check(DSAStack);
9037 if (Check.Visit(VDDef->getInit())) {
9038 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
9039 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
9040 continue;
9041 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009042 }
9043 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009044
Alexey Bataevc5e02582014-06-16 07:08:35 +00009045 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9046 // in a Construct]
9047 // Variables with the predetermined data-sharing attributes may not be
9048 // listed in data-sharing attributes clauses, except for the cases
9049 // listed below. For these exceptions only, listing a predetermined
9050 // variable in a data-sharing attribute clause is allowed and overrides
9051 // the variable's predetermined data-sharing attributes.
9052 // OpenMP [2.14.3.6, Restrictions, p.3]
9053 // Any number of reduction clauses can be specified on the directive,
9054 // but a list item can appear only once in the reduction clauses for that
9055 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009056 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009057 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009058 if (DVar.CKind == OMPC_reduction) {
9059 Diag(ELoc, diag::err_omp_once_referenced)
9060 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009061 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009062 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009063 } else if (DVar.CKind != OMPC_unknown) {
9064 Diag(ELoc, diag::err_omp_wrong_dsa)
9065 << getOpenMPClauseName(DVar.CKind)
9066 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009067 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009068 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009069 }
9070
9071 // OpenMP [2.14.3.6, Restrictions, p.1]
9072 // A list item that appears in a reduction clause of a worksharing
9073 // construct must be shared in the parallel regions to which any of the
9074 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009075 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9076 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009077 !isOpenMPParallelDirective(CurrDir) &&
9078 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009079 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009080 if (DVar.CKind != OMPC_shared) {
9081 Diag(ELoc, diag::err_omp_required_access)
9082 << getOpenMPClauseName(OMPC_reduction)
9083 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009084 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009085 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009086 }
9087 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009088
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009089 // Try to find 'declare reduction' corresponding construct before using
9090 // builtin/overloaded operators.
9091 CXXCastPath BasePath;
9092 ExprResult DeclareReductionRef = buildDeclareReductionRef(
9093 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
9094 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9095 if (DeclareReductionRef.isInvalid())
9096 continue;
9097 if (CurContext->isDependentContext() &&
9098 (DeclareReductionRef.isUnset() ||
9099 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
9100 Vars.push_back(RefExpr);
9101 Privates.push_back(nullptr);
9102 LHSs.push_back(nullptr);
9103 RHSs.push_back(nullptr);
9104 ReductionOps.push_back(DeclareReductionRef.get());
9105 continue;
9106 }
9107 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9108 // Not allowed reduction identifier is found.
9109 Diag(ReductionId.getLocStart(),
9110 diag::err_omp_unknown_reduction_identifier)
9111 << Type << ReductionIdRange;
9112 continue;
9113 }
9114
9115 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9116 // The type of a list item that appears in a reduction clause must be valid
9117 // for the reduction-identifier. For a max or min reduction in C, the type
9118 // of the list item must be an allowed arithmetic data type: char, int,
9119 // float, double, or _Bool, possibly modified with long, short, signed, or
9120 // unsigned. For a max or min reduction in C++, the type of the list item
9121 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9122 // double, or bool, possibly modified with long, short, signed, or unsigned.
9123 if (DeclareReductionRef.isUnset()) {
9124 if ((BOK == BO_GT || BOK == BO_LT) &&
9125 !(Type->isScalarType() ||
9126 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9127 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
9128 << getLangOpts().CPlusPlus;
9129 if (!ASE && !OASE) {
9130 bool IsDecl = !VD ||
9131 VD->isThisDeclarationADefinition(Context) ==
9132 VarDecl::DeclarationOnly;
9133 Diag(D->getLocation(),
9134 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9135 << D;
9136 }
9137 continue;
9138 }
9139 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
9140 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
9141 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
9142 if (!ASE && !OASE) {
9143 bool IsDecl = !VD ||
9144 VD->isThisDeclarationADefinition(Context) ==
9145 VarDecl::DeclarationOnly;
9146 Diag(D->getLocation(),
9147 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9148 << D;
9149 }
9150 continue;
9151 }
9152 }
9153
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009154 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009155 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009156 D->hasAttrs() ? &D->getAttrs() : nullptr);
9157 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9158 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009159 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009160 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009161 (!ASE &&
9162 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009163 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009164 // Create pseudo array type for private copy. The size for this array will
9165 // be generated during codegen.
9166 // For array subscripts or single variables Private Ty is the same as Type
9167 // (type of the variable or single array element).
9168 PrivateTy = Context.getVariableArrayType(
9169 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9170 Context.getSizeType(), VK_RValue),
9171 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009172 } else if (!ASE && !OASE &&
9173 Context.getAsArrayType(D->getType().getNonReferenceType()))
9174 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009175 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009176 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9177 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009178 // Add initializer for private variable.
9179 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009180 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9181 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9182 if (DeclareReductionRef.isUsable()) {
9183 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9184 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9185 if (DRD->getInitializer()) {
9186 Init = DRDRef;
9187 RHSVD->setInit(DRDRef);
9188 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009189 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009190 } else {
9191 switch (BOK) {
9192 case BO_Add:
9193 case BO_Xor:
9194 case BO_Or:
9195 case BO_LOr:
9196 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9197 if (Type->isScalarType() || Type->isAnyComplexType())
9198 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9199 break;
9200 case BO_Mul:
9201 case BO_LAnd:
9202 if (Type->isScalarType() || Type->isAnyComplexType()) {
9203 // '*' and '&&' reduction ops - initializer is '1'.
9204 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009205 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009206 break;
9207 case BO_And: {
9208 // '&' reduction op - initializer is '~0'.
9209 QualType OrigType = Type;
9210 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9211 Type = ComplexTy->getElementType();
9212 if (Type->isRealFloatingType()) {
9213 llvm::APFloat InitValue =
9214 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9215 /*isIEEE=*/true);
9216 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9217 Type, ELoc);
9218 } else if (Type->isScalarType()) {
9219 auto Size = Context.getTypeSize(Type);
9220 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9221 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9222 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9223 }
9224 if (Init && OrigType->isAnyComplexType()) {
9225 // Init = 0xFFFF + 0xFFFFi;
9226 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9227 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9228 }
9229 Type = OrigType;
9230 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009231 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009232 case BO_LT:
9233 case BO_GT: {
9234 // 'min' reduction op - initializer is 'Largest representable number in
9235 // the reduction list item type'.
9236 // 'max' reduction op - initializer is 'Least representable number in
9237 // the reduction list item type'.
9238 if (Type->isIntegerType() || Type->isPointerType()) {
9239 bool IsSigned = Type->hasSignedIntegerRepresentation();
9240 auto Size = Context.getTypeSize(Type);
9241 QualType IntTy =
9242 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9243 llvm::APInt InitValue =
9244 (BOK != BO_LT)
9245 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9246 : llvm::APInt::getMinValue(Size)
9247 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9248 : llvm::APInt::getMaxValue(Size);
9249 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9250 if (Type->isPointerType()) {
9251 // Cast to pointer type.
9252 auto CastExpr = BuildCStyleCastExpr(
9253 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9254 SourceLocation(), Init);
9255 if (CastExpr.isInvalid())
9256 continue;
9257 Init = CastExpr.get();
9258 }
9259 } else if (Type->isRealFloatingType()) {
9260 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9261 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9262 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9263 Type, ELoc);
9264 }
9265 break;
9266 }
9267 case BO_PtrMemD:
9268 case BO_PtrMemI:
9269 case BO_MulAssign:
9270 case BO_Div:
9271 case BO_Rem:
9272 case BO_Sub:
9273 case BO_Shl:
9274 case BO_Shr:
9275 case BO_LE:
9276 case BO_GE:
9277 case BO_EQ:
9278 case BO_NE:
9279 case BO_AndAssign:
9280 case BO_XorAssign:
9281 case BO_OrAssign:
9282 case BO_Assign:
9283 case BO_AddAssign:
9284 case BO_SubAssign:
9285 case BO_DivAssign:
9286 case BO_RemAssign:
9287 case BO_ShlAssign:
9288 case BO_ShrAssign:
9289 case BO_Comma:
9290 llvm_unreachable("Unexpected reduction operation");
9291 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009292 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009293 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009294 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009295 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009296 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009297 if (RHSVD->isInvalidDecl())
9298 continue;
9299 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009300 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9301 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009302 bool IsDecl =
9303 !VD ||
9304 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9305 Diag(D->getLocation(),
9306 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9307 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009308 continue;
9309 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009310 // Store initializer for single element in private copy. Will be used during
9311 // codegen.
9312 PrivateVD->setInit(RHSVD->getInit());
9313 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009314 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009315 ExprResult ReductionOp;
9316 if (DeclareReductionRef.isUsable()) {
9317 QualType RedTy = DeclareReductionRef.get()->getType();
9318 QualType PtrRedTy = Context.getPointerType(RedTy);
9319 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9320 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9321 if (!BasePath.empty()) {
9322 LHS = DefaultLvalueConversion(LHS.get());
9323 RHS = DefaultLvalueConversion(RHS.get());
9324 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9325 CK_UncheckedDerivedToBase, LHS.get(),
9326 &BasePath, LHS.get()->getValueKind());
9327 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9328 CK_UncheckedDerivedToBase, RHS.get(),
9329 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009330 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009331 FunctionProtoType::ExtProtoInfo EPI;
9332 QualType Params[] = {PtrRedTy, PtrRedTy};
9333 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9334 auto *OVE = new (Context) OpaqueValueExpr(
9335 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9336 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9337 Expr *Args[] = {LHS.get(), RHS.get()};
9338 ReductionOp = new (Context)
9339 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9340 } else {
9341 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9342 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9343 if (ReductionOp.isUsable()) {
9344 if (BOK != BO_LT && BOK != BO_GT) {
9345 ReductionOp =
9346 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9347 BO_Assign, LHSDRE, ReductionOp.get());
9348 } else {
9349 auto *ConditionalOp = new (Context) ConditionalOperator(
9350 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9351 RHSDRE, Type, VK_LValue, OK_Ordinary);
9352 ReductionOp =
9353 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9354 BO_Assign, LHSDRE, ConditionalOp);
9355 }
9356 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9357 }
9358 if (ReductionOp.isInvalid())
9359 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009360 }
9361
Alexey Bataev60da77e2016-02-29 05:54:20 +00009362 DeclRefExpr *Ref = nullptr;
9363 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009364 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009365 if (ASE || OASE) {
9366 TransformExprToCaptures RebuildToCapture(*this, D);
9367 VarsExpr =
9368 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9369 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009370 } else {
9371 VarsExpr = Ref =
9372 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009373 }
9374 if (!IsOpenMPCapturedDecl(D)) {
9375 ExprCaptures.push_back(Ref->getDecl());
9376 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9377 ExprResult RefRes = DefaultLvalueConversion(Ref);
9378 if (!RefRes.isUsable())
9379 continue;
9380 ExprResult PostUpdateRes =
9381 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9382 SimpleRefExpr, RefRes.get());
9383 if (!PostUpdateRes.isUsable())
9384 continue;
9385 ExprPostUpdates.push_back(
9386 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009387 }
9388 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009389 }
9390 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9391 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009392 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009393 LHSs.push_back(LHSDRE);
9394 RHSs.push_back(RHSDRE);
9395 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009396 }
9397
9398 if (Vars.empty())
9399 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009400
Alexey Bataevc5e02582014-06-16 07:08:35 +00009401 return OMPReductionClause::Create(
9402 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009403 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009404 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9405 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009406}
9407
Alexey Bataevecba70f2016-04-12 11:02:11 +00009408bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9409 SourceLocation LinLoc) {
9410 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9411 LinKind == OMPC_LINEAR_unknown) {
9412 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9413 return true;
9414 }
9415 return false;
9416}
9417
9418bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9419 OpenMPLinearClauseKind LinKind,
9420 QualType Type) {
9421 auto *VD = dyn_cast_or_null<VarDecl>(D);
9422 // A variable must not have an incomplete type or a reference type.
9423 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9424 return true;
9425 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9426 !Type->isReferenceType()) {
9427 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9428 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9429 return true;
9430 }
9431 Type = Type.getNonReferenceType();
9432
9433 // A list item must not be const-qualified.
9434 if (Type.isConstant(Context)) {
9435 Diag(ELoc, diag::err_omp_const_variable)
9436 << getOpenMPClauseName(OMPC_linear);
9437 if (D) {
9438 bool IsDecl =
9439 !VD ||
9440 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9441 Diag(D->getLocation(),
9442 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9443 << D;
9444 }
9445 return true;
9446 }
9447
9448 // A list item must be of integral or pointer type.
9449 Type = Type.getUnqualifiedType().getCanonicalType();
9450 const auto *Ty = Type.getTypePtrOrNull();
9451 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9452 !Ty->isPointerType())) {
9453 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9454 if (D) {
9455 bool IsDecl =
9456 !VD ||
9457 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9458 Diag(D->getLocation(),
9459 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9460 << D;
9461 }
9462 return true;
9463 }
9464 return false;
9465}
9466
Alexey Bataev182227b2015-08-20 10:54:39 +00009467OMPClause *Sema::ActOnOpenMPLinearClause(
9468 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9469 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9470 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009471 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009472 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009473 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009474 SmallVector<Decl *, 4> ExprCaptures;
9475 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009476 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009477 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009478 for (auto &RefExpr : VarList) {
9479 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009480 SourceLocation ELoc;
9481 SourceRange ERange;
9482 Expr *SimpleRefExpr = RefExpr;
9483 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9484 /*AllowArraySection=*/false);
9485 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009486 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009487 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009488 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009489 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009490 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009491 ValueDecl *D = Res.first;
9492 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009493 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009494
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009495 QualType Type = D->getType();
9496 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009497
9498 // OpenMP [2.14.3.7, linear clause]
9499 // A list-item cannot appear in more than one linear clause.
9500 // A list-item that appears in a linear clause cannot appear in any
9501 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009502 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009503 if (DVar.RefExpr) {
9504 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9505 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009506 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009507 continue;
9508 }
9509
Alexey Bataevecba70f2016-04-12 11:02:11 +00009510 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009511 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009512 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009513
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009514 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009515 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9516 D->hasAttrs() ? &D->getAttrs() : nullptr);
9517 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009518 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009519 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009520 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009521 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009522 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009523 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9524 if (!IsOpenMPCapturedDecl(D)) {
9525 ExprCaptures.push_back(Ref->getDecl());
9526 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9527 ExprResult RefRes = DefaultLvalueConversion(Ref);
9528 if (!RefRes.isUsable())
9529 continue;
9530 ExprResult PostUpdateRes =
9531 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9532 SimpleRefExpr, RefRes.get());
9533 if (!PostUpdateRes.isUsable())
9534 continue;
9535 ExprPostUpdates.push_back(
9536 IgnoredValueConversions(PostUpdateRes.get()).get());
9537 }
9538 }
9539 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009540 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009541 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009542 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009543 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009544 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009545 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009546 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9547
9548 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009549 Vars.push_back((VD || CurContext->isDependentContext())
9550 ? RefExpr->IgnoreParens()
9551 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009552 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009553 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009554 }
9555
9556 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009557 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009558
9559 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009560 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009561 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9562 !Step->isInstantiationDependent() &&
9563 !Step->containsUnexpandedParameterPack()) {
9564 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009565 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009566 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009567 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009568 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009569
Alexander Musman3276a272015-03-21 10:12:56 +00009570 // Build var to save the step value.
9571 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009572 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009573 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009574 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009575 ExprResult CalcStep =
9576 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009577 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009578
Alexander Musman8dba6642014-04-22 13:09:42 +00009579 // Warn about zero linear step (it would be probably better specified as
9580 // making corresponding variables 'const').
9581 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009582 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9583 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009584 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9585 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009586 if (!IsConstant && CalcStep.isUsable()) {
9587 // Calculate the step beforehand instead of doing this on each iteration.
9588 // (This is not used if the number of iterations may be kfold-ed).
9589 CalcStepExpr = CalcStep.get();
9590 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009591 }
9592
Alexey Bataev182227b2015-08-20 10:54:39 +00009593 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9594 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009595 StepExpr, CalcStepExpr,
9596 buildPreInits(Context, ExprCaptures),
9597 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009598}
9599
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009600static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9601 Expr *NumIterations, Sema &SemaRef,
9602 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009603 // Walk the vars and build update/final expressions for the CodeGen.
9604 SmallVector<Expr *, 8> Updates;
9605 SmallVector<Expr *, 8> Finals;
9606 Expr *Step = Clause.getStep();
9607 Expr *CalcStep = Clause.getCalcStep();
9608 // OpenMP [2.14.3.7, linear clause]
9609 // If linear-step is not specified it is assumed to be 1.
9610 if (Step == nullptr)
9611 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009612 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009613 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009614 }
Alexander Musman3276a272015-03-21 10:12:56 +00009615 bool HasErrors = false;
9616 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009617 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009618 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009619 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009620 SourceLocation ELoc;
9621 SourceRange ERange;
9622 Expr *SimpleRefExpr = RefExpr;
9623 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9624 /*AllowArraySection=*/false);
9625 ValueDecl *D = Res.first;
9626 if (Res.second || !D) {
9627 Updates.push_back(nullptr);
9628 Finals.push_back(nullptr);
9629 HasErrors = true;
9630 continue;
9631 }
9632 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9633 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9634 ->getMemberDecl();
9635 }
9636 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009637 Expr *InitExpr = *CurInit;
9638
9639 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009640 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009641 Expr *CapturedRef;
9642 if (LinKind == OMPC_LINEAR_uval)
9643 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9644 else
9645 CapturedRef =
9646 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9647 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9648 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009649
9650 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009651 ExprResult Update;
9652 if (!Info.first) {
9653 Update =
9654 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9655 InitExpr, IV, Step, /* Subtract */ false);
9656 } else
9657 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009658 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9659 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009660
9661 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009662 ExprResult Final;
9663 if (!Info.first) {
9664 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9665 InitExpr, NumIterations, Step,
9666 /* Subtract */ false);
9667 } else
9668 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009669 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9670 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009671
Alexander Musman3276a272015-03-21 10:12:56 +00009672 if (!Update.isUsable() || !Final.isUsable()) {
9673 Updates.push_back(nullptr);
9674 Finals.push_back(nullptr);
9675 HasErrors = true;
9676 } else {
9677 Updates.push_back(Update.get());
9678 Finals.push_back(Final.get());
9679 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009680 ++CurInit;
9681 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009682 }
9683 Clause.setUpdates(Updates);
9684 Clause.setFinals(Finals);
9685 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009686}
9687
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009688OMPClause *Sema::ActOnOpenMPAlignedClause(
9689 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9690 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9691
9692 SmallVector<Expr *, 8> Vars;
9693 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009694 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9695 SourceLocation ELoc;
9696 SourceRange ERange;
9697 Expr *SimpleRefExpr = RefExpr;
9698 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9699 /*AllowArraySection=*/false);
9700 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009701 // It will be analyzed later.
9702 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009703 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009704 ValueDecl *D = Res.first;
9705 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009706 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009707
Alexey Bataev1efd1662016-03-29 10:59:56 +00009708 QualType QType = D->getType();
9709 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009710
9711 // OpenMP [2.8.1, simd construct, Restrictions]
9712 // The type of list items appearing in the aligned clause must be
9713 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009714 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009715 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009716 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009717 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009718 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009719 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009720 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009721 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009722 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009723 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009724 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009725 continue;
9726 }
9727
9728 // OpenMP [2.8.1, simd construct, Restrictions]
9729 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009730 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009731 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009732 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9733 << getOpenMPClauseName(OMPC_aligned);
9734 continue;
9735 }
9736
Alexey Bataev1efd1662016-03-29 10:59:56 +00009737 DeclRefExpr *Ref = nullptr;
9738 if (!VD && IsOpenMPCapturedDecl(D))
9739 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9740 Vars.push_back(DefaultFunctionArrayConversion(
9741 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9742 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009743 }
9744
9745 // OpenMP [2.8.1, simd construct, Description]
9746 // The parameter of the aligned clause, alignment, must be a constant
9747 // positive integer expression.
9748 // If no optional parameter is specified, implementation-defined default
9749 // alignments for SIMD instructions on the target platforms are assumed.
9750 if (Alignment != nullptr) {
9751 ExprResult AlignResult =
9752 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9753 if (AlignResult.isInvalid())
9754 return nullptr;
9755 Alignment = AlignResult.get();
9756 }
9757 if (Vars.empty())
9758 return nullptr;
9759
9760 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9761 EndLoc, Vars, Alignment);
9762}
9763
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009764OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9765 SourceLocation StartLoc,
9766 SourceLocation LParenLoc,
9767 SourceLocation EndLoc) {
9768 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009769 SmallVector<Expr *, 8> SrcExprs;
9770 SmallVector<Expr *, 8> DstExprs;
9771 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009772 for (auto &RefExpr : VarList) {
9773 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9774 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009775 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009776 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009777 SrcExprs.push_back(nullptr);
9778 DstExprs.push_back(nullptr);
9779 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009780 continue;
9781 }
9782
Alexey Bataeved09d242014-05-28 05:53:51 +00009783 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009784 // OpenMP [2.1, C/C++]
9785 // A list item is a variable name.
9786 // OpenMP [2.14.4.1, Restrictions, p.1]
9787 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009788 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009789 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009790 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9791 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009792 continue;
9793 }
9794
9795 Decl *D = DE->getDecl();
9796 VarDecl *VD = cast<VarDecl>(D);
9797
9798 QualType Type = VD->getType();
9799 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9800 // It will be analyzed later.
9801 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009802 SrcExprs.push_back(nullptr);
9803 DstExprs.push_back(nullptr);
9804 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009805 continue;
9806 }
9807
9808 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9809 // A list item that appears in a copyin clause must be threadprivate.
9810 if (!DSAStack->isThreadPrivate(VD)) {
9811 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009812 << getOpenMPClauseName(OMPC_copyin)
9813 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009814 continue;
9815 }
9816
9817 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9818 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009819 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009820 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009821 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009822 auto *SrcVD =
9823 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9824 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009825 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009826 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9827 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009828 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9829 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009830 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009831 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009832 // For arrays generate assignment operation for single element and replace
9833 // it by the original array element in CodeGen.
9834 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9835 PseudoDstExpr, PseudoSrcExpr);
9836 if (AssignmentOp.isInvalid())
9837 continue;
9838 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9839 /*DiscardedValue=*/true);
9840 if (AssignmentOp.isInvalid())
9841 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009842
9843 DSAStack->addDSA(VD, DE, OMPC_copyin);
9844 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009845 SrcExprs.push_back(PseudoSrcExpr);
9846 DstExprs.push_back(PseudoDstExpr);
9847 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009848 }
9849
Alexey Bataeved09d242014-05-28 05:53:51 +00009850 if (Vars.empty())
9851 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009852
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009853 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9854 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009855}
9856
Alexey Bataevbae9a792014-06-27 10:37:06 +00009857OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9858 SourceLocation StartLoc,
9859 SourceLocation LParenLoc,
9860 SourceLocation EndLoc) {
9861 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009862 SmallVector<Expr *, 8> SrcExprs;
9863 SmallVector<Expr *, 8> DstExprs;
9864 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009865 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009866 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9867 SourceLocation ELoc;
9868 SourceRange ERange;
9869 Expr *SimpleRefExpr = RefExpr;
9870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9871 /*AllowArraySection=*/false);
9872 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009873 // It will be analyzed later.
9874 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009875 SrcExprs.push_back(nullptr);
9876 DstExprs.push_back(nullptr);
9877 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009878 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009879 ValueDecl *D = Res.first;
9880 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009881 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009882
Alexey Bataeve122da12016-03-17 10:50:17 +00009883 QualType Type = D->getType();
9884 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009885
9886 // OpenMP [2.14.4.2, Restrictions, p.2]
9887 // A list item that appears in a copyprivate clause may not appear in a
9888 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009889 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9890 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009891 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9892 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009893 Diag(ELoc, diag::err_omp_wrong_dsa)
9894 << getOpenMPClauseName(DVar.CKind)
9895 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009896 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009897 continue;
9898 }
9899
9900 // OpenMP [2.11.4.2, Restrictions, p.1]
9901 // All list items that appear in a copyprivate clause must be either
9902 // threadprivate or private in the enclosing context.
9903 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009904 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009905 if (DVar.CKind == OMPC_shared) {
9906 Diag(ELoc, diag::err_omp_required_access)
9907 << getOpenMPClauseName(OMPC_copyprivate)
9908 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009909 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009910 continue;
9911 }
9912 }
9913 }
9914
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009915 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009916 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009917 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009918 << getOpenMPClauseName(OMPC_copyprivate) << Type
9919 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009920 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009921 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009922 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009923 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009924 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009925 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009926 continue;
9927 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009928
Alexey Bataevbae9a792014-06-27 10:37:06 +00009929 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9930 // A variable of class type (or array thereof) that appears in a
9931 // copyin clause requires an accessible, unambiguous copy assignment
9932 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009933 Type = Context.getBaseElementType(Type.getNonReferenceType())
9934 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009935 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009936 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9937 D->hasAttrs() ? &D->getAttrs() : nullptr);
9938 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009939 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009940 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9941 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009942 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009943 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009944 PseudoDstExpr, PseudoSrcExpr);
9945 if (AssignmentOp.isInvalid())
9946 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009947 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009948 /*DiscardedValue=*/true);
9949 if (AssignmentOp.isInvalid())
9950 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009951
9952 // No need to mark vars as copyprivate, they are already threadprivate or
9953 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009954 assert(VD || IsOpenMPCapturedDecl(D));
9955 Vars.push_back(
9956 VD ? RefExpr->IgnoreParens()
9957 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009958 SrcExprs.push_back(PseudoSrcExpr);
9959 DstExprs.push_back(PseudoDstExpr);
9960 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009961 }
9962
9963 if (Vars.empty())
9964 return nullptr;
9965
Alexey Bataeva63048e2015-03-23 06:18:07 +00009966 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9967 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009968}
9969
Alexey Bataev6125da92014-07-21 11:26:11 +00009970OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9971 SourceLocation StartLoc,
9972 SourceLocation LParenLoc,
9973 SourceLocation EndLoc) {
9974 if (VarList.empty())
9975 return nullptr;
9976
9977 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9978}
Alexey Bataevdea47612014-07-23 07:46:59 +00009979
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009980OMPClause *
9981Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9982 SourceLocation DepLoc, SourceLocation ColonLoc,
9983 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9984 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009985 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009986 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009987 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009988 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009989 return nullptr;
9990 }
9991 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009992 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9993 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009994 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009995 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009996 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9997 /*Last=*/OMPC_DEPEND_unknown, Except)
9998 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009999 return nullptr;
10000 }
10001 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010002 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010003 llvm::APSInt DepCounter(/*BitWidth=*/32);
10004 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10005 if (DepKind == OMPC_DEPEND_sink) {
10006 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10007 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10008 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010009 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010010 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010011 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10012 DSAStack->getParentOrderedRegionParam()) {
10013 for (auto &RefExpr : VarList) {
10014 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010015 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010016 // It will be analyzed later.
10017 Vars.push_back(RefExpr);
10018 continue;
10019 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010020
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010021 SourceLocation ELoc = RefExpr->getExprLoc();
10022 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10023 if (DepKind == OMPC_DEPEND_sink) {
10024 if (DepCounter >= TotalDepCount) {
10025 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10026 continue;
10027 }
10028 ++DepCounter;
10029 // OpenMP [2.13.9, Summary]
10030 // depend(dependence-type : vec), where dependence-type is:
10031 // 'sink' and where vec is the iteration vector, which has the form:
10032 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10033 // where n is the value specified by the ordered clause in the loop
10034 // directive, xi denotes the loop iteration variable of the i-th nested
10035 // loop associated with the loop directive, and di is a constant
10036 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010037 if (CurContext->isDependentContext()) {
10038 // It will be analyzed later.
10039 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010040 continue;
10041 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010042 SimpleExpr = SimpleExpr->IgnoreImplicit();
10043 OverloadedOperatorKind OOK = OO_None;
10044 SourceLocation OOLoc;
10045 Expr *LHS = SimpleExpr;
10046 Expr *RHS = nullptr;
10047 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10048 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10049 OOLoc = BO->getOperatorLoc();
10050 LHS = BO->getLHS()->IgnoreParenImpCasts();
10051 RHS = BO->getRHS()->IgnoreParenImpCasts();
10052 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10053 OOK = OCE->getOperator();
10054 OOLoc = OCE->getOperatorLoc();
10055 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10056 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10057 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10058 OOK = MCE->getMethodDecl()
10059 ->getNameInfo()
10060 .getName()
10061 .getCXXOverloadedOperator();
10062 OOLoc = MCE->getCallee()->getExprLoc();
10063 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10064 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10065 }
10066 SourceLocation ELoc;
10067 SourceRange ERange;
10068 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10069 /*AllowArraySection=*/false);
10070 if (Res.second) {
10071 // It will be analyzed later.
10072 Vars.push_back(RefExpr);
10073 }
10074 ValueDecl *D = Res.first;
10075 if (!D)
10076 continue;
10077
10078 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10079 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10080 continue;
10081 }
10082 if (RHS) {
10083 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10084 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10085 if (RHSRes.isInvalid())
10086 continue;
10087 }
10088 if (!CurContext->isDependentContext() &&
10089 DSAStack->getParentOrderedRegionParam() &&
10090 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10091 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10092 << DSAStack->getParentLoopControlVariable(
10093 DepCounter.getZExtValue());
10094 continue;
10095 }
10096 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010097 } else {
10098 // OpenMP [2.11.1.1, Restrictions, p.3]
10099 // A variable that is part of another variable (such as a field of a
10100 // structure) but is not an array element or an array section cannot
10101 // appear in a depend clause.
10102 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10103 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10104 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10105 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10106 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010107 (ASE &&
10108 !ASE->getBase()
10109 ->getType()
10110 .getNonReferenceType()
10111 ->isPointerType() &&
10112 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010113 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10114 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010115 continue;
10116 }
10117 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010118 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10119 }
10120
10121 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10122 TotalDepCount > VarList.size() &&
10123 DSAStack->getParentOrderedRegionParam()) {
10124 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10125 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10126 }
10127 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10128 Vars.empty())
10129 return nullptr;
10130 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010131 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10132 DepKind, DepLoc, ColonLoc, Vars);
10133 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10134 DSAStack->addDoacrossDependClause(C, OpsOffs);
10135 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010136}
Michael Wonge710d542015-08-07 16:16:36 +000010137
10138OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10139 SourceLocation LParenLoc,
10140 SourceLocation EndLoc) {
10141 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010142
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010143 // OpenMP [2.9.1, Restrictions]
10144 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010145 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10146 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010147 return nullptr;
10148
Michael Wonge710d542015-08-07 16:16:36 +000010149 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10150}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010151
10152static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10153 DSAStackTy *Stack, CXXRecordDecl *RD) {
10154 if (!RD || RD->isInvalidDecl())
10155 return true;
10156
10157 auto QTy = SemaRef.Context.getRecordType(RD);
10158 if (RD->isDynamicClass()) {
10159 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10160 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10161 return false;
10162 }
10163 auto *DC = RD;
10164 bool IsCorrect = true;
10165 for (auto *I : DC->decls()) {
10166 if (I) {
10167 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10168 if (MD->isStatic()) {
10169 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10170 SemaRef.Diag(MD->getLocation(),
10171 diag::note_omp_static_member_in_target);
10172 IsCorrect = false;
10173 }
10174 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10175 if (VD->isStaticDataMember()) {
10176 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10177 SemaRef.Diag(VD->getLocation(),
10178 diag::note_omp_static_member_in_target);
10179 IsCorrect = false;
10180 }
10181 }
10182 }
10183 }
10184
10185 for (auto &I : RD->bases()) {
10186 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10187 I.getType()->getAsCXXRecordDecl()))
10188 IsCorrect = false;
10189 }
10190 return IsCorrect;
10191}
10192
10193static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10194 DSAStackTy *Stack, QualType QTy) {
10195 NamedDecl *ND;
10196 if (QTy->isIncompleteType(&ND)) {
10197 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10198 return false;
10199 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010200 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010201 return false;
10202 }
10203 return true;
10204}
10205
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010206/// \brief Return true if it can be proven that the provided array expression
10207/// (array section or array subscript) does NOT specify the whole size of the
10208/// array whose base type is \a BaseQTy.
10209static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10210 const Expr *E,
10211 QualType BaseQTy) {
10212 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10213
10214 // If this is an array subscript, it refers to the whole size if the size of
10215 // the dimension is constant and equals 1. Also, an array section assumes the
10216 // format of an array subscript if no colon is used.
10217 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10218 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10219 return ATy->getSize().getSExtValue() != 1;
10220 // Size can't be evaluated statically.
10221 return false;
10222 }
10223
10224 assert(OASE && "Expecting array section if not an array subscript.");
10225 auto *LowerBound = OASE->getLowerBound();
10226 auto *Length = OASE->getLength();
10227
10228 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010229 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010230 if (LowerBound) {
10231 llvm::APSInt ConstLowerBound;
10232 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10233 return false; // Can't get the integer value as a constant.
10234 if (ConstLowerBound.getSExtValue())
10235 return true;
10236 }
10237
10238 // If we don't have a length we covering the whole dimension.
10239 if (!Length)
10240 return false;
10241
10242 // If the base is a pointer, we don't have a way to get the size of the
10243 // pointee.
10244 if (BaseQTy->isPointerType())
10245 return false;
10246
10247 // We can only check if the length is the same as the size of the dimension
10248 // if we have a constant array.
10249 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10250 if (!CATy)
10251 return false;
10252
10253 llvm::APSInt ConstLength;
10254 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10255 return false; // Can't get the integer value as a constant.
10256
10257 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10258}
10259
10260// Return true if it can be proven that the provided array expression (array
10261// section or array subscript) does NOT specify a single element of the array
10262// whose base type is \a BaseQTy.
10263static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010264 const Expr *E,
10265 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010266 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10267
10268 // An array subscript always refer to a single element. Also, an array section
10269 // assumes the format of an array subscript if no colon is used.
10270 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10271 return false;
10272
10273 assert(OASE && "Expecting array section if not an array subscript.");
10274 auto *Length = OASE->getLength();
10275
10276 // If we don't have a length we have to check if the array has unitary size
10277 // for this dimension. Also, we should always expect a length if the base type
10278 // is pointer.
10279 if (!Length) {
10280 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10281 return ATy->getSize().getSExtValue() != 1;
10282 // We cannot assume anything.
10283 return false;
10284 }
10285
10286 // Check if the length evaluates to 1.
10287 llvm::APSInt ConstLength;
10288 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10289 return false; // Can't get the integer value as a constant.
10290
10291 return ConstLength.getSExtValue() != 1;
10292}
10293
Samuel Antao661c0902016-05-26 17:39:58 +000010294// Return the expression of the base of the mappable expression or null if it
10295// cannot be determined and do all the necessary checks to see if the expression
10296// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010297// components of the expression.
10298static Expr *CheckMapClauseExpressionBase(
10299 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010300 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10301 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010302 SourceLocation ELoc = E->getExprLoc();
10303 SourceRange ERange = E->getSourceRange();
10304
10305 // The base of elements of list in a map clause have to be either:
10306 // - a reference to variable or field.
10307 // - a member expression.
10308 // - an array expression.
10309 //
10310 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10311 // reference to 'r'.
10312 //
10313 // If we have:
10314 //
10315 // struct SS {
10316 // Bla S;
10317 // foo() {
10318 // #pragma omp target map (S.Arr[:12]);
10319 // }
10320 // }
10321 //
10322 // We want to retrieve the member expression 'this->S';
10323
10324 Expr *RelevantExpr = nullptr;
10325
Samuel Antao5de996e2016-01-22 20:21:36 +000010326 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10327 // If a list item is an array section, it must specify contiguous storage.
10328 //
10329 // For this restriction it is sufficient that we make sure only references
10330 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010331 // exist except in the rightmost expression (unless they cover the whole
10332 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010333 //
10334 // r.ArrS[3:5].Arr[6:7]
10335 //
10336 // r.ArrS[3:5].x
10337 //
10338 // but these would be valid:
10339 // r.ArrS[3].Arr[6:7]
10340 //
10341 // r.ArrS[3].x
10342
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010343 bool AllowUnitySizeArraySection = true;
10344 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010345
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010346 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010347 E = E->IgnoreParenImpCasts();
10348
10349 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10350 if (!isa<VarDecl>(CurE->getDecl()))
10351 break;
10352
10353 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010354
10355 // If we got a reference to a declaration, we should not expect any array
10356 // section before that.
10357 AllowUnitySizeArraySection = false;
10358 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010359
10360 // Record the component.
10361 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10362 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010363 continue;
10364 }
10365
10366 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10367 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10368
10369 if (isa<CXXThisExpr>(BaseE))
10370 // We found a base expression: this->Val.
10371 RelevantExpr = CurE;
10372 else
10373 E = BaseE;
10374
10375 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10376 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10377 << CurE->getSourceRange();
10378 break;
10379 }
10380
10381 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10382
10383 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10384 // A bit-field cannot appear in a map clause.
10385 //
10386 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010387 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10388 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010389 break;
10390 }
10391
10392 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10393 // If the type of a list item is a reference to a type T then the type
10394 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010395 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010396
10397 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10398 // A list item cannot be a variable that is a member of a structure with
10399 // a union type.
10400 //
10401 if (auto *RT = CurType->getAs<RecordType>())
10402 if (RT->isUnionType()) {
10403 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10404 << CurE->getSourceRange();
10405 break;
10406 }
10407
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010408 // If we got a member expression, we should not expect any array section
10409 // before that:
10410 //
10411 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10412 // If a list item is an element of a structure, only the rightmost symbol
10413 // of the variable reference can be an array section.
10414 //
10415 AllowUnitySizeArraySection = false;
10416 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010417
10418 // Record the component.
10419 CurComponents.push_back(
10420 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010421 continue;
10422 }
10423
10424 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10425 E = CurE->getBase()->IgnoreParenImpCasts();
10426
10427 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10428 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10429 << 0 << CurE->getSourceRange();
10430 break;
10431 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010432
10433 // If we got an array subscript that express the whole dimension we
10434 // can have any array expressions before. If it only expressing part of
10435 // the dimension, we can only have unitary-size array expressions.
10436 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10437 E->getType()))
10438 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010439
10440 // Record the component - we don't have any declaration associated.
10441 CurComponents.push_back(
10442 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010443 continue;
10444 }
10445
10446 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010447 E = CurE->getBase()->IgnoreParenImpCasts();
10448
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010449 auto CurType =
10450 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10451
Samuel Antao5de996e2016-01-22 20:21:36 +000010452 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10453 // If the type of a list item is a reference to a type T then the type
10454 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010455 if (CurType->isReferenceType())
10456 CurType = CurType->getPointeeType();
10457
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010458 bool IsPointer = CurType->isAnyPointerType();
10459
10460 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010461 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10462 << 0 << CurE->getSourceRange();
10463 break;
10464 }
10465
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010466 bool NotWhole =
10467 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10468 bool NotUnity =
10469 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10470
Samuel Antaodab51bb2016-07-18 23:22:11 +000010471 if (AllowWholeSizeArraySection) {
10472 // Any array section is currently allowed. Allowing a whole size array
10473 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010474 //
10475 // If this array section refers to the whole dimension we can still
10476 // accept other array sections before this one, except if the base is a
10477 // pointer. Otherwise, only unitary sections are accepted.
10478 if (NotWhole || IsPointer)
10479 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010480 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010481 // A unity or whole array section is not allowed and that is not
10482 // compatible with the properties of the current array section.
10483 SemaRef.Diag(
10484 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10485 << CurE->getSourceRange();
10486 break;
10487 }
Samuel Antao90927002016-04-26 14:54:23 +000010488
10489 // Record the component - we don't have any declaration associated.
10490 CurComponents.push_back(
10491 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010492 continue;
10493 }
10494
10495 // If nothing else worked, this is not a valid map clause expression.
10496 SemaRef.Diag(ELoc,
10497 diag::err_omp_expected_named_var_member_or_array_expression)
10498 << ERange;
10499 break;
10500 }
10501
10502 return RelevantExpr;
10503}
10504
10505// Return true if expression E associated with value VD has conflicts with other
10506// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010507static bool CheckMapConflicts(
10508 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10509 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010510 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10511 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010512 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010513 SourceLocation ELoc = E->getExprLoc();
10514 SourceRange ERange = E->getSourceRange();
10515
10516 // In order to easily check the conflicts we need to match each component of
10517 // the expression under test with the components of the expressions that are
10518 // already in the stack.
10519
Samuel Antao5de996e2016-01-22 20:21:36 +000010520 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010521 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010522 "Map clause expression with unexpected base!");
10523
10524 // Variables to help detecting enclosing problems in data environment nests.
10525 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010526 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010527
Samuel Antao90927002016-04-26 14:54:23 +000010528 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10529 VD, CurrentRegionOnly,
10530 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010531 StackComponents,
10532 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010533
Samuel Antao5de996e2016-01-22 20:21:36 +000010534 assert(!StackComponents.empty() &&
10535 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010536 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010537 "Map clause expression with unexpected base!");
10538
Samuel Antao90927002016-04-26 14:54:23 +000010539 // The whole expression in the stack.
10540 auto *RE = StackComponents.front().getAssociatedExpression();
10541
Samuel Antao5de996e2016-01-22 20:21:36 +000010542 // Expressions must start from the same base. Here we detect at which
10543 // point both expressions diverge from each other and see if we can
10544 // detect if the memory referred to both expressions is contiguous and
10545 // do not overlap.
10546 auto CI = CurComponents.rbegin();
10547 auto CE = CurComponents.rend();
10548 auto SI = StackComponents.rbegin();
10549 auto SE = StackComponents.rend();
10550 for (; CI != CE && SI != SE; ++CI, ++SI) {
10551
10552 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10553 // At most one list item can be an array item derived from a given
10554 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010555 if (CurrentRegionOnly &&
10556 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10557 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10558 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10559 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10560 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010561 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010562 << CI->getAssociatedExpression()->getSourceRange();
10563 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10564 diag::note_used_here)
10565 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010566 return true;
10567 }
10568
10569 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010570 if (CI->getAssociatedExpression()->getStmtClass() !=
10571 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010572 break;
10573
10574 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010575 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010576 break;
10577 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010578 // Check if the extra components of the expressions in the enclosing
10579 // data environment are redundant for the current base declaration.
10580 // If they are, the maps completely overlap, which is legal.
10581 for (; SI != SE; ++SI) {
10582 QualType Type;
10583 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010584 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010585 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010586 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10587 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010588 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10589 Type =
10590 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10591 }
10592 if (Type.isNull() || Type->isAnyPointerType() ||
10593 CheckArrayExpressionDoesNotReferToWholeSize(
10594 SemaRef, SI->getAssociatedExpression(), Type))
10595 break;
10596 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010597
10598 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10599 // List items of map clauses in the same construct must not share
10600 // original storage.
10601 //
10602 // If the expressions are exactly the same or one is a subset of the
10603 // other, it means they are sharing storage.
10604 if (CI == CE && SI == SE) {
10605 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010606 if (CKind == OMPC_map)
10607 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10608 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010609 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010610 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10611 << ERange;
10612 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010613 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10614 << RE->getSourceRange();
10615 return true;
10616 } else {
10617 // If we find the same expression in the enclosing data environment,
10618 // that is legal.
10619 IsEnclosedByDataEnvironmentExpr = true;
10620 return false;
10621 }
10622 }
10623
Samuel Antao90927002016-04-26 14:54:23 +000010624 QualType DerivedType =
10625 std::prev(CI)->getAssociatedDeclaration()->getType();
10626 SourceLocation DerivedLoc =
10627 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010628
10629 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10630 // If the type of a list item is a reference to a type T then the type
10631 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010632 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010633
10634 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10635 // A variable for which the type is pointer and an array section
10636 // derived from that variable must not appear as list items of map
10637 // clauses of the same construct.
10638 //
10639 // Also, cover one of the cases in:
10640 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10641 // If any part of the original storage of a list item has corresponding
10642 // storage in the device data environment, all of the original storage
10643 // must have corresponding storage in the device data environment.
10644 //
10645 if (DerivedType->isAnyPointerType()) {
10646 if (CI == CE || SI == SE) {
10647 SemaRef.Diag(
10648 DerivedLoc,
10649 diag::err_omp_pointer_mapped_along_with_derived_section)
10650 << DerivedLoc;
10651 } else {
10652 assert(CI != CE && SI != SE);
10653 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10654 << DerivedLoc;
10655 }
10656 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10657 << RE->getSourceRange();
10658 return true;
10659 }
10660
10661 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10662 // List items of map clauses in the same construct must not share
10663 // original storage.
10664 //
10665 // An expression is a subset of the other.
10666 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010667 if (CKind == OMPC_map)
10668 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10669 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010670 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010671 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10672 << ERange;
10673 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010674 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10675 << RE->getSourceRange();
10676 return true;
10677 }
10678
10679 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010680 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010681 if (!CurrentRegionOnly && SI != SE)
10682 EnclosingExpr = RE;
10683
10684 // The current expression is a subset of the expression in the data
10685 // environment.
10686 IsEnclosedByDataEnvironmentExpr |=
10687 (!CurrentRegionOnly && CI != CE && SI == SE);
10688
10689 return false;
10690 });
10691
10692 if (CurrentRegionOnly)
10693 return FoundError;
10694
10695 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10696 // If any part of the original storage of a list item has corresponding
10697 // storage in the device data environment, all of the original storage must
10698 // have corresponding storage in the device data environment.
10699 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10700 // If a list item is an element of a structure, and a different element of
10701 // the structure has a corresponding list item in the device data environment
10702 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010703 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010704 // data environment prior to the task encountering the construct.
10705 //
10706 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10707 SemaRef.Diag(ELoc,
10708 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10709 << ERange;
10710 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10711 << EnclosingExpr->getSourceRange();
10712 return true;
10713 }
10714
10715 return FoundError;
10716}
10717
Samuel Antao661c0902016-05-26 17:39:58 +000010718namespace {
10719// Utility struct that gathers all the related lists associated with a mappable
10720// expression.
10721struct MappableVarListInfo final {
10722 // The list of expressions.
10723 ArrayRef<Expr *> VarList;
10724 // The list of processed expressions.
10725 SmallVector<Expr *, 16> ProcessedVarList;
10726 // The mappble components for each expression.
10727 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10728 // The base declaration of the variable.
10729 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10730
10731 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10732 // We have a list of components and base declarations for each entry in the
10733 // variable list.
10734 VarComponents.reserve(VarList.size());
10735 VarBaseDeclarations.reserve(VarList.size());
10736 }
10737};
10738}
10739
10740// Check the validity of the provided variable list for the provided clause kind
10741// \a CKind. In the check process the valid expressions, and mappable expression
10742// components and variables are extracted and used to fill \a Vars,
10743// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10744// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10745static void
10746checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10747 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10748 SourceLocation StartLoc,
10749 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10750 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010751 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10752 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010753 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010754
Samuel Antao90927002016-04-26 14:54:23 +000010755 // Keep track of the mappable components and base declarations in this clause.
10756 // Each entry in the list is going to have a list of components associated. We
10757 // record each set of the components so that we can build the clause later on.
10758 // In the end we should have the same amount of declarations and component
10759 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010760
Samuel Antao661c0902016-05-26 17:39:58 +000010761 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010762 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010763 SourceLocation ELoc = RE->getExprLoc();
10764
Kelvin Li0bff7af2015-11-23 05:32:03 +000010765 auto *VE = RE->IgnoreParenLValueCasts();
10766
10767 if (VE->isValueDependent() || VE->isTypeDependent() ||
10768 VE->isInstantiationDependent() ||
10769 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010770 // We can only analyze this information once the missing information is
10771 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010772 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010773 continue;
10774 }
10775
10776 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010777
Samuel Antao5de996e2016-01-22 20:21:36 +000010778 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010779 SemaRef.Diag(ELoc,
10780 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010781 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010782 continue;
10783 }
10784
Samuel Antao90927002016-04-26 14:54:23 +000010785 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10786 ValueDecl *CurDeclaration = nullptr;
10787
10788 // Obtain the array or member expression bases if required. Also, fill the
10789 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010790 auto *BE =
10791 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010792 if (!BE)
10793 continue;
10794
Samuel Antao90927002016-04-26 14:54:23 +000010795 assert(!CurComponents.empty() &&
10796 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010797
Samuel Antao90927002016-04-26 14:54:23 +000010798 // For the following checks, we rely on the base declaration which is
10799 // expected to be associated with the last component. The declaration is
10800 // expected to be a variable or a field (if 'this' is being mapped).
10801 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10802 assert(CurDeclaration && "Null decl on map clause.");
10803 assert(
10804 CurDeclaration->isCanonicalDecl() &&
10805 "Expecting components to have associated only canonical declarations.");
10806
10807 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10808 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010809
10810 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010811 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010812
10813 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010814 // threadprivate variables cannot appear in a map clause.
10815 // OpenMP 4.5 [2.10.5, target update Construct]
10816 // threadprivate variables cannot appear in a from clause.
10817 if (VD && DSAS->isThreadPrivate(VD)) {
10818 auto DVar = DSAS->getTopDSA(VD, false);
10819 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10820 << getOpenMPClauseName(CKind);
10821 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010822 continue;
10823 }
10824
Samuel Antao5de996e2016-01-22 20:21:36 +000010825 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10826 // A list item cannot appear in both a map clause and a data-sharing
10827 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010828
Samuel Antao5de996e2016-01-22 20:21:36 +000010829 // Check conflicts with other map clause expressions. We check the conflicts
10830 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010831 // environment, because the restrictions are different. We only have to
10832 // check conflicts across regions for the map clauses.
10833 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10834 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010835 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010836 if (CKind == OMPC_map &&
10837 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10838 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010839 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010840
Samuel Antao661c0902016-05-26 17:39:58 +000010841 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010842 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10843 // If the type of a list item is a reference to a type T then the type will
10844 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010845 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010846
Samuel Antao661c0902016-05-26 17:39:58 +000010847 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10848 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010849 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010850 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010851 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10852 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010853 continue;
10854
Samuel Antao661c0902016-05-26 17:39:58 +000010855 if (CKind == OMPC_map) {
10856 // target enter data
10857 // OpenMP [2.10.2, Restrictions, p. 99]
10858 // A map-type must be specified in all map clauses and must be either
10859 // to or alloc.
10860 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10861 if (DKind == OMPD_target_enter_data &&
10862 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10863 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10864 << (IsMapTypeImplicit ? 1 : 0)
10865 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10866 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010867 continue;
10868 }
Samuel Antao661c0902016-05-26 17:39:58 +000010869
10870 // target exit_data
10871 // OpenMP [2.10.3, Restrictions, p. 102]
10872 // A map-type must be specified in all map clauses and must be either
10873 // from, release, or delete.
10874 if (DKind == OMPD_target_exit_data &&
10875 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10876 MapType == OMPC_MAP_delete)) {
10877 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10878 << (IsMapTypeImplicit ? 1 : 0)
10879 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10880 << getOpenMPDirectiveName(DKind);
10881 continue;
10882 }
10883
10884 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10885 // A list item cannot appear in both a map clause and a data-sharing
10886 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010887 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010888 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010889 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010890 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10891 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010892 auto DVar = DSAS->getTopDSA(VD, false);
10893 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010894 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010895 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010896 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010897 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10898 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10899 continue;
10900 }
10901 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010902 }
10903
Samuel Antao90927002016-04-26 14:54:23 +000010904 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010905 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010906
10907 // Store the components in the stack so that they can be used to check
10908 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010909 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10910 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010911
10912 // Save the components and declaration to create the clause. For purposes of
10913 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010914 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010915 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10916 MVLI.VarComponents.back().append(CurComponents.begin(),
10917 CurComponents.end());
10918 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10919 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010920 }
Samuel Antao661c0902016-05-26 17:39:58 +000010921}
10922
10923OMPClause *
10924Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10925 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10926 SourceLocation MapLoc, SourceLocation ColonLoc,
10927 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10928 SourceLocation LParenLoc, SourceLocation EndLoc) {
10929 MappableVarListInfo MVLI(VarList);
10930 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10931 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010932
Samuel Antao5de996e2016-01-22 20:21:36 +000010933 // We need to produce a map clause even if we don't have variables so that
10934 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010935 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10936 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10937 MVLI.VarComponents, MapTypeModifier, MapType,
10938 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010939}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010940
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010941QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10942 TypeResult ParsedType) {
10943 assert(ParsedType.isUsable());
10944
10945 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10946 if (ReductionType.isNull())
10947 return QualType();
10948
10949 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10950 // A type name in a declare reduction directive cannot be a function type, an
10951 // array type, a reference type, or a type qualified with const, volatile or
10952 // restrict.
10953 if (ReductionType.hasQualifiers()) {
10954 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10955 return QualType();
10956 }
10957
10958 if (ReductionType->isFunctionType()) {
10959 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10960 return QualType();
10961 }
10962 if (ReductionType->isReferenceType()) {
10963 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10964 return QualType();
10965 }
10966 if (ReductionType->isArrayType()) {
10967 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10968 return QualType();
10969 }
10970 return ReductionType;
10971}
10972
10973Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10974 Scope *S, DeclContext *DC, DeclarationName Name,
10975 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10976 AccessSpecifier AS, Decl *PrevDeclInScope) {
10977 SmallVector<Decl *, 8> Decls;
10978 Decls.reserve(ReductionTypes.size());
10979
10980 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10981 ForRedeclaration);
10982 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10983 // A reduction-identifier may not be re-declared in the current scope for the
10984 // same type or for a type that is compatible according to the base language
10985 // rules.
10986 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10987 OMPDeclareReductionDecl *PrevDRD = nullptr;
10988 bool InCompoundScope = true;
10989 if (S != nullptr) {
10990 // Find previous declaration with the same name not referenced in other
10991 // declarations.
10992 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10993 InCompoundScope =
10994 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10995 LookupName(Lookup, S);
10996 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10997 /*AllowInlineNamespace=*/false);
10998 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10999 auto Filter = Lookup.makeFilter();
11000 while (Filter.hasNext()) {
11001 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11002 if (InCompoundScope) {
11003 auto I = UsedAsPrevious.find(PrevDecl);
11004 if (I == UsedAsPrevious.end())
11005 UsedAsPrevious[PrevDecl] = false;
11006 if (auto *D = PrevDecl->getPrevDeclInScope())
11007 UsedAsPrevious[D] = true;
11008 }
11009 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11010 PrevDecl->getLocation();
11011 }
11012 Filter.done();
11013 if (InCompoundScope) {
11014 for (auto &PrevData : UsedAsPrevious) {
11015 if (!PrevData.second) {
11016 PrevDRD = PrevData.first;
11017 break;
11018 }
11019 }
11020 }
11021 } else if (PrevDeclInScope != nullptr) {
11022 auto *PrevDRDInScope = PrevDRD =
11023 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11024 do {
11025 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11026 PrevDRDInScope->getLocation();
11027 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11028 } while (PrevDRDInScope != nullptr);
11029 }
11030 for (auto &TyData : ReductionTypes) {
11031 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11032 bool Invalid = false;
11033 if (I != PreviousRedeclTypes.end()) {
11034 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11035 << TyData.first;
11036 Diag(I->second, diag::note_previous_definition);
11037 Invalid = true;
11038 }
11039 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11040 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11041 Name, TyData.first, PrevDRD);
11042 DC->addDecl(DRD);
11043 DRD->setAccess(AS);
11044 Decls.push_back(DRD);
11045 if (Invalid)
11046 DRD->setInvalidDecl();
11047 else
11048 PrevDRD = DRD;
11049 }
11050
11051 return DeclGroupPtrTy::make(
11052 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11053}
11054
11055void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11056 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11057
11058 // Enter new function scope.
11059 PushFunctionScope();
11060 getCurFunction()->setHasBranchProtectedScope();
11061 getCurFunction()->setHasOMPDeclareReductionCombiner();
11062
11063 if (S != nullptr)
11064 PushDeclContext(S, DRD);
11065 else
11066 CurContext = DRD;
11067
Faisal Valid143a0c2017-04-01 21:30:49 +000011068 PushExpressionEvaluationContext(
11069 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011070
11071 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011072 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11073 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11074 // uses semantics of argument handles by value, but it should be passed by
11075 // reference. C lang does not support references, so pass all parameters as
11076 // pointers.
11077 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011078 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011079 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011080 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11081 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11082 // uses semantics of argument handles by value, but it should be passed by
11083 // reference. C lang does not support references, so pass all parameters as
11084 // pointers.
11085 // Create 'T omp_out;' variable.
11086 auto *OmpOutParm =
11087 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11088 if (S != nullptr) {
11089 PushOnScopeChains(OmpInParm, S);
11090 PushOnScopeChains(OmpOutParm, S);
11091 } else {
11092 DRD->addDecl(OmpInParm);
11093 DRD->addDecl(OmpOutParm);
11094 }
11095}
11096
11097void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11098 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11099 DiscardCleanupsInEvaluationContext();
11100 PopExpressionEvaluationContext();
11101
11102 PopDeclContext();
11103 PopFunctionScopeInfo();
11104
11105 if (Combiner != nullptr)
11106 DRD->setCombiner(Combiner);
11107 else
11108 DRD->setInvalidDecl();
11109}
11110
11111void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11112 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11113
11114 // Enter new function scope.
11115 PushFunctionScope();
11116 getCurFunction()->setHasBranchProtectedScope();
11117
11118 if (S != nullptr)
11119 PushDeclContext(S, DRD);
11120 else
11121 CurContext = DRD;
11122
Faisal Valid143a0c2017-04-01 21:30:49 +000011123 PushExpressionEvaluationContext(
11124 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011125
11126 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011127 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11128 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11129 // uses semantics of argument handles by value, but it should be passed by
11130 // reference. C lang does not support references, so pass all parameters as
11131 // pointers.
11132 // Create 'T omp_priv;' variable.
11133 auto *OmpPrivParm =
11134 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011135 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11136 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11137 // uses semantics of argument handles by value, but it should be passed by
11138 // reference. C lang does not support references, so pass all parameters as
11139 // pointers.
11140 // Create 'T omp_orig;' variable.
11141 auto *OmpOrigParm =
11142 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011143 if (S != nullptr) {
11144 PushOnScopeChains(OmpPrivParm, S);
11145 PushOnScopeChains(OmpOrigParm, S);
11146 } else {
11147 DRD->addDecl(OmpPrivParm);
11148 DRD->addDecl(OmpOrigParm);
11149 }
11150}
11151
11152void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11153 Expr *Initializer) {
11154 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11155 DiscardCleanupsInEvaluationContext();
11156 PopExpressionEvaluationContext();
11157
11158 PopDeclContext();
11159 PopFunctionScopeInfo();
11160
11161 if (Initializer != nullptr)
11162 DRD->setInitializer(Initializer);
11163 else
11164 DRD->setInvalidDecl();
11165}
11166
11167Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11168 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11169 for (auto *D : DeclReductions.get()) {
11170 if (IsValid) {
11171 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11172 if (S != nullptr)
11173 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11174 } else
11175 D->setInvalidDecl();
11176 }
11177 return DeclReductions;
11178}
11179
David Majnemer9d168222016-08-05 17:44:54 +000011180OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011181 SourceLocation StartLoc,
11182 SourceLocation LParenLoc,
11183 SourceLocation EndLoc) {
11184 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011185 Stmt *HelperValStmt = nullptr;
11186 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011187
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011188 // OpenMP [teams Constrcut, Restrictions]
11189 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011190 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11191 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011192 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011193
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011194 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11195 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11196 if (CaptureRegion != OMPD_unknown) {
11197 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11198 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11199 HelperValStmt = buildPreInits(Context, Captures);
11200 }
11201
11202 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11203 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011204}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011205
11206OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11207 SourceLocation StartLoc,
11208 SourceLocation LParenLoc,
11209 SourceLocation EndLoc) {
11210 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011211 Stmt *HelperValStmt = nullptr;
11212 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011213
11214 // OpenMP [teams Constrcut, Restrictions]
11215 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011216 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11217 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011218 return nullptr;
11219
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011220 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11221 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11222 if (CaptureRegion != OMPD_unknown) {
11223 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11224 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11225 HelperValStmt = buildPreInits(Context, Captures);
11226 }
11227
11228 return new (Context) OMPThreadLimitClause(
11229 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011230}
Alexey Bataeva0569352015-12-01 10:17:31 +000011231
11232OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11233 SourceLocation StartLoc,
11234 SourceLocation LParenLoc,
11235 SourceLocation EndLoc) {
11236 Expr *ValExpr = Priority;
11237
11238 // OpenMP [2.9.1, task Constrcut]
11239 // The priority-value is a non-negative numerical scalar expression.
11240 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11241 /*StrictlyPositive=*/false))
11242 return nullptr;
11243
11244 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11245}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011246
11247OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11248 SourceLocation StartLoc,
11249 SourceLocation LParenLoc,
11250 SourceLocation EndLoc) {
11251 Expr *ValExpr = Grainsize;
11252
11253 // OpenMP [2.9.2, taskloop Constrcut]
11254 // The parameter of the grainsize clause must be a positive integer
11255 // expression.
11256 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11257 /*StrictlyPositive=*/true))
11258 return nullptr;
11259
11260 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11261}
Alexey Bataev382967a2015-12-08 12:06:20 +000011262
11263OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11264 SourceLocation StartLoc,
11265 SourceLocation LParenLoc,
11266 SourceLocation EndLoc) {
11267 Expr *ValExpr = NumTasks;
11268
11269 // OpenMP [2.9.2, taskloop Constrcut]
11270 // The parameter of the num_tasks clause must be a positive integer
11271 // expression.
11272 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11273 /*StrictlyPositive=*/true))
11274 return nullptr;
11275
11276 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11277}
11278
Alexey Bataev28c75412015-12-15 08:19:24 +000011279OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11280 SourceLocation LParenLoc,
11281 SourceLocation EndLoc) {
11282 // OpenMP [2.13.2, critical construct, Description]
11283 // ... where hint-expression is an integer constant expression that evaluates
11284 // to a valid lock hint.
11285 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11286 if (HintExpr.isInvalid())
11287 return nullptr;
11288 return new (Context)
11289 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11290}
11291
Carlo Bertollib4adf552016-01-15 18:50:31 +000011292OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11293 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11294 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11295 SourceLocation EndLoc) {
11296 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11297 std::string Values;
11298 Values += "'";
11299 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11300 Values += "'";
11301 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11302 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11303 return nullptr;
11304 }
11305 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011306 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011307 if (ChunkSize) {
11308 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11309 !ChunkSize->isInstantiationDependent() &&
11310 !ChunkSize->containsUnexpandedParameterPack()) {
11311 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11312 ExprResult Val =
11313 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11314 if (Val.isInvalid())
11315 return nullptr;
11316
11317 ValExpr = Val.get();
11318
11319 // OpenMP [2.7.1, Restrictions]
11320 // chunk_size must be a loop invariant integer expression with a positive
11321 // value.
11322 llvm::APSInt Result;
11323 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11324 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11325 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11326 << "dist_schedule" << ChunkSize->getSourceRange();
11327 return nullptr;
11328 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011329 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11330 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011331 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11332 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11333 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011334 }
11335 }
11336 }
11337
11338 return new (Context)
11339 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011340 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011341}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011342
11343OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11344 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11345 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11346 SourceLocation KindLoc, SourceLocation EndLoc) {
11347 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011348 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011349 std::string Value;
11350 SourceLocation Loc;
11351 Value += "'";
11352 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11353 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011354 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011355 Loc = MLoc;
11356 } else {
11357 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011358 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011359 Loc = KindLoc;
11360 }
11361 Value += "'";
11362 Diag(Loc, diag::err_omp_unexpected_clause_value)
11363 << Value << getOpenMPClauseName(OMPC_defaultmap);
11364 return nullptr;
11365 }
11366
11367 return new (Context)
11368 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11369}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011370
11371bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11372 DeclContext *CurLexicalContext = getCurLexicalContext();
11373 if (!CurLexicalContext->isFileContext() &&
11374 !CurLexicalContext->isExternCContext() &&
11375 !CurLexicalContext->isExternCXXContext()) {
11376 Diag(Loc, diag::err_omp_region_not_file_context);
11377 return false;
11378 }
11379 if (IsInOpenMPDeclareTargetContext) {
11380 Diag(Loc, diag::err_omp_enclosed_declare_target);
11381 return false;
11382 }
11383
11384 IsInOpenMPDeclareTargetContext = true;
11385 return true;
11386}
11387
11388void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11389 assert(IsInOpenMPDeclareTargetContext &&
11390 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11391
11392 IsInOpenMPDeclareTargetContext = false;
11393}
11394
David Majnemer9d168222016-08-05 17:44:54 +000011395void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11396 CXXScopeSpec &ScopeSpec,
11397 const DeclarationNameInfo &Id,
11398 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11399 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011400 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11401 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11402
11403 if (Lookup.isAmbiguous())
11404 return;
11405 Lookup.suppressDiagnostics();
11406
11407 if (!Lookup.isSingleResult()) {
11408 if (TypoCorrection Corrected =
11409 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11410 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11411 CTK_ErrorRecovery)) {
11412 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11413 << Id.getName());
11414 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11415 return;
11416 }
11417
11418 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11419 return;
11420 }
11421
11422 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11423 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11424 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11425 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11426
11427 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11428 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11429 ND->addAttr(A);
11430 if (ASTMutationListener *ML = Context.getASTMutationListener())
11431 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11432 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11433 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11434 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11435 << Id.getName();
11436 }
11437 } else
11438 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11439}
11440
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011441static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11442 Sema &SemaRef, Decl *D) {
11443 if (!D)
11444 return;
11445 Decl *LD = nullptr;
11446 if (isa<TagDecl>(D)) {
11447 LD = cast<TagDecl>(D)->getDefinition();
11448 } else if (isa<VarDecl>(D)) {
11449 LD = cast<VarDecl>(D)->getDefinition();
11450
11451 // If this is an implicit variable that is legal and we do not need to do
11452 // anything.
11453 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011454 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11455 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11456 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011457 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011458 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011459 return;
11460 }
11461
11462 } else if (isa<FunctionDecl>(D)) {
11463 const FunctionDecl *FD = nullptr;
11464 if (cast<FunctionDecl>(D)->hasBody(FD))
11465 LD = const_cast<FunctionDecl *>(FD);
11466
11467 // If the definition is associated with the current declaration in the
11468 // target region (it can be e.g. a lambda) that is legal and we do not need
11469 // to do anything else.
11470 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011471 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11472 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11473 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011474 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011475 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011476 return;
11477 }
11478 }
11479 if (!LD)
11480 LD = D;
11481 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11482 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11483 // Outlined declaration is not declared target.
11484 if (LD->isOutOfLine()) {
11485 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11486 SemaRef.Diag(SL, diag::note_used_here) << SR;
11487 } else {
11488 DeclContext *DC = LD->getDeclContext();
11489 while (DC) {
11490 if (isa<FunctionDecl>(DC) &&
11491 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11492 break;
11493 DC = DC->getParent();
11494 }
11495 if (DC)
11496 return;
11497
11498 // Is not declared in target context.
11499 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11500 SemaRef.Diag(SL, diag::note_used_here) << SR;
11501 }
11502 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011503 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11504 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11505 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011506 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011507 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011508 }
11509}
11510
11511static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11512 Sema &SemaRef, DSAStackTy *Stack,
11513 ValueDecl *VD) {
11514 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11515 return true;
11516 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11517 return false;
11518 return true;
11519}
11520
11521void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11522 if (!D || D->isInvalidDecl())
11523 return;
11524 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11525 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11526 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11527 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11528 if (DSAStack->isThreadPrivate(VD)) {
11529 Diag(SL, diag::err_omp_threadprivate_in_target);
11530 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11531 return;
11532 }
11533 }
11534 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11535 // Problem if any with var declared with incomplete type will be reported
11536 // as normal, so no need to check it here.
11537 if ((E || !VD->getType()->isIncompleteType()) &&
11538 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11539 // Mark decl as declared target to prevent further diagnostic.
11540 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011541 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11542 Context, OMPDeclareTargetDeclAttr::MT_To);
11543 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011544 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011545 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011546 }
11547 return;
11548 }
11549 }
11550 if (!E) {
11551 // Checking declaration inside declare target region.
11552 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11553 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011554 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11555 Context, OMPDeclareTargetDeclAttr::MT_To);
11556 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011557 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011558 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011559 }
11560 return;
11561 }
11562 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11563}
Samuel Antao661c0902016-05-26 17:39:58 +000011564
11565OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11566 SourceLocation StartLoc,
11567 SourceLocation LParenLoc,
11568 SourceLocation EndLoc) {
11569 MappableVarListInfo MVLI(VarList);
11570 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11571 if (MVLI.ProcessedVarList.empty())
11572 return nullptr;
11573
11574 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11575 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11576 MVLI.VarComponents);
11577}
Samuel Antaoec172c62016-05-26 17:49:04 +000011578
11579OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11580 SourceLocation StartLoc,
11581 SourceLocation LParenLoc,
11582 SourceLocation EndLoc) {
11583 MappableVarListInfo MVLI(VarList);
11584 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11585 if (MVLI.ProcessedVarList.empty())
11586 return nullptr;
11587
11588 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11589 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11590 MVLI.VarComponents);
11591}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011592
11593OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11594 SourceLocation StartLoc,
11595 SourceLocation LParenLoc,
11596 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011597 MappableVarListInfo MVLI(VarList);
11598 SmallVector<Expr *, 8> PrivateCopies;
11599 SmallVector<Expr *, 8> Inits;
11600
Carlo Bertolli2404b172016-07-13 15:37:16 +000011601 for (auto &RefExpr : VarList) {
11602 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11603 SourceLocation ELoc;
11604 SourceRange ERange;
11605 Expr *SimpleRefExpr = RefExpr;
11606 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11607 if (Res.second) {
11608 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011609 MVLI.ProcessedVarList.push_back(RefExpr);
11610 PrivateCopies.push_back(nullptr);
11611 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011612 }
11613 ValueDecl *D = Res.first;
11614 if (!D)
11615 continue;
11616
11617 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011618 Type = Type.getNonReferenceType().getUnqualifiedType();
11619
11620 auto *VD = dyn_cast<VarDecl>(D);
11621
11622 // Item should be a pointer or reference to pointer.
11623 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011624 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11625 << 0 << RefExpr->getSourceRange();
11626 continue;
11627 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011628
11629 // Build the private variable and the expression that refers to it.
11630 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11631 D->hasAttrs() ? &D->getAttrs() : nullptr);
11632 if (VDPrivate->isInvalidDecl())
11633 continue;
11634
11635 CurContext->addDecl(VDPrivate);
11636 auto VDPrivateRefExpr = buildDeclRefExpr(
11637 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11638
11639 // Add temporary variable to initialize the private copy of the pointer.
11640 auto *VDInit =
11641 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11642 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11643 RefExpr->getExprLoc());
11644 AddInitializerToDecl(VDPrivate,
11645 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011646 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011647
11648 // If required, build a capture to implement the privatization initialized
11649 // with the current list item value.
11650 DeclRefExpr *Ref = nullptr;
11651 if (!VD)
11652 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11653 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11654 PrivateCopies.push_back(VDPrivateRefExpr);
11655 Inits.push_back(VDInitRefExpr);
11656
11657 // We need to add a data sharing attribute for this variable to make sure it
11658 // is correctly captured. A variable that shows up in a use_device_ptr has
11659 // similar properties of a first private variable.
11660 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11661
11662 // Create a mappable component for the list item. List items in this clause
11663 // only need a component.
11664 MVLI.VarBaseDeclarations.push_back(D);
11665 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11666 MVLI.VarComponents.back().push_back(
11667 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011668 }
11669
Samuel Antaocc10b852016-07-28 14:23:26 +000011670 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011671 return nullptr;
11672
Samuel Antaocc10b852016-07-28 14:23:26 +000011673 return OMPUseDevicePtrClause::Create(
11674 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11675 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011676}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011677
11678OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11679 SourceLocation StartLoc,
11680 SourceLocation LParenLoc,
11681 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011682 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011683 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011684 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011685 SourceLocation ELoc;
11686 SourceRange ERange;
11687 Expr *SimpleRefExpr = RefExpr;
11688 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11689 if (Res.second) {
11690 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011691 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011692 }
11693 ValueDecl *D = Res.first;
11694 if (!D)
11695 continue;
11696
11697 QualType Type = D->getType();
11698 // item should be a pointer or array or reference to pointer or array
11699 if (!Type.getNonReferenceType()->isPointerType() &&
11700 !Type.getNonReferenceType()->isArrayType()) {
11701 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11702 << 0 << RefExpr->getSourceRange();
11703 continue;
11704 }
Samuel Antao6890b092016-07-28 14:25:09 +000011705
11706 // Check if the declaration in the clause does not show up in any data
11707 // sharing attribute.
11708 auto DVar = DSAStack->getTopDSA(D, false);
11709 if (isOpenMPPrivate(DVar.CKind)) {
11710 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11711 << getOpenMPClauseName(DVar.CKind)
11712 << getOpenMPClauseName(OMPC_is_device_ptr)
11713 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11714 ReportOriginalDSA(*this, DSAStack, D, DVar);
11715 continue;
11716 }
11717
11718 Expr *ConflictExpr;
11719 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011720 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011721 [&ConflictExpr](
11722 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11723 OpenMPClauseKind) -> bool {
11724 ConflictExpr = R.front().getAssociatedExpression();
11725 return true;
11726 })) {
11727 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11728 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11729 << ConflictExpr->getSourceRange();
11730 continue;
11731 }
11732
11733 // Store the components in the stack so that they can be used to check
11734 // against other clauses later on.
11735 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11736 DSAStack->addMappableExpressionComponents(
11737 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11738
11739 // Record the expression we've just processed.
11740 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11741
11742 // Create a mappable component for the list item. List items in this clause
11743 // only need a component. We use a null declaration to signal fields in
11744 // 'this'.
11745 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11746 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11747 "Unexpected device pointer expression!");
11748 MVLI.VarBaseDeclarations.push_back(
11749 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11750 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11751 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011752 }
11753
Samuel Antao6890b092016-07-28 14:25:09 +000011754 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011755 return nullptr;
11756
Samuel Antao6890b092016-07-28 14:25:09 +000011757 return OMPIsDevicePtrClause::Create(
11758 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11759 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011760}