blob: 290a7bbd15ba7bbe2c2eba571932c30807e2770d [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000142 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000143 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000144 bool NowaitRegion = false;
145 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000146 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000147 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000148 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000149 /// Reference to the taskgroup task_reduction reference expression.
150 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000151 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000152 /// List of globals marked as declare target link in this target region
153 /// (isOpenMPTargetExecutionDirective(Directive) == true).
154 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000155 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000156 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000157 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
158 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000159 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 };
161
Alexey Bataeve3727102018-04-18 15:57:46 +0000162 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000164 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000165 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000166 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
167 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000168 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000169 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000170 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000171 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000172 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000173 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000174 /// captured by reference.
175 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000176 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000177 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000178
Richard Smith375dec52019-05-30 23:21:14 +0000179 /// Iterators over the stack iterate in order from innermost to outermost
180 /// directive.
181 using const_iterator = StackTy::const_reverse_iterator;
182 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000183 return Stack.empty() ? const_iterator()
184 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000185 }
186 const_iterator end() const {
187 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
188 }
189 using iterator = StackTy::reverse_iterator;
190 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000191 return Stack.empty() ? iterator()
192 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000193 }
194 iterator end() {
195 return Stack.empty() ? iterator() : Stack.back().first.rend();
196 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197
Richard Smith375dec52019-05-30 23:21:14 +0000198 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000199
Alexey Bataev4b465392017-04-26 15:06:24 +0000200 bool isStackEmpty() const {
201 return Stack.empty() ||
202 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000203 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000204 }
Richard Smith375dec52019-05-30 23:21:14 +0000205 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000206 return isStackEmpty() ? 0
207 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000208 }
209
210 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000211 size_t Size = getStackSize();
212 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000213 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000214 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000215 }
216 const SharingMapTy *getTopOfStackOrNull() const {
217 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
218 }
219 SharingMapTy &getTopOfStack() {
220 assert(!isStackEmpty() && "no current directive");
221 return *getTopOfStackOrNull();
222 }
223 const SharingMapTy &getTopOfStack() const {
224 return const_cast<DSAStackTy&>(*this).getTopOfStack();
225 }
226
227 SharingMapTy *getSecondOnStackOrNull() {
228 size_t Size = getStackSize();
229 if (Size <= 1)
230 return nullptr;
231 return &Stack.back().first[Size - 2];
232 }
233 const SharingMapTy *getSecondOnStackOrNull() const {
234 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
235 }
236
237 /// Get the stack element at a certain level (previously returned by
238 /// \c getNestingLevel).
239 ///
240 /// Note that nesting levels count from outermost to innermost, and this is
241 /// the reverse of our iteration order where new inner levels are pushed at
242 /// the front of the stack.
243 SharingMapTy &getStackElemAtLevel(unsigned Level) {
244 assert(Level < getStackSize() && "no such stack element");
245 return Stack.back().first[Level];
246 }
247 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
248 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
249 }
250
251 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
252
253 /// Checks if the variable is a local for OpenMP region.
254 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000255
Kelvin Li1408f912018-09-26 04:28:39 +0000256 /// Vector of previously declared requires directives
257 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000258 /// omp_allocator_handle_t type.
259 QualType OMPAllocatorHandleT;
260 /// Expression for the predefined allocators.
261 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
262 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000263 /// Vector of previously encountered target directives
264 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000265
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000267 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000268
Alexey Bataev27ef9512019-03-20 20:14:22 +0000269 /// Sets omp_allocator_handle_t type.
270 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
271 /// Gets omp_allocator_handle_t type.
272 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
273 /// Sets the given default allocator.
274 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
275 Expr *Allocator) {
276 OMPPredefinedAllocators[AllocatorKind] = Allocator;
277 }
278 /// Returns the specified default allocator.
279 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
280 return OMPPredefinedAllocators[AllocatorKind];
281 }
282
Alexey Bataevaac108a2015-06-23 04:51:00 +0000283 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000284 OpenMPClauseKind getClauseParsingMode() const {
285 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
286 return ClauseKindMode;
287 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000288 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000289
Richard Smith0621a8f2019-05-31 00:45:10 +0000290 bool isBodyComplete() const {
291 const SharingMapTy *Top = getTopOfStackOrNull();
292 return Top && Top->BodyComplete;
293 }
294 void setBodyComplete() {
295 getTopOfStack().BodyComplete = true;
296 }
297
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000298 bool isForceVarCapturing() const { return ForceCapturing; }
299 void setForceVarCapturing(bool V) { ForceCapturing = V; }
300
Alexey Bataev60705422018-10-30 15:50:12 +0000301 void setForceCaptureByReferenceInTargetExecutable(bool V) {
302 ForceCaptureByReferenceInTargetExecutable = V;
303 }
304 bool isForceCaptureByReferenceInTargetExecutable() const {
305 return ForceCaptureByReferenceInTargetExecutable;
306 }
307
Alexey Bataev758e55e2013-09-06 18:03:48 +0000308 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000309 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000310 assert(!IgnoredStackElements &&
311 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000312 if (Stack.empty() ||
313 Stack.back().second != CurrentNonCapturingFunctionScope)
314 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
315 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
316 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000317 }
318
319 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000320 assert(!IgnoredStackElements &&
321 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000322 assert(!Stack.back().first.empty() &&
323 "Data-sharing attributes stack is empty!");
324 Stack.back().first.pop_back();
325 }
326
Richard Smith0621a8f2019-05-31 00:45:10 +0000327 /// RAII object to temporarily leave the scope of a directive when we want to
328 /// logically operate in its parent.
329 class ParentDirectiveScope {
330 DSAStackTy &Self;
331 bool Active;
332 public:
333 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
334 : Self(Self), Active(false) {
335 if (Activate)
336 enable();
337 }
338 ~ParentDirectiveScope() { disable(); }
339 void disable() {
340 if (Active) {
341 --Self.IgnoredStackElements;
342 Active = false;
343 }
344 }
345 void enable() {
346 if (!Active) {
347 ++Self.IgnoredStackElements;
348 Active = true;
349 }
350 }
351 };
352
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000353 /// Marks that we're started loop parsing.
354 void loopInit() {
355 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
356 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000357 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000358 }
359 /// Start capturing of the variables in the loop context.
360 void loopStart() {
361 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
362 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000363 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000364 }
365 /// true, if variables are captured, false otherwise.
366 bool isLoopStarted() const {
367 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
368 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000369 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000370 }
371 /// Marks (or clears) declaration as possibly loop counter.
372 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000373 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000374 D ? D->getCanonicalDecl() : D;
375 }
376 /// Gets the possible loop counter decl.
377 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000378 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000379 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000380 /// Start new OpenMP region stack in new non-capturing function.
381 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000382 assert(!IgnoredStackElements &&
383 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
385 assert(!isa<CapturingScopeInfo>(CurFnScope));
386 CurrentNonCapturingFunctionScope = CurFnScope;
387 }
388 /// Pop region stack for non-capturing function.
389 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000390 assert(!IgnoredStackElements &&
391 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000392 if (!Stack.empty() && Stack.back().second == OldFSI) {
393 assert(Stack.back().first.empty());
394 Stack.pop_back();
395 }
396 CurrentNonCapturingFunctionScope = nullptr;
397 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
398 if (!isa<CapturingScopeInfo>(FSI)) {
399 CurrentNonCapturingFunctionScope = FSI;
400 break;
401 }
402 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000403 }
404
Alexey Bataeve3727102018-04-18 15:57:46 +0000405 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000406 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000407 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000408 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000409 getCriticalWithHint(const DeclarationNameInfo &Name) const {
410 auto I = Criticals.find(Name.getAsString());
411 if (I != Criticals.end())
412 return I->second;
413 return std::make_pair(nullptr, llvm::APSInt());
414 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000415 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000416 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000417 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000418 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000419
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000420 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000421 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000423 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000424 /// \return The index of the loop control variable in the list of associated
425 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000426 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000427 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000428 /// parent region.
429 /// \return The index of the loop control variable in the list of associated
430 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000431 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000433 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000434 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000437 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000438 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439
Alexey Bataevfa312f32017-07-21 18:48:21 +0000440 /// Adds additional information for the reduction items with the reduction id
441 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000442 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000443 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000444 /// Adds additional information for the reduction items with the reduction id
445 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000446 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000447 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000448 /// Returns the location and reduction operation from the innermost parent
449 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000450 const DSAVarData
451 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
452 BinaryOperatorKind &BOK,
453 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000454 /// Returns the location and reduction operation from the innermost parent
455 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000456 const DSAVarData
457 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
458 const Expr *&ReductionRef,
459 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000460 /// Return reduction reference expression for the current taskgroup.
461 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000462 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000463 "taskgroup reference expression requested for non taskgroup "
464 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000465 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000466 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000467 /// Checks if the given \p VD declaration is actually a taskgroup reduction
468 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000469 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000470 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
471 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000472 ->getDecl() == VD;
473 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000474
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000475 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000476 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000477 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000478 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000479 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000480 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000481 /// match specified \a CPred predicate in any directive which matches \a DPred
482 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000483 const DSAVarData
484 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
485 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
486 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000487 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000488 /// match specified \a CPred predicate in any innermost directive which
489 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000490 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000491 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000492 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
493 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000494 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000496 /// attributes which match specified \a CPred predicate at the specified
497 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000498 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000499 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000500 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000502 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000503 /// specified \a DPred predicate.
504 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000505 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000506 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000509 bool hasDirective(
510 const llvm::function_ref<bool(
511 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
512 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000513 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000516 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000517 const SharingMapTy *Top = getTopOfStackOrNull();
518 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000521 OpenMPDirectiveKind getDirective(unsigned Level) const {
522 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000523 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000524 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000525 /// Returns the capture region at the specified level.
526 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
527 unsigned OpenMPCaptureLevel) const {
528 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
529 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
530 return CaptureRegions[OpenMPCaptureLevel];
531 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000533 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000534 const SharingMapTy *Parent = getSecondOnStackOrNull();
535 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000536 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000537
Kelvin Li1408f912018-09-26 04:28:39 +0000538 /// Add requires decl to internal vector
539 void addRequiresDecl(OMPRequiresDecl *RD) {
540 RequiresDecls.push_back(RD);
541 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000542
Alexey Bataev318f431b2019-03-22 15:25:12 +0000543 /// Checks if the defined 'requires' directive has specified type of clause.
544 template <typename ClauseType>
545 bool hasRequiresDeclWithClause() {
546 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
547 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
548 return isa<ClauseType>(C);
549 });
550 });
551 }
552
Kelvin Li1408f912018-09-26 04:28:39 +0000553 /// Checks for a duplicate clause amongst previously declared requires
554 /// directives
555 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
556 bool IsDuplicate = false;
557 for (OMPClause *CNew : ClauseList) {
558 for (const OMPRequiresDecl *D : RequiresDecls) {
559 for (const OMPClause *CPrev : D->clauselists()) {
560 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
561 SemaRef.Diag(CNew->getBeginLoc(),
562 diag::err_omp_requires_clause_redeclaration)
563 << getOpenMPClauseName(CNew->getClauseKind());
564 SemaRef.Diag(CPrev->getBeginLoc(),
565 diag::note_omp_requires_previous_clause)
566 << getOpenMPClauseName(CPrev->getClauseKind());
567 IsDuplicate = true;
568 }
569 }
570 }
571 }
572 return IsDuplicate;
573 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000574
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000575 /// Add location of previously encountered target to internal vector
576 void addTargetDirLocation(SourceLocation LocStart) {
577 TargetLocations.push_back(LocStart);
578 }
579
580 // Return previously encountered target region locations.
581 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
582 return TargetLocations;
583 }
584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000585 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000586 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000587 getTopOfStack().DefaultAttr = DSA_none;
588 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000589 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000590 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000591 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000592 getTopOfStack().DefaultAttr = DSA_shared;
593 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000594 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000595 /// Set default data mapping attribute to 'tofrom:scalar'.
596 void setDefaultDMAToFromScalar(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000597 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
598 getTopOfStack().DefaultMapAttrLoc = Loc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600
601 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000602 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000603 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000604 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000605 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000606 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000607 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000608 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000609 DefaultMapAttributes getDefaultDMA() const {
610 return isStackEmpty() ? DMA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000611 : getTopOfStack().DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000612 }
613 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000614 return getStackElemAtLevel(Level).DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000615 }
616 SourceLocation getDefaultDMALocation() const {
617 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000618 : getTopOfStack().DefaultMapAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000619 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000621 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000622 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000623 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000624 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000625 }
626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000627 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000628 void setOrderedRegion(bool IsOrdered, const Expr *Param,
629 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000630 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000631 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000632 else
Richard Smith375dec52019-05-30 23:21:14 +0000633 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000634 }
635 /// Returns true, if region is ordered (has associated 'ordered' clause),
636 /// false - otherwise.
637 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000638 if (const SharingMapTy *Top = getTopOfStackOrNull())
639 return Top->OrderedRegion.hasValue();
640 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000641 }
642 /// Returns optional parameter for the ordered region.
643 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000644 if (const SharingMapTy *Top = getTopOfStackOrNull())
645 if (Top->OrderedRegion.hasValue())
646 return Top->OrderedRegion.getValue();
647 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000648 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000649 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000650 /// 'ordered' clause), false - otherwise.
651 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000652 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
653 return Parent->OrderedRegion.hasValue();
654 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000655 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000656 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000657 std::pair<const Expr *, OMPOrderedClause *>
658 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000659 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
660 if (Parent->OrderedRegion.hasValue())
661 return Parent->OrderedRegion.getValue();
662 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000663 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000664 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000665 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000666 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000667 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000668 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000669 /// 'nowait' clause), false - otherwise.
670 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000671 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
672 return Parent->NowaitRegion;
673 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000674 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000675 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000676 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000677 if (SharingMapTy *Parent = getSecondOnStackOrNull())
678 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000679 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000680 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000681 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000682 const SharingMapTy *Top = getTopOfStackOrNull();
683 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000684 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000686 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000687 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000688 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000689 if (Val > 1)
690 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000691 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000692 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000693 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000694 const SharingMapTy *Top = getTopOfStackOrNull();
695 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000696 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000697 /// Returns true if the construct is associated with multiple loops.
698 bool hasMutipleLoops() const {
699 const SharingMapTy *Top = getTopOfStackOrNull();
700 return Top ? Top->HasMutipleLoops : false;
701 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000702
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000703 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000704 /// region.
705 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000706 if (SharingMapTy *Parent = getSecondOnStackOrNull())
707 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000708 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000709 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000710 bool hasInnerTeamsRegion() const {
711 return getInnerTeamsRegionLoc().isValid();
712 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000713 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000714 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000715 const SharingMapTy *Top = getTopOfStackOrNull();
716 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000717 }
718
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000719 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000720 const SharingMapTy *Top = getTopOfStackOrNull();
721 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000722 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000723 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000724 const SharingMapTy *Top = getTopOfStackOrNull();
725 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000726 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000727
Samuel Antao4c8035b2016-12-12 18:00:20 +0000728 /// Do the check specified in \a Check to all component lists and return true
729 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000730 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000731 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000732 const llvm::function_ref<
733 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000734 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000735 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 if (isStackEmpty())
737 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000738 auto SI = begin();
739 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000740
741 if (SI == SE)
742 return false;
743
Alexey Bataeve3727102018-04-18 15:57:46 +0000744 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000745 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000746 else
747 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000748
749 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000750 auto MI = SI->MappedExprComponents.find(VD);
751 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000752 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
753 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000754 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000755 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000756 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000757 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000758 }
759
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000760 /// Do the check specified in \a Check to all component lists at a given level
761 /// and return true if any issue is found.
762 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000763 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000764 const llvm::function_ref<
765 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000766 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000767 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000768 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000769 return false;
770
Richard Smith375dec52019-05-30 23:21:14 +0000771 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
772 auto MI = StackElem.MappedExprComponents.find(VD);
773 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000774 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
775 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000776 if (Check(L, MI->second.Kind))
777 return true;
778 return false;
779 }
780
Samuel Antao4c8035b2016-12-12 18:00:20 +0000781 /// Create a new mappable expression component list associated with a given
782 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000783 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000784 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000785 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
786 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000787 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000788 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000789 MEC.Components.resize(MEC.Components.size() + 1);
790 MEC.Components.back().append(Components.begin(), Components.end());
791 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000792 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000793
794 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000795 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000796 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000797 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000798 void addDoacrossDependClause(OMPDependClause *C,
799 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000800 SharingMapTy *Parent = getSecondOnStackOrNull();
801 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
802 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000803 }
804 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
805 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000806 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000807 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000808 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000809 return llvm::make_range(Ref.begin(), Ref.end());
810 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000811 return llvm::make_range(StackElem.DoacrossDepends.end(),
812 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000813 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000814
815 // Store types of classes which have been explicitly mapped
816 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000817 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000818 StackElem.MappedClassesQualTypes.insert(QT);
819 }
820
821 // Return set of mapped classes types
822 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000823 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000824 return StackElem.MappedClassesQualTypes.count(QT) != 0;
825 }
826
Alexey Bataeva495c642019-03-11 19:51:42 +0000827 /// Adds global declare target to the parent target region.
828 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
829 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
830 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
831 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000832 for (auto &Elem : *this) {
833 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
834 Elem.DeclareTargetLinkVarDecls.push_back(E);
835 return;
836 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000837 }
838 }
839
840 /// Returns the list of globals with declare target link if current directive
841 /// is target.
842 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
843 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
844 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000845 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000846 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000847};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000848
849bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
850 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
851}
852
853bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000854 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
855 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000856}
Alexey Bataeve3727102018-04-18 15:57:46 +0000857
Alexey Bataeved09d242014-05-28 05:53:51 +0000858} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000859
Alexey Bataeve3727102018-04-18 15:57:46 +0000860static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000861 if (const auto *FE = dyn_cast<FullExpr>(E))
862 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000863
Alexey Bataeve3727102018-04-18 15:57:46 +0000864 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000865 E = MTE->GetTemporaryExpr();
866
Alexey Bataeve3727102018-04-18 15:57:46 +0000867 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000868 E = Binder->getSubExpr();
869
Alexey Bataeve3727102018-04-18 15:57:46 +0000870 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000871 E = ICE->getSubExprAsWritten();
872 return E->IgnoreParens();
873}
874
Alexey Bataeve3727102018-04-18 15:57:46 +0000875static Expr *getExprAsWritten(Expr *E) {
876 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
877}
878
879static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
880 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
881 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000882 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000883 const auto *VD = dyn_cast<VarDecl>(D);
884 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000885 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000886 VD = VD->getCanonicalDecl();
887 D = VD;
888 } else {
889 assert(FD);
890 FD = FD->getCanonicalDecl();
891 D = FD;
892 }
893 return D;
894}
895
Alexey Bataeve3727102018-04-18 15:57:46 +0000896static ValueDecl *getCanonicalDecl(ValueDecl *D) {
897 return const_cast<ValueDecl *>(
898 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
899}
900
Richard Smith375dec52019-05-30 23:21:14 +0000901DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000902 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000903 D = getCanonicalDecl(D);
904 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000905 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000906 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000907 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000908 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
909 // in a region but not in construct]
910 // File-scope or namespace-scope variables referenced in called routines
911 // in the region are shared unless they appear in a threadprivate
912 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000914 DVar.CKind = OMPC_shared;
915
916 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
917 // in a region but not in construct]
918 // Variables with static storage duration that are declared in called
919 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000920 if (VD && VD->hasGlobalStorage())
921 DVar.CKind = OMPC_shared;
922
923 // Non-static data members are shared by default.
924 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000925 DVar.CKind = OMPC_shared;
926
Alexey Bataev758e55e2013-09-06 18:03:48 +0000927 return DVar;
928 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000929
Alexey Bataevec3da872014-01-31 05:15:34 +0000930 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
931 // in a Construct, C/C++, predetermined, p.1]
932 // Variables with automatic storage duration that are declared in a scope
933 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000934 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
935 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000936 DVar.CKind = OMPC_private;
937 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000938 }
939
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000940 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000941 // Explicitly specified attributes and local variables with predetermined
942 // attributes.
943 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000944 const DSAInfo &Data = Iter->SharingMap.lookup(D);
945 DVar.RefExpr = Data.RefExpr.getPointer();
946 DVar.PrivateCopy = Data.PrivateCopy;
947 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000948 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000949 return DVar;
950 }
951
952 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
953 // in a Construct, C/C++, implicitly determined, p.1]
954 // In a parallel or task construct, the data-sharing attributes of these
955 // variables are determined by the default clause, if present.
956 switch (Iter->DefaultAttr) {
957 case DSA_shared:
958 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000959 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000960 return DVar;
961 case DSA_none:
962 return DVar;
963 case DSA_unspecified:
964 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
965 // in a Construct, implicitly determined, p.2]
966 // In a parallel construct, if no default clause is present, these
967 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000968 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +0000969 if ((isOpenMPParallelDirective(DVar.DKind) &&
970 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000971 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000972 DVar.CKind = OMPC_shared;
973 return DVar;
974 }
975
976 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
977 // in a Construct, implicitly determined, p.4]
978 // In a task construct, if no default clause is present, a variable that in
979 // the enclosing context is determined to be shared by all implicit tasks
980 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000981 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000982 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +0000983 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000984 do {
985 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000986 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000987 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000988 // In a task construct, if no default clause is present, a variable
989 // whose data-sharing attribute is not determined by the rules above is
990 // firstprivate.
991 DVarTemp = getDSA(I, D);
992 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000993 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000994 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995 return DVar;
996 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000997 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000998 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000999 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001000 return DVar;
1001 }
1002 }
1003 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1004 // in a Construct, implicitly determined, p.3]
1005 // For constructs other than task, if no default clause is present, these
1006 // variables inherit their data-sharing attributes from the enclosing
1007 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001008 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001009}
1010
Alexey Bataeve3727102018-04-18 15:57:46 +00001011const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1012 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001013 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001014 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001015 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001016 auto It = StackElem.AlignedMap.find(D);
1017 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001018 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001019 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001020 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001021 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001022 assert(It->second && "Unexpected nullptr expr in the aligned map");
1023 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001024}
1025
Alexey Bataeve3727102018-04-18 15:57:46 +00001026void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001027 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001028 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001029 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001030 StackElem.LCVMap.try_emplace(
1031 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001032}
1033
Alexey Bataeve3727102018-04-18 15:57:46 +00001034const DSAStackTy::LCDeclInfo
1035DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001036 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001038 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001039 auto It = StackElem.LCVMap.find(D);
1040 if (It != StackElem.LCVMap.end())
1041 return It->second;
1042 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001043}
1044
Alexey Bataeve3727102018-04-18 15:57:46 +00001045const DSAStackTy::LCDeclInfo
1046DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001047 const SharingMapTy *Parent = getSecondOnStackOrNull();
1048 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001049 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001050 auto It = Parent->LCVMap.find(D);
1051 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001052 return It->second;
1053 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001054}
1055
Alexey Bataeve3727102018-04-18 15:57:46 +00001056const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001057 const SharingMapTy *Parent = getSecondOnStackOrNull();
1058 assert(Parent && "Data-sharing attributes stack is empty");
1059 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001060 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001061 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001062 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001063 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001064 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001065}
1066
Alexey Bataeve3727102018-04-18 15:57:46 +00001067void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001068 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001069 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001070 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001071 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001072 Data.Attributes = A;
1073 Data.RefExpr.setPointer(E);
1074 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001075 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001076 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001077 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1078 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1079 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1080 (isLoopControlVariable(D).first && A == OMPC_private));
1081 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1082 Data.RefExpr.setInt(/*IntVal=*/true);
1083 return;
1084 }
1085 const bool IsLastprivate =
1086 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1087 Data.Attributes = A;
1088 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1089 Data.PrivateCopy = PrivateCopy;
1090 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001091 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001092 Data.Attributes = A;
1093 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1094 Data.PrivateCopy = nullptr;
1095 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001096 }
1097}
1098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001099/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001100static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001101 StringRef Name, const AttrVec *Attrs = nullptr,
1102 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001103 DeclContext *DC = SemaRef.CurContext;
1104 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1105 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001106 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001107 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1108 if (Attrs) {
1109 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1110 I != E; ++I)
1111 Decl->addAttr(*I);
1112 }
1113 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001114 if (OrigRef) {
1115 Decl->addAttr(
1116 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1117 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001118 return Decl;
1119}
1120
1121static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1122 SourceLocation Loc,
1123 bool RefersToCapture = false) {
1124 D->setReferenced();
1125 D->markUsed(S.Context);
1126 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1127 SourceLocation(), D, RefersToCapture, Loc, Ty,
1128 VK_LValue);
1129}
1130
Alexey Bataeve3727102018-04-18 15:57:46 +00001131void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001132 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001133 D = getCanonicalDecl(D);
1134 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001135 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001136 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001137 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001138 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001139 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001140 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001141 "Additional reduction info may be specified only once for reduction "
1142 "items.");
1143 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001144 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001145 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001146 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001147 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1148 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001149 TaskgroupReductionRef =
1150 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001151 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001152}
1153
Alexey Bataeve3727102018-04-18 15:57:46 +00001154void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001155 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001156 D = getCanonicalDecl(D);
1157 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001158 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001159 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001160 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001161 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001162 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001163 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001164 "Additional reduction info may be specified only once for reduction "
1165 "items.");
1166 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001167 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001168 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001169 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001170 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1171 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001172 TaskgroupReductionRef =
1173 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001174 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001175}
1176
Alexey Bataeve3727102018-04-18 15:57:46 +00001177const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1178 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1179 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001180 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001181 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001182 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001183 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001184 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001185 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001186 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001187 if (!ReductionData.ReductionOp ||
1188 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001189 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001190 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001191 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001192 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1193 "expression for the descriptor is not "
1194 "set.");
1195 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001196 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1197 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001198 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001199 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001200}
1201
Alexey Bataeve3727102018-04-18 15:57:46 +00001202const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1203 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1204 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001205 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001206 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001207 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001208 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001209 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001210 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001211 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001212 if (!ReductionData.ReductionOp ||
1213 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001214 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001215 SR = ReductionData.ReductionRange;
1216 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001217 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1218 "expression for the descriptor is not "
1219 "set.");
1220 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001221 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1222 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001223 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001224 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001225}
1226
Richard Smith375dec52019-05-30 23:21:14 +00001227bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001228 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001229 for (const_iterator E = end(); I != E; ++I) {
1230 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1231 isOpenMPTargetExecutionDirective(I->Directive)) {
1232 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1233 Scope *CurScope = getCurScope();
1234 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1235 CurScope = CurScope->getParent();
1236 return CurScope != TopScope;
1237 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001238 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001239 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001240}
1241
Joel E. Dennyd2649292019-01-04 22:11:56 +00001242static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1243 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001244 bool *IsClassType = nullptr) {
1245 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001246 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001247 bool IsConstant = Type.isConstant(Context);
1248 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001249 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1250 ? Type->getAsCXXRecordDecl()
1251 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001252 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1253 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1254 RD = CTD->getTemplatedDecl();
1255 if (IsClassType)
1256 *IsClassType = RD;
1257 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1258 RD->hasDefinition() && RD->hasMutableFields());
1259}
1260
Joel E. Dennyd2649292019-01-04 22:11:56 +00001261static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1262 QualType Type, OpenMPClauseKind CKind,
1263 SourceLocation ELoc,
1264 bool AcceptIfMutable = true,
1265 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001266 ASTContext &Context = SemaRef.getASTContext();
1267 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001268 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1269 unsigned Diag = ListItemNotVar
1270 ? diag::err_omp_const_list_item
1271 : IsClassType ? diag::err_omp_const_not_mutable_variable
1272 : diag::err_omp_const_variable;
1273 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1274 if (!ListItemNotVar && D) {
1275 const VarDecl *VD = dyn_cast<VarDecl>(D);
1276 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1277 VarDecl::DeclarationOnly;
1278 SemaRef.Diag(D->getLocation(),
1279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1280 << D;
1281 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001282 return true;
1283 }
1284 return false;
1285}
1286
Alexey Bataeve3727102018-04-18 15:57:46 +00001287const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1288 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001289 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001290 DSAVarData DVar;
1291
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001292 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001293 auto TI = Threadprivates.find(D);
1294 if (TI != Threadprivates.end()) {
1295 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001296 DVar.CKind = OMPC_threadprivate;
1297 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001298 }
1299 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001300 DVar.RefExpr = buildDeclRefExpr(
1301 SemaRef, VD, D->getType().getNonReferenceType(),
1302 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1303 DVar.CKind = OMPC_threadprivate;
1304 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001305 return DVar;
1306 }
1307 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1308 // in a Construct, C/C++, predetermined, p.1]
1309 // Variables appearing in threadprivate directives are threadprivate.
1310 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1311 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1312 SemaRef.getLangOpts().OpenMPUseTLS &&
1313 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1314 (VD && VD->getStorageClass() == SC_Register &&
1315 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1316 DVar.RefExpr = buildDeclRefExpr(
1317 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1318 DVar.CKind = OMPC_threadprivate;
1319 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1320 return DVar;
1321 }
1322 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1323 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1324 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001325 const_iterator IterTarget =
1326 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1327 return isOpenMPTargetExecutionDirective(Data.Directive);
1328 });
1329 if (IterTarget != end()) {
1330 const_iterator ParentIterTarget = IterTarget + 1;
1331 for (const_iterator Iter = begin();
1332 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001333 if (isOpenMPLocal(VD, Iter)) {
1334 DVar.RefExpr =
1335 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1336 D->getLocation());
1337 DVar.CKind = OMPC_threadprivate;
1338 return DVar;
1339 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001340 }
Richard Smith375dec52019-05-30 23:21:14 +00001341 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001342 auto DSAIter = IterTarget->SharingMap.find(D);
1343 if (DSAIter != IterTarget->SharingMap.end() &&
1344 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1345 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1346 DVar.CKind = OMPC_threadprivate;
1347 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001348 }
Richard Smith375dec52019-05-30 23:21:14 +00001349 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001350 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001351 D, std::distance(ParentIterTarget, End),
1352 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001353 DVar.RefExpr =
1354 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1355 IterTarget->ConstructLoc);
1356 DVar.CKind = OMPC_threadprivate;
1357 return DVar;
1358 }
1359 }
1360 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001361 }
1362
Alexey Bataev4b465392017-04-26 15:06:24 +00001363 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001364 // Not in OpenMP execution region and top scope was already checked.
1365 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001366
Alexey Bataev758e55e2013-09-06 18:03:48 +00001367 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001368 // in a Construct, C/C++, predetermined, p.4]
1369 // Static data members are shared.
1370 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1371 // in a Construct, C/C++, predetermined, p.7]
1372 // Variables with static storage duration that are declared in a scope
1373 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001374 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001375 // Check for explicitly specified attributes.
1376 const_iterator I = begin();
1377 const_iterator EndI = end();
1378 if (FromParent && I != EndI)
1379 ++I;
1380 auto It = I->SharingMap.find(D);
1381 if (It != I->SharingMap.end()) {
1382 const DSAInfo &Data = It->getSecond();
1383 DVar.RefExpr = Data.RefExpr.getPointer();
1384 DVar.PrivateCopy = Data.PrivateCopy;
1385 DVar.CKind = Data.Attributes;
1386 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1387 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001388 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001389 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001390
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001391 DVar.CKind = OMPC_shared;
1392 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001393 }
1394
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001395 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001396 // The predetermined shared attribute for const-qualified types having no
1397 // mutable members was removed after OpenMP 3.1.
1398 if (SemaRef.LangOpts.OpenMP <= 31) {
1399 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1400 // in a Construct, C/C++, predetermined, p.6]
1401 // Variables with const qualified type having no mutable member are
1402 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001403 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001404 // Variables with const-qualified type having no mutable member may be
1405 // listed in a firstprivate clause, even if they are static data members.
1406 DSAVarData DVarTemp = hasInnermostDSA(
1407 D,
1408 [](OpenMPClauseKind C) {
1409 return C == OMPC_firstprivate || C == OMPC_shared;
1410 },
1411 MatchesAlways, FromParent);
1412 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1413 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001414
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001415 DVar.CKind = OMPC_shared;
1416 return DVar;
1417 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001418 }
1419
Alexey Bataev758e55e2013-09-06 18:03:48 +00001420 // Explicitly specified attributes and local variables with predetermined
1421 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001422 const_iterator I = begin();
1423 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001424 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001425 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001426 auto It = I->SharingMap.find(D);
1427 if (It != I->SharingMap.end()) {
1428 const DSAInfo &Data = It->getSecond();
1429 DVar.RefExpr = Data.RefExpr.getPointer();
1430 DVar.PrivateCopy = Data.PrivateCopy;
1431 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001432 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001433 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001434 }
1435
1436 return DVar;
1437}
1438
Alexey Bataeve3727102018-04-18 15:57:46 +00001439const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1440 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001441 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001442 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001443 return getDSA(I, D);
1444 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001445 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001446 const_iterator StartI = begin();
1447 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001448 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001449 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001450 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001451}
1452
Alexey Bataeve3727102018-04-18 15:57:46 +00001453const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001454DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001455 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1456 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001457 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001458 if (isStackEmpty())
1459 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001460 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001461 const_iterator I = begin();
1462 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001463 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001464 ++I;
1465 for (; I != EndI; ++I) {
1466 if (!DPred(I->Directive) &&
1467 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001468 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001469 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001470 DSAVarData DVar = getDSA(NewI, D);
1471 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001472 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001473 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001474 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001475}
1476
Alexey Bataeve3727102018-04-18 15:57:46 +00001477const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001478 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1479 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001480 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001481 if (isStackEmpty())
1482 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001483 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001484 const_iterator StartI = begin();
1485 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001486 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001487 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001488 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001489 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001490 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001491 DSAVarData DVar = getDSA(NewI, D);
1492 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001493}
1494
Alexey Bataevaac108a2015-06-23 04:51:00 +00001495bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001496 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1497 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001498 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001499 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001500 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001501 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1502 auto I = StackElem.SharingMap.find(D);
1503 if (I != StackElem.SharingMap.end() &&
1504 I->getSecond().RefExpr.getPointer() &&
1505 CPred(I->getSecond().Attributes) &&
1506 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001507 return true;
1508 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001509 auto LI = StackElem.LCVMap.find(D);
1510 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001511 return CPred(OMPC_private);
1512 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001513}
1514
Samuel Antao4be30e92015-10-02 17:14:03 +00001515bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001516 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1517 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001518 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001519 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001520 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1521 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001522}
1523
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001524bool DSAStackTy::hasDirective(
1525 const llvm::function_ref<bool(OpenMPDirectiveKind,
1526 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001527 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001528 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001529 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001530 size_t Skip = FromParent ? 2 : 1;
1531 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1532 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001533 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1534 return true;
1535 }
1536 return false;
1537}
1538
Alexey Bataev758e55e2013-09-06 18:03:48 +00001539void Sema::InitDataSharingAttributesStack() {
1540 VarDataSharingAttributesStack = new DSAStackTy(*this);
1541}
1542
1543#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1544
Alexey Bataev4b465392017-04-26 15:06:24 +00001545void Sema::pushOpenMPFunctionRegion() {
1546 DSAStack->pushFunction();
1547}
1548
1549void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1550 DSAStack->popFunction(OldFSI);
1551}
1552
Alexey Bataevc416e642019-02-08 18:02:25 +00001553static bool isOpenMPDeviceDelayedContext(Sema &S) {
1554 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1555 "Expected OpenMP device compilation.");
1556 return !S.isInOpenMPTargetExecutionDirective() &&
1557 !S.isInOpenMPDeclareTargetContext();
1558}
1559
Alexey Bataev729e2422019-08-23 16:11:14 +00001560namespace {
1561/// Status of the function emission on the host/device.
1562enum class FunctionEmissionStatus {
1563 Emitted,
1564 Discarded,
1565 Unknown,
1566};
1567} // anonymous namespace
1568
Alexey Bataevc416e642019-02-08 18:02:25 +00001569Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1570 unsigned DiagID) {
1571 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1572 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001573 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001574 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1575 switch (FES) {
1576 case FunctionEmissionStatus::Emitted:
1577 Kind = DeviceDiagBuilder::K_Immediate;
1578 break;
1579 case FunctionEmissionStatus::Unknown:
1580 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1581 : DeviceDiagBuilder::K_Immediate;
1582 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001583 case FunctionEmissionStatus::TemplateDiscarded:
1584 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001585 Kind = DeviceDiagBuilder::K_Nop;
1586 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001587 case FunctionEmissionStatus::CUDADiscarded:
1588 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1589 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001590 }
1591
1592 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1593}
1594
Alexey Bataev729e2422019-08-23 16:11:14 +00001595Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1596 unsigned DiagID) {
1597 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1598 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001599 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001600 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1601 switch (FES) {
1602 case FunctionEmissionStatus::Emitted:
1603 Kind = DeviceDiagBuilder::K_Immediate;
1604 break;
1605 case FunctionEmissionStatus::Unknown:
1606 Kind = DeviceDiagBuilder::K_Deferred;
1607 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001608 case FunctionEmissionStatus::TemplateDiscarded:
1609 case FunctionEmissionStatus::OMPDiscarded:
1610 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001611 Kind = DeviceDiagBuilder::K_Nop;
1612 break;
1613 }
1614
1615 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001616}
1617
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001618void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1619 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001620 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1621 "Expected OpenMP device compilation.");
1622 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001623 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001624 FunctionDecl *Caller = getCurFunctionDecl();
1625
Alexey Bataev729e2422019-08-23 16:11:14 +00001626 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001627 if (Caller) {
1628 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1629 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1630 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1631 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1632 "CUDADiscarded unexpected in OpenMP device function check");
1633 if ((CallerS == FunctionEmissionStatus::Emitted ||
1634 (!isOpenMPDeviceDelayedContext(*this) &&
1635 CallerS == FunctionEmissionStatus::Unknown)) &&
1636 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1637 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1638 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1639 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1640 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1641 diag::note_omp_marked_device_type_here)
1642 << HostDevTy;
1643 return;
1644 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001645 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001646 // If the caller is known-emitted, mark the callee as known-emitted.
1647 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001648 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1649 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001650 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001651 markKnownEmitted(*this, Caller, Callee, Loc,
1652 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001653 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001654 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001655 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001656 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001657 else if (Caller)
1658 DeviceCallGraph[Caller].insert({Callee, Loc});
1659}
1660
Alexey Bataev729e2422019-08-23 16:11:14 +00001661void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1662 bool CheckCaller) {
1663 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1664 "Expected OpenMP host compilation.");
1665 assert(Callee && "Callee may not be null.");
1666 Callee = Callee->getMostRecentDecl();
1667 FunctionDecl *Caller = getCurFunctionDecl();
1668
1669 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001670 if (Caller) {
1671 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1672 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1673 assert(
1674 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1675 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1676 "CUDADiscarded unexpected in OpenMP host function check");
1677 if (CallerS == FunctionEmissionStatus::Emitted &&
1678 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1679 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1680 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1681 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1682 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1683 diag::note_omp_marked_device_type_here)
1684 << NoHostDevTy;
1685 return;
1686 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001687 }
1688 // If the caller is known-emitted, mark the callee as known-emitted.
1689 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001690 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1691 if ((!CheckCaller && !Caller) ||
1692 (Caller &&
1693 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1694 markKnownEmitted(
1695 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1696 return CheckCaller &&
1697 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1698 });
1699 else if (Caller)
1700 DeviceCallGraph[Caller].insert({Callee, Loc});
1701 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001702}
1703
Alexey Bataev123ad192019-02-27 20:29:45 +00001704void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1705 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1706 "OpenMP device compilation mode is expected.");
1707 QualType Ty = E->getType();
1708 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001709 ((Ty->isFloat128Type() ||
1710 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1711 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001712 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1713 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001714 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1715 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1716 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001717}
1718
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001719bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1720 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001721 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1722
Alexey Bataeve3727102018-04-18 15:57:46 +00001723 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001724 bool IsByRef = true;
1725
1726 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001727 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001728 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001729
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001730 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001731 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001732 // This table summarizes how a given variable should be passed to the device
1733 // given its type and the clauses where it appears. This table is based on
1734 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1735 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1736 //
1737 // =========================================================================
1738 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1739 // | |(tofrom:scalar)| | pvt | | | |
1740 // =========================================================================
1741 // | scl | | | | - | | bycopy|
1742 // | scl | | - | x | - | - | bycopy|
1743 // | scl | | x | - | - | - | null |
1744 // | scl | x | | | - | | byref |
1745 // | scl | x | - | x | - | - | bycopy|
1746 // | scl | x | x | - | - | - | null |
1747 // | scl | | - | - | - | x | byref |
1748 // | scl | x | - | - | - | x | byref |
1749 //
1750 // | agg | n.a. | | | - | | byref |
1751 // | agg | n.a. | - | x | - | - | byref |
1752 // | agg | n.a. | x | - | - | - | null |
1753 // | agg | n.a. | - | - | - | x | byref |
1754 // | agg | n.a. | - | - | - | x[] | byref |
1755 //
1756 // | ptr | n.a. | | | - | | bycopy|
1757 // | ptr | n.a. | - | x | - | - | bycopy|
1758 // | ptr | n.a. | x | - | - | - | null |
1759 // | ptr | n.a. | - | - | - | x | byref |
1760 // | ptr | n.a. | - | - | - | x[] | bycopy|
1761 // | ptr | n.a. | - | - | x | | bycopy|
1762 // | ptr | n.a. | - | - | x | x | bycopy|
1763 // | ptr | n.a. | - | - | x | x[] | bycopy|
1764 // =========================================================================
1765 // Legend:
1766 // scl - scalar
1767 // ptr - pointer
1768 // agg - aggregate
1769 // x - applies
1770 // - - invalid in this combination
1771 // [] - mapped with an array section
1772 // byref - should be mapped by reference
1773 // byval - should be mapped by value
1774 // null - initialize a local variable to null on the device
1775 //
1776 // Observations:
1777 // - All scalar declarations that show up in a map clause have to be passed
1778 // by reference, because they may have been mapped in the enclosing data
1779 // environment.
1780 // - If the scalar value does not fit the size of uintptr, it has to be
1781 // passed by reference, regardless the result in the table above.
1782 // - For pointers mapped by value that have either an implicit map or an
1783 // array section, the runtime library may pass the NULL value to the
1784 // device instead of the value passed to it by the compiler.
1785
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001786 if (Ty->isReferenceType())
1787 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001788
1789 // Locate map clauses and see if the variable being captured is referred to
1790 // in any of those clauses. Here we only care about variables, not fields,
1791 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001792 bool IsVariableAssociatedWithSection = false;
1793
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001794 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001795 D, Level,
1796 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1797 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001798 MapExprComponents,
1799 OpenMPClauseKind WhereFoundClauseKind) {
1800 // Only the map clause information influences how a variable is
1801 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001802 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001803 if (WhereFoundClauseKind != OMPC_map)
1804 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001805
1806 auto EI = MapExprComponents.rbegin();
1807 auto EE = MapExprComponents.rend();
1808
1809 assert(EI != EE && "Invalid map expression!");
1810
1811 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1812 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1813
1814 ++EI;
1815 if (EI == EE)
1816 return false;
1817
1818 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1819 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1820 isa<MemberExpr>(EI->getAssociatedExpression())) {
1821 IsVariableAssociatedWithSection = true;
1822 // There is nothing more we need to know about this variable.
1823 return true;
1824 }
1825
1826 // Keep looking for more map info.
1827 return false;
1828 });
1829
1830 if (IsVariableUsedInMapClause) {
1831 // If variable is identified in a map clause it is always captured by
1832 // reference except if it is a pointer that is dereferenced somehow.
1833 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1834 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001835 // By default, all the data that has a scalar type is mapped by copy
1836 // (except for reduction variables).
1837 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001838 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1839 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001840 !Ty->isScalarType() ||
1841 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1842 DSAStack->hasExplicitDSA(
1843 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001844 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001845 }
1846
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001847 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001848 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001849 ((IsVariableUsedInMapClause &&
1850 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1851 OMPD_target) ||
1852 !DSAStack->hasExplicitDSA(
1853 D,
1854 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1855 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001856 // If the variable is artificial and must be captured by value - try to
1857 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001858 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1859 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001860 }
1861
Samuel Antao86ace552016-04-27 22:40:57 +00001862 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001863 // and alignment, because the runtime library only deals with uintptr types.
1864 // If it does not fit the uintptr size, we need to pass the data by reference
1865 // instead.
1866 if (!IsByRef &&
1867 (Ctx.getTypeSizeInChars(Ty) >
1868 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001869 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001870 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001871 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001872
1873 return IsByRef;
1874}
1875
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001876unsigned Sema::getOpenMPNestingLevel() const {
1877 assert(getLangOpts().OpenMP);
1878 return DSAStack->getNestingLevel();
1879}
1880
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001881bool Sema::isInOpenMPTargetExecutionDirective() const {
1882 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1883 !DSAStack->isClauseParsingMode()) ||
1884 DSAStack->hasDirective(
1885 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1886 SourceLocation) -> bool {
1887 return isOpenMPTargetExecutionDirective(K);
1888 },
1889 false);
1890}
1891
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001892VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1893 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001894 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001895 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001896
Alexey Bataev7c860692019-10-25 16:35:32 -04001897 auto *VD = dyn_cast<VarDecl>(D);
1898 // Do not capture constexpr variables.
1899 if (VD && VD->isConstexpr())
1900 return nullptr;
1901
Richard Smith0621a8f2019-05-31 00:45:10 +00001902 // If we want to determine whether the variable should be captured from the
1903 // perspective of the current capturing scope, and we've already left all the
1904 // capturing scopes of the top directive on the stack, check from the
1905 // perspective of its parent directive (if any) instead.
1906 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1907 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1908
Samuel Antao4be30e92015-10-02 17:14:03 +00001909 // If we are attempting to capture a global variable in a directive with
1910 // 'target' we return true so that this global is also mapped to the device.
1911 //
Richard Smith0621a8f2019-05-31 00:45:10 +00001912 if (VD && !VD->hasLocalStorage() &&
1913 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1914 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001915 // Try to mark variable as declare target if it is used in capturing
1916 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001917 if (LangOpts.OpenMP <= 45 &&
1918 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001919 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001920 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001921 } else if (isInOpenMPTargetExecutionDirective()) {
1922 // If the declaration is enclosed in a 'declare target' directive,
1923 // then it should not be captured.
1924 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001925 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001926 return nullptr;
1927 return VD;
1928 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001929 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001930
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001931 if (CheckScopeInfo) {
1932 bool OpenMPFound = false;
1933 for (unsigned I = StopAt + 1; I > 0; --I) {
1934 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1935 if(!isa<CapturingScopeInfo>(FSI))
1936 return nullptr;
1937 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1938 if (RSI->CapRegionKind == CR_OpenMP) {
1939 OpenMPFound = true;
1940 break;
1941 }
1942 }
1943 if (!OpenMPFound)
1944 return nullptr;
1945 }
1946
Alexey Bataev48977c32015-08-04 08:10:48 +00001947 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1948 (!DSAStack->isClauseParsingMode() ||
1949 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001950 auto &&Info = DSAStack->isLoopControlVariable(D);
1951 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001952 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001953 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001954 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001955 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001956 DSAStackTy::DSAVarData DVarPrivate =
1957 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001958 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001959 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00001960 // Threadprivate variables must not be captured.
1961 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
1962 return nullptr;
1963 // The variable is not private or it is the variable in the directive with
1964 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001965 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1966 [](OpenMPDirectiveKind) { return true; },
1967 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001968 if (DVarPrivate.CKind != OMPC_unknown ||
1969 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001970 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001971 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001972 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001973}
1974
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001975void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1976 unsigned Level) const {
1977 SmallVector<OpenMPDirectiveKind, 4> Regions;
1978 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1979 FunctionScopesIndex -= Regions.size();
1980}
1981
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001982void Sema::startOpenMPLoop() {
1983 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1984 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1985 DSAStack->loopInit();
1986}
1987
Alexey Bataevbef93a92019-10-07 18:54:57 +00001988void Sema::startOpenMPCXXRangeFor() {
1989 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1990 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1991 DSAStack->resetPossibleLoopCounter();
1992 DSAStack->loopStart();
1993 }
1994}
1995
Alexey Bataeve3727102018-04-18 15:57:46 +00001996bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001997 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001998 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1999 if (DSAStack->getAssociatedLoops() > 0 &&
2000 !DSAStack->isLoopStarted()) {
2001 DSAStack->resetPossibleLoopCounter(D);
2002 DSAStack->loopStart();
2003 return true;
2004 }
2005 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2006 DSAStack->isLoopControlVariable(D).first) &&
2007 !DSAStack->hasExplicitDSA(
2008 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2009 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2010 return true;
2011 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002012 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2013 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2014 DSAStack->isForceVarCapturing() &&
2015 !DSAStack->hasExplicitDSA(
2016 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2017 return true;
2018 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002019 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002020 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002021 (DSAStack->isClauseParsingMode() &&
2022 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002023 // Consider taskgroup reduction descriptor variable a private to avoid
2024 // possible capture in the region.
2025 (DSAStack->hasExplicitDirective(
2026 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2027 Level) &&
2028 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002029}
2030
Alexey Bataeve3727102018-04-18 15:57:46 +00002031void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2032 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002033 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2034 D = getCanonicalDecl(D);
2035 OpenMPClauseKind OMPC = OMPC_unknown;
2036 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2037 const unsigned NewLevel = I - 1;
2038 if (DSAStack->hasExplicitDSA(D,
2039 [&OMPC](const OpenMPClauseKind K) {
2040 if (isOpenMPPrivate(K)) {
2041 OMPC = K;
2042 return true;
2043 }
2044 return false;
2045 },
2046 NewLevel))
2047 break;
2048 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2049 D, NewLevel,
2050 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2051 OpenMPClauseKind) { return true; })) {
2052 OMPC = OMPC_map;
2053 break;
2054 }
2055 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2056 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002057 OMPC = OMPC_map;
2058 if (D->getType()->isScalarType() &&
2059 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
2060 DefaultMapAttributes::DMA_tofrom_scalar)
2061 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002062 break;
2063 }
2064 }
2065 if (OMPC != OMPC_unknown)
2066 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2067}
2068
Alexey Bataeve3727102018-04-18 15:57:46 +00002069bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2070 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002071 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2072 // Return true if the current level is no longer enclosed in a target region.
2073
Alexey Bataeve3727102018-04-18 15:57:46 +00002074 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002075 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002076 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2077 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002078}
2079
Alexey Bataeved09d242014-05-28 05:53:51 +00002080void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002081
Alexey Bataev729e2422019-08-23 16:11:14 +00002082void Sema::finalizeOpenMPDelayedAnalysis() {
2083 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2084 // Diagnose implicit declare target functions and their callees.
2085 for (const auto &CallerCallees : DeviceCallGraph) {
2086 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2087 OMPDeclareTargetDeclAttr::getDeviceType(
2088 CallerCallees.getFirst()->getMostRecentDecl());
2089 // Ignore host functions during device analyzis.
2090 if (LangOpts.OpenMPIsDevice && DevTy &&
2091 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2092 continue;
2093 // Ignore nohost functions during host analyzis.
2094 if (!LangOpts.OpenMPIsDevice && DevTy &&
2095 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2096 continue;
2097 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2098 &Callee : CallerCallees.getSecond()) {
2099 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2100 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2101 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2102 if (LangOpts.OpenMPIsDevice && DevTy &&
2103 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2104 // Diagnose host function called during device codegen.
2105 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2106 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2107 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2108 << HostDevTy << 0;
2109 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2110 diag::note_omp_marked_device_type_here)
2111 << HostDevTy;
2112 continue;
2113 }
2114 if (!LangOpts.OpenMPIsDevice && DevTy &&
2115 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2116 // Diagnose nohost function called during host codegen.
2117 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2118 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2119 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2120 << NoHostDevTy << 1;
2121 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2122 diag::note_omp_marked_device_type_here)
2123 << NoHostDevTy;
2124 continue;
2125 }
2126 }
2127 }
2128}
2129
Alexey Bataev758e55e2013-09-06 18:03:48 +00002130void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2131 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002132 Scope *CurScope, SourceLocation Loc) {
2133 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002134 PushExpressionEvaluationContext(
2135 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002136}
2137
Alexey Bataevaac108a2015-06-23 04:51:00 +00002138void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2139 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002140}
2141
Alexey Bataevaac108a2015-06-23 04:51:00 +00002142void Sema::EndOpenMPClause() {
2143 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002144}
2145
Alexey Bataeve106f252019-04-01 14:25:31 +00002146static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2147 ArrayRef<OMPClause *> Clauses);
2148
Alexey Bataev758e55e2013-09-06 18:03:48 +00002149void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002150 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2151 // A variable of class type (or array thereof) that appears in a lastprivate
2152 // clause requires an accessible, unambiguous default constructor for the
2153 // class type, unless the list item is also specified in a firstprivate
2154 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002155 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2156 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002157 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2158 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002159 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002160 if (DE->isValueDependent() || DE->isTypeDependent()) {
2161 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002162 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002163 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002164 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002165 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002166 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002167 const DSAStackTy::DSAVarData DVar =
2168 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002169 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002170 // Generate helper private variable and initialize it with the
2171 // default value. The address of the original variable is replaced
2172 // by the address of the new private variable in CodeGen. This new
2173 // variable is not added to IdResolver, so the code in the OpenMP
2174 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002175 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002176 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002177 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002178 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002179 if (VDPrivate->isInvalidDecl()) {
2180 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002181 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002182 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002183 PrivateCopies.push_back(buildDeclRefExpr(
2184 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002185 } else {
2186 // The variable is also a firstprivate, so initialization sequence
2187 // for private copy is generated already.
2188 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002189 }
2190 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002191 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002192 }
2193 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002194 // Check allocate clauses.
2195 if (!CurContext->isDependentContext())
2196 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002197 }
2198
Alexey Bataev758e55e2013-09-06 18:03:48 +00002199 DSAStack->pop();
2200 DiscardCleanupsInEvaluationContext();
2201 PopExpressionEvaluationContext();
2202}
2203
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002204static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2205 Expr *NumIterations, Sema &SemaRef,
2206 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002207
Alexey Bataeva769e072013-03-22 06:34:35 +00002208namespace {
2209
Alexey Bataeve3727102018-04-18 15:57:46 +00002210class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002211private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002212 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002213
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002214public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002215 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002216 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002217 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002218 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002219 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002220 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2221 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002222 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002223 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002224 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002225
2226 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002227 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002228 }
2229
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002230};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002231
Alexey Bataeve3727102018-04-18 15:57:46 +00002232class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002233private:
2234 Sema &SemaRef;
2235
2236public:
2237 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2238 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2239 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002240 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2241 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002242 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2243 SemaRef.getCurScope());
2244 }
2245 return false;
2246 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002247
2248 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002249 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002250 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002251};
2252
Alexey Bataeved09d242014-05-28 05:53:51 +00002253} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002254
2255ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2256 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002257 const DeclarationNameInfo &Id,
2258 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002259 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2260 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2261
2262 if (Lookup.isAmbiguous())
2263 return ExprError();
2264
2265 VarDecl *VD;
2266 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002267 VarDeclFilterCCC CCC(*this);
2268 if (TypoCorrection Corrected =
2269 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2270 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002271 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002272 PDiag(Lookup.empty()
2273 ? diag::err_undeclared_var_use_suggest
2274 : diag::err_omp_expected_var_arg_suggest)
2275 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002276 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002277 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002278 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2279 : diag::err_omp_expected_var_arg)
2280 << Id.getName();
2281 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002282 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002283 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2284 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2285 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2286 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002287 }
2288 Lookup.suppressDiagnostics();
2289
2290 // OpenMP [2.9.2, Syntax, C/C++]
2291 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002292 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002293 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002294 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002295 bool IsDecl =
2296 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002297 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002298 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2299 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002300 return ExprError();
2301 }
2302
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002303 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002304 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002305 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2306 // A threadprivate directive for file-scope variables must appear outside
2307 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002308 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2309 !getCurLexicalContext()->isTranslationUnit()) {
2310 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002311 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002312 bool IsDecl =
2313 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2314 Diag(VD->getLocation(),
2315 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2316 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002317 return ExprError();
2318 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002319 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2320 // A threadprivate directive for static class member variables must appear
2321 // in the class definition, in the same scope in which the member
2322 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002323 if (CanonicalVD->isStaticDataMember() &&
2324 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2325 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002326 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002327 bool IsDecl =
2328 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2329 Diag(VD->getLocation(),
2330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2331 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002332 return ExprError();
2333 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002334 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2335 // A threadprivate directive for namespace-scope variables must appear
2336 // outside any definition or declaration other than the namespace
2337 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002338 if (CanonicalVD->getDeclContext()->isNamespace() &&
2339 (!getCurLexicalContext()->isFileContext() ||
2340 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2341 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002342 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002343 bool IsDecl =
2344 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2345 Diag(VD->getLocation(),
2346 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2347 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002348 return ExprError();
2349 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002350 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2351 // A threadprivate directive for static block-scope variables must appear
2352 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002353 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002354 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002355 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002356 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002357 bool IsDecl =
2358 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2359 Diag(VD->getLocation(),
2360 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2361 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002362 return ExprError();
2363 }
2364
2365 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2366 // A threadprivate directive must lexically precede all references to any
2367 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002368 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2369 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002370 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002371 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002372 return ExprError();
2373 }
2374
2375 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002376 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2377 SourceLocation(), VD,
2378 /*RefersToEnclosingVariableOrCapture=*/false,
2379 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002380}
2381
Alexey Bataeved09d242014-05-28 05:53:51 +00002382Sema::DeclGroupPtrTy
2383Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2384 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002385 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002386 CurContext->addDecl(D);
2387 return DeclGroupPtrTy::make(DeclGroupRef(D));
2388 }
David Blaikie0403cb12016-01-15 23:43:25 +00002389 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002390}
2391
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002392namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002393class LocalVarRefChecker final
2394 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002395 Sema &SemaRef;
2396
2397public:
2398 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002399 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002400 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002401 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002402 diag::err_omp_local_var_in_threadprivate_init)
2403 << E->getSourceRange();
2404 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2405 << VD << VD->getSourceRange();
2406 return true;
2407 }
2408 }
2409 return false;
2410 }
2411 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002412 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002413 if (Child && Visit(Child))
2414 return true;
2415 }
2416 return false;
2417 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002418 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002419};
2420} // namespace
2421
Alexey Bataeved09d242014-05-28 05:53:51 +00002422OMPThreadPrivateDecl *
2423Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002424 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002425 for (Expr *RefExpr : VarList) {
2426 auto *DE = cast<DeclRefExpr>(RefExpr);
2427 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002428 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002429
Alexey Bataev376b4a42016-02-09 09:41:09 +00002430 // Mark variable as used.
2431 VD->setReferenced();
2432 VD->markUsed(Context);
2433
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002434 QualType QType = VD->getType();
2435 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2436 // It will be analyzed later.
2437 Vars.push_back(DE);
2438 continue;
2439 }
2440
Alexey Bataeva769e072013-03-22 06:34:35 +00002441 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2442 // A threadprivate variable must not have an incomplete type.
2443 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002444 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002445 continue;
2446 }
2447
2448 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2449 // A threadprivate variable must not have a reference type.
2450 if (VD->getType()->isReferenceType()) {
2451 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002452 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2453 bool IsDecl =
2454 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2455 Diag(VD->getLocation(),
2456 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2457 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002458 continue;
2459 }
2460
Samuel Antaof8b50122015-07-13 22:54:53 +00002461 // Check if this is a TLS variable. If TLS is not being supported, produce
2462 // the corresponding diagnostic.
2463 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2464 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2465 getLangOpts().OpenMPUseTLS &&
2466 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002467 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2468 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002469 Diag(ILoc, diag::err_omp_var_thread_local)
2470 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002471 bool IsDecl =
2472 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2473 Diag(VD->getLocation(),
2474 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2475 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002476 continue;
2477 }
2478
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002479 // Check if initial value of threadprivate variable reference variable with
2480 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002481 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002482 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002483 if (Checker.Visit(Init))
2484 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002485 }
2486
Alexey Bataeved09d242014-05-28 05:53:51 +00002487 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002488 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002489 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2490 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002491 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002492 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002493 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002494 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002495 if (!Vars.empty()) {
2496 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2497 Vars);
2498 D->setAccess(AS_public);
2499 }
2500 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002501}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002502
Alexey Bataev27ef9512019-03-20 20:14:22 +00002503static OMPAllocateDeclAttr::AllocatorTypeTy
2504getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2505 if (!Allocator)
2506 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2507 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2508 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002509 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002510 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002511 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002512 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002513 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2514 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2515 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002516 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002517 llvm::FoldingSetNodeID AEId, DAEId;
2518 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2519 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2520 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002521 AllocatorKindRes = AllocatorKind;
2522 break;
2523 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002524 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002525 return AllocatorKindRes;
2526}
2527
Alexey Bataeve106f252019-04-01 14:25:31 +00002528static bool checkPreviousOMPAllocateAttribute(
2529 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2530 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2531 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2532 return false;
2533 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2534 Expr *PrevAllocator = A->getAllocator();
2535 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2536 getAllocatorKind(S, Stack, PrevAllocator);
2537 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2538 if (AllocatorsMatch &&
2539 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2540 Allocator && PrevAllocator) {
2541 const Expr *AE = Allocator->IgnoreParenImpCasts();
2542 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2543 llvm::FoldingSetNodeID AEId, PAEId;
2544 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2545 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2546 AllocatorsMatch = AEId == PAEId;
2547 }
2548 if (!AllocatorsMatch) {
2549 SmallString<256> AllocatorBuffer;
2550 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2551 if (Allocator)
2552 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2553 SmallString<256> PrevAllocatorBuffer;
2554 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2555 if (PrevAllocator)
2556 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2557 S.getPrintingPolicy());
2558
2559 SourceLocation AllocatorLoc =
2560 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2561 SourceRange AllocatorRange =
2562 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2563 SourceLocation PrevAllocatorLoc =
2564 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2565 SourceRange PrevAllocatorRange =
2566 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2567 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2568 << (Allocator ? 1 : 0) << AllocatorStream.str()
2569 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2570 << AllocatorRange;
2571 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2572 << PrevAllocatorRange;
2573 return true;
2574 }
2575 return false;
2576}
2577
2578static void
2579applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2580 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2581 Expr *Allocator, SourceRange SR) {
2582 if (VD->hasAttr<OMPAllocateDeclAttr>())
2583 return;
2584 if (Allocator &&
2585 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2586 Allocator->isInstantiationDependent() ||
2587 Allocator->containsUnexpandedParameterPack()))
2588 return;
2589 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2590 Allocator, SR);
2591 VD->addAttr(A);
2592 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2593 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2594}
2595
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002596Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2597 SourceLocation Loc, ArrayRef<Expr *> VarList,
2598 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2599 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2600 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002601 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002602 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2603 // allocate directives that appear in a target region must specify an
2604 // allocator clause unless a requires directive with the dynamic_allocators
2605 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002606 if (LangOpts.OpenMPIsDevice &&
2607 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002608 targetDiag(Loc, diag::err_expected_allocator_clause);
2609 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002610 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002611 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002612 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2613 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002614 SmallVector<Expr *, 8> Vars;
2615 for (Expr *RefExpr : VarList) {
2616 auto *DE = cast<DeclRefExpr>(RefExpr);
2617 auto *VD = cast<VarDecl>(DE->getDecl());
2618
2619 // Check if this is a TLS variable or global register.
2620 if (VD->getTLSKind() != VarDecl::TLS_None ||
2621 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2622 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2623 !VD->isLocalVarDecl()))
2624 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002625
Alexey Bataev282555a2019-03-19 20:33:44 +00002626 // If the used several times in the allocate directive, the same allocator
2627 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002628 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2629 AllocatorKind, Allocator))
2630 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002631
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002632 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2633 // If a list item has a static storage type, the allocator expression in the
2634 // allocator clause must be a constant expression that evaluates to one of
2635 // the predefined memory allocator values.
2636 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002637 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002638 Diag(Allocator->getExprLoc(),
2639 diag::err_omp_expected_predefined_allocator)
2640 << Allocator->getSourceRange();
2641 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2642 VarDecl::DeclarationOnly;
2643 Diag(VD->getLocation(),
2644 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2645 << VD;
2646 continue;
2647 }
2648 }
2649
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002650 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002651 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2652 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002653 }
2654 if (Vars.empty())
2655 return nullptr;
2656 if (!Owner)
2657 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002658 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002659 D->setAccess(AS_public);
2660 Owner->addDecl(D);
2661 return DeclGroupPtrTy::make(DeclGroupRef(D));
2662}
2663
2664Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002665Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2666 ArrayRef<OMPClause *> ClauseList) {
2667 OMPRequiresDecl *D = nullptr;
2668 if (!CurContext->isFileContext()) {
2669 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2670 } else {
2671 D = CheckOMPRequiresDecl(Loc, ClauseList);
2672 if (D) {
2673 CurContext->addDecl(D);
2674 DSAStack->addRequiresDecl(D);
2675 }
2676 }
2677 return DeclGroupPtrTy::make(DeclGroupRef(D));
2678}
2679
2680OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2681 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002682 /// For target specific clauses, the requires directive cannot be
2683 /// specified after the handling of any of the target regions in the
2684 /// current compilation unit.
2685 ArrayRef<SourceLocation> TargetLocations =
2686 DSAStack->getEncounteredTargetLocs();
2687 if (!TargetLocations.empty()) {
2688 for (const OMPClause *CNew : ClauseList) {
2689 // Check if any of the requires clauses affect target regions.
2690 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2691 isa<OMPUnifiedAddressClause>(CNew) ||
2692 isa<OMPReverseOffloadClause>(CNew) ||
2693 isa<OMPDynamicAllocatorsClause>(CNew)) {
2694 Diag(Loc, diag::err_omp_target_before_requires)
2695 << getOpenMPClauseName(CNew->getClauseKind());
2696 for (SourceLocation TargetLoc : TargetLocations) {
2697 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2698 }
2699 }
2700 }
2701 }
2702
Kelvin Li1408f912018-09-26 04:28:39 +00002703 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2704 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2705 ClauseList);
2706 return nullptr;
2707}
2708
Alexey Bataeve3727102018-04-18 15:57:46 +00002709static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2710 const ValueDecl *D,
2711 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002712 bool IsLoopIterVar = false) {
2713 if (DVar.RefExpr) {
2714 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2715 << getOpenMPClauseName(DVar.CKind);
2716 return;
2717 }
2718 enum {
2719 PDSA_StaticMemberShared,
2720 PDSA_StaticLocalVarShared,
2721 PDSA_LoopIterVarPrivate,
2722 PDSA_LoopIterVarLinear,
2723 PDSA_LoopIterVarLastprivate,
2724 PDSA_ConstVarShared,
2725 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002726 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002727 PDSA_LocalVarPrivate,
2728 PDSA_Implicit
2729 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002730 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002731 auto ReportLoc = D->getLocation();
2732 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002733 if (IsLoopIterVar) {
2734 if (DVar.CKind == OMPC_private)
2735 Reason = PDSA_LoopIterVarPrivate;
2736 else if (DVar.CKind == OMPC_lastprivate)
2737 Reason = PDSA_LoopIterVarLastprivate;
2738 else
2739 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002740 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2741 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002742 Reason = PDSA_TaskVarFirstprivate;
2743 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002744 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002745 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002746 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002747 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002748 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002749 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002750 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002751 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002752 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002753 ReportHint = true;
2754 Reason = PDSA_LocalVarPrivate;
2755 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002756 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002757 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002758 << Reason << ReportHint
2759 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2760 } else if (DVar.ImplicitDSALoc.isValid()) {
2761 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2762 << getOpenMPClauseName(DVar.CKind);
2763 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002764}
2765
Alexey Bataev758e55e2013-09-06 18:03:48 +00002766namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002767class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002768 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002769 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002770 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002771 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002772 CapturedStmt *CS = nullptr;
2773 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2774 llvm::SmallVector<Expr *, 4> ImplicitMap;
2775 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2776 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002777
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002778 void VisitSubCaptures(OMPExecutableDirective *S) {
2779 // Check implicitly captured variables.
2780 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2781 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002782 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002783 // Try to capture inner this->member references to generate correct mappings
2784 // and diagnostics.
2785 if (TryCaptureCXXThisMembers ||
2786 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2787 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2788 [](const CapturedStmt::Capture &C) {
2789 return C.capturesThis();
2790 }))) {
2791 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2792 TryCaptureCXXThisMembers = true;
2793 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2794 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2795 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002796 }
2797
Alexey Bataev758e55e2013-09-06 18:03:48 +00002798public:
2799 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002800 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2801 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2802 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002803 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002804 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002805 // Check the datasharing rules for the expressions in the clauses.
2806 if (!CS) {
2807 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2808 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2809 Visit(CED->getInit());
2810 return;
2811 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002812 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2813 // Do not analyze internal variables and do not enclose them into
2814 // implicit clauses.
2815 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002816 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002817 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002818 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002819 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002820
Alexey Bataeve3727102018-04-18 15:57:46 +00002821 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002822 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002823 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002824 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002825
Alexey Bataevafe50572017-10-06 17:00:28 +00002826 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002827 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002828 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002829 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002830 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2831 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002832 return;
2833
Alexey Bataeve3727102018-04-18 15:57:46 +00002834 SourceLocation ELoc = E->getExprLoc();
2835 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002836 // The default(none) clause requires that each variable that is referenced
2837 // in the construct, and does not have a predetermined data-sharing
2838 // attribute, must have its data-sharing attribute explicitly determined
2839 // by being listed in a data-sharing attribute clause.
2840 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002841 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002842 VarsWithInheritedDSA.count(VD) == 0) {
2843 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002844 return;
2845 }
2846
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002847 if (isOpenMPTargetExecutionDirective(DKind) &&
2848 !Stack->isLoopControlVariable(VD).first) {
2849 if (!Stack->checkMappableExprComponentListsForDecl(
2850 VD, /*CurrentRegionOnly=*/true,
2851 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2852 StackComponents,
2853 OpenMPClauseKind) {
2854 // Variable is used if it has been marked as an array, array
2855 // section or the variable iself.
2856 return StackComponents.size() == 1 ||
2857 std::all_of(
2858 std::next(StackComponents.rbegin()),
2859 StackComponents.rend(),
2860 [](const OMPClauseMappableExprCommon::
2861 MappableComponent &MC) {
2862 return MC.getAssociatedDeclaration() ==
2863 nullptr &&
2864 (isa<OMPArraySectionExpr>(
2865 MC.getAssociatedExpression()) ||
2866 isa<ArraySubscriptExpr>(
2867 MC.getAssociatedExpression()));
2868 });
2869 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002870 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002871 // By default lambdas are captured as firstprivates.
2872 if (const auto *RD =
2873 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002874 IsFirstprivate = RD->isLambda();
2875 IsFirstprivate =
2876 IsFirstprivate ||
2877 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002878 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002879 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002880 ImplicitFirstprivate.emplace_back(E);
2881 else
2882 ImplicitMap.emplace_back(E);
2883 return;
2884 }
2885 }
2886
Alexey Bataev758e55e2013-09-06 18:03:48 +00002887 // OpenMP [2.9.3.6, Restrictions, p.2]
2888 // A list item that appears in a reduction clause of the innermost
2889 // enclosing worksharing or parallel construct may not be accessed in an
2890 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002891 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002892 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2893 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002894 return isOpenMPParallelDirective(K) ||
2895 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2896 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002897 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002898 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002899 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002900 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002901 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002902 return;
2903 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002904
2905 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002906 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002907 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002908 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002909 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002910 return;
2911 }
2912
2913 // Store implicitly used globals with declare target link for parent
2914 // target.
2915 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2916 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2917 Stack->addToParentTargetRegionLinkGlobals(E);
2918 return;
2919 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002920 }
2921 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002922 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002923 if (E->isTypeDependent() || E->isValueDependent() ||
2924 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2925 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002926 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002927 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002928 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002929 if (!FD)
2930 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002931 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002932 // Check if the variable has explicit DSA set and stop analysis if it
2933 // so.
2934 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2935 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002936
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002937 if (isOpenMPTargetExecutionDirective(DKind) &&
2938 !Stack->isLoopControlVariable(FD).first &&
2939 !Stack->checkMappableExprComponentListsForDecl(
2940 FD, /*CurrentRegionOnly=*/true,
2941 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2942 StackComponents,
2943 OpenMPClauseKind) {
2944 return isa<CXXThisExpr>(
2945 cast<MemberExpr>(
2946 StackComponents.back().getAssociatedExpression())
2947 ->getBase()
2948 ->IgnoreParens());
2949 })) {
2950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2951 // A bit-field cannot appear in a map clause.
2952 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002953 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002954 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002955
2956 // Check to see if the member expression is referencing a class that
2957 // has already been explicitly mapped
2958 if (Stack->isClassPreviouslyMapped(TE->getType()))
2959 return;
2960
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002961 ImplicitMap.emplace_back(E);
2962 return;
2963 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002964
Alexey Bataeve3727102018-04-18 15:57:46 +00002965 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002966 // OpenMP [2.9.3.6, Restrictions, p.2]
2967 // A list item that appears in a reduction clause of the innermost
2968 // enclosing worksharing or parallel construct may not be accessed in
2969 // an explicit task.
2970 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002971 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2972 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002973 return isOpenMPParallelDirective(K) ||
2974 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2975 },
2976 /*FromParent=*/true);
2977 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2978 ErrorFound = true;
2979 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002980 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002981 return;
2982 }
2983
2984 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002985 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002986 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002987 !Stack->isLoopControlVariable(FD).first) {
2988 // Check if there is a captured expression for the current field in the
2989 // region. Do not mark it as firstprivate unless there is no captured
2990 // expression.
2991 // TODO: try to make it firstprivate.
2992 if (DVar.CKind != OMPC_unknown)
2993 ImplicitFirstprivate.push_back(E);
2994 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002995 return;
2996 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002997 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002998 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002999 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003000 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003001 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003002 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003003 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3004 if (!Stack->checkMappableExprComponentListsForDecl(
3005 VD, /*CurrentRegionOnly=*/true,
3006 [&CurComponents](
3007 OMPClauseMappableExprCommon::MappableExprComponentListRef
3008 StackComponents,
3009 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003010 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003011 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003012 for (const auto &SC : llvm::reverse(StackComponents)) {
3013 // Do both expressions have the same kind?
3014 if (CCI->getAssociatedExpression()->getStmtClass() !=
3015 SC.getAssociatedExpression()->getStmtClass())
3016 if (!(isa<OMPArraySectionExpr>(
3017 SC.getAssociatedExpression()) &&
3018 isa<ArraySubscriptExpr>(
3019 CCI->getAssociatedExpression())))
3020 return false;
3021
Alexey Bataeve3727102018-04-18 15:57:46 +00003022 const Decl *CCD = CCI->getAssociatedDeclaration();
3023 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003024 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3025 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3026 if (SCD != CCD)
3027 return false;
3028 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003029 if (CCI == CCE)
3030 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003031 }
3032 return true;
3033 })) {
3034 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003035 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003036 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003037 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003038 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003039 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003040 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003041 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003042 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003043 // for task|target directives.
3044 // Skip analysis of arguments of implicitly defined map clause for target
3045 // directives.
3046 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3047 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003048 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003049 if (CC)
3050 Visit(CC);
3051 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003052 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003053 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003054 // Check implicitly captured variables.
3055 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003056 }
3057 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003058 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003059 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003060 // Check implicitly captured variables in the task-based directives to
3061 // check if they must be firstprivatized.
3062 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003063 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003064 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003065 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003066
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003067 void visitSubCaptures(CapturedStmt *S) {
3068 for (const CapturedStmt::Capture &Cap : S->captures()) {
3069 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3070 continue;
3071 VarDecl *VD = Cap.getCapturedVar();
3072 // Do not try to map the variable if it or its sub-component was mapped
3073 // already.
3074 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3075 Stack->checkMappableExprComponentListsForDecl(
3076 VD, /*CurrentRegionOnly=*/true,
3077 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3078 OpenMPClauseKind) { return true; }))
3079 continue;
3080 DeclRefExpr *DRE = buildDeclRefExpr(
3081 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3082 Cap.getLocation(), /*RefersToCapture=*/true);
3083 Visit(DRE);
3084 }
3085 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003086 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003087 ArrayRef<Expr *> getImplicitFirstprivate() const {
3088 return ImplicitFirstprivate;
3089 }
3090 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00003091 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003092 return VarsWithInheritedDSA;
3093 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003094
Alexey Bataev7ff55242014-06-19 09:13:45 +00003095 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003096 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3097 // Process declare target link variables for the target directives.
3098 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3099 for (DeclRefExpr *E : Stack->getLinkGlobals())
3100 Visit(E);
3101 }
3102 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003103};
Alexey Bataeved09d242014-05-28 05:53:51 +00003104} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003105
Alexey Bataevbae9a792014-06-27 10:37:06 +00003106void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003107 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003108 case OMPD_parallel:
3109 case OMPD_parallel_for:
3110 case OMPD_parallel_for_simd:
3111 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003112 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003113 case OMPD_teams_distribute:
3114 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003115 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003116 QualType KmpInt32PtrTy =
3117 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003118 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003119 std::make_pair(".global_tid.", KmpInt32PtrTy),
3120 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3121 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003122 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003123 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3124 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003125 break;
3126 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003127 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003128 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003129 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003130 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003131 case OMPD_target_teams_distribute:
3132 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003133 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3134 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3135 QualType KmpInt32PtrTy =
3136 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3137 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003138 FunctionProtoType::ExtProtoInfo EPI;
3139 EPI.Variadic = true;
3140 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3141 Sema::CapturedParamNameType Params[] = {
3142 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003143 std::make_pair(".part_id.", KmpInt32PtrTy),
3144 std::make_pair(".privates.", VoidPtrTy),
3145 std::make_pair(
3146 ".copy_fn.",
3147 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003148 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3149 std::make_pair(StringRef(), QualType()) // __context with shared vars
3150 };
3151 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003152 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003153 // Mark this captured region as inlined, because we don't use outlined
3154 // function directly.
3155 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3156 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003157 Context, {}, AttributeCommonInfo::AS_Keyword,
3158 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003159 Sema::CapturedParamNameType ParamsTarget[] = {
3160 std::make_pair(StringRef(), QualType()) // __context with shared vars
3161 };
3162 // Start a captured region for 'target' with no implicit parameters.
3163 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003164 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003165 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003166 std::make_pair(".global_tid.", KmpInt32PtrTy),
3167 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3168 std::make_pair(StringRef(), QualType()) // __context with shared vars
3169 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003170 // Start a captured region for 'teams' or 'parallel'. Both regions have
3171 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003172 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003173 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003174 break;
3175 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003176 case OMPD_target:
3177 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003178 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3179 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3180 QualType KmpInt32PtrTy =
3181 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3182 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003183 FunctionProtoType::ExtProtoInfo EPI;
3184 EPI.Variadic = true;
3185 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3186 Sema::CapturedParamNameType Params[] = {
3187 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003188 std::make_pair(".part_id.", KmpInt32PtrTy),
3189 std::make_pair(".privates.", VoidPtrTy),
3190 std::make_pair(
3191 ".copy_fn.",
3192 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003193 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3194 std::make_pair(StringRef(), QualType()) // __context with shared vars
3195 };
3196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003197 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003198 // Mark this captured region as inlined, because we don't use outlined
3199 // function directly.
3200 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3201 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003202 Context, {}, AttributeCommonInfo::AS_Keyword,
3203 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003204 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003205 std::make_pair(StringRef(), QualType()),
3206 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003207 break;
3208 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003209 case OMPD_simd:
3210 case OMPD_for:
3211 case OMPD_for_simd:
3212 case OMPD_sections:
3213 case OMPD_section:
3214 case OMPD_single:
3215 case OMPD_master:
3216 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003217 case OMPD_taskgroup:
3218 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003219 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003220 case OMPD_ordered:
3221 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003222 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003223 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003224 std::make_pair(StringRef(), QualType()) // __context with shared vars
3225 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003226 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3227 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003228 break;
3229 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003230 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3232 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3233 QualType KmpInt32PtrTy =
3234 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3235 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003236 FunctionProtoType::ExtProtoInfo EPI;
3237 EPI.Variadic = true;
3238 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003239 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003240 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003241 std::make_pair(".part_id.", KmpInt32PtrTy),
3242 std::make_pair(".privates.", VoidPtrTy),
3243 std::make_pair(
3244 ".copy_fn.",
3245 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003246 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003247 std::make_pair(StringRef(), QualType()) // __context with shared vars
3248 };
3249 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3250 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003251 // Mark this captured region as inlined, because we don't use outlined
3252 // function directly.
3253 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3254 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003255 Context, {}, AttributeCommonInfo::AS_Keyword,
3256 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003257 break;
3258 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003259 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003260 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003261 case OMPD_master_taskloop:
3262 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003263 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003264 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3265 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003266 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003267 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3268 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003269 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003270 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3271 .withConst();
3272 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3273 QualType KmpInt32PtrTy =
3274 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3275 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003276 FunctionProtoType::ExtProtoInfo EPI;
3277 EPI.Variadic = true;
3278 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003279 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003280 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003281 std::make_pair(".part_id.", KmpInt32PtrTy),
3282 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003283 std::make_pair(
3284 ".copy_fn.",
3285 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3286 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3287 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003288 std::make_pair(".ub.", KmpUInt64Ty),
3289 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003290 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003291 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003292 std::make_pair(StringRef(), QualType()) // __context with shared vars
3293 };
3294 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3295 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003296 // Mark this captured region as inlined, because we don't use outlined
3297 // function directly.
3298 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3299 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003300 Context, {}, AttributeCommonInfo::AS_Keyword,
3301 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003302 break;
3303 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003304 case OMPD_parallel_master_taskloop:
3305 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003306 QualType KmpInt32Ty =
3307 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3308 .withConst();
3309 QualType KmpUInt64Ty =
3310 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3311 .withConst();
3312 QualType KmpInt64Ty =
3313 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3314 .withConst();
3315 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3316 QualType KmpInt32PtrTy =
3317 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3318 Sema::CapturedParamNameType ParamsParallel[] = {
3319 std::make_pair(".global_tid.", KmpInt32PtrTy),
3320 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3321 std::make_pair(StringRef(), QualType()) // __context with shared vars
3322 };
3323 // Start a captured region for 'parallel'.
3324 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3325 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3326 QualType Args[] = {VoidPtrTy};
3327 FunctionProtoType::ExtProtoInfo EPI;
3328 EPI.Variadic = true;
3329 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3330 Sema::CapturedParamNameType Params[] = {
3331 std::make_pair(".global_tid.", KmpInt32Ty),
3332 std::make_pair(".part_id.", KmpInt32PtrTy),
3333 std::make_pair(".privates.", VoidPtrTy),
3334 std::make_pair(
3335 ".copy_fn.",
3336 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3337 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3338 std::make_pair(".lb.", KmpUInt64Ty),
3339 std::make_pair(".ub.", KmpUInt64Ty),
3340 std::make_pair(".st.", KmpInt64Ty),
3341 std::make_pair(".liter.", KmpInt32Ty),
3342 std::make_pair(".reductions.", VoidPtrTy),
3343 std::make_pair(StringRef(), QualType()) // __context with shared vars
3344 };
3345 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3346 Params, /*OpenMPCaptureLevel=*/2);
3347 // Mark this captured region as inlined, because we don't use outlined
3348 // function directly.
3349 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3350 AlwaysInlineAttr::CreateImplicit(
3351 Context, {}, AttributeCommonInfo::AS_Keyword,
3352 AlwaysInlineAttr::Keyword_forceinline));
3353 break;
3354 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003355 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003356 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003357 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003358 QualType KmpInt32PtrTy =
3359 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3360 Sema::CapturedParamNameType Params[] = {
3361 std::make_pair(".global_tid.", KmpInt32PtrTy),
3362 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003363 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3364 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003365 std::make_pair(StringRef(), QualType()) // __context with shared vars
3366 };
3367 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3368 Params);
3369 break;
3370 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003371 case OMPD_target_teams_distribute_parallel_for:
3372 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003373 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003374 QualType KmpInt32PtrTy =
3375 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003376 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003377
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003378 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003379 FunctionProtoType::ExtProtoInfo EPI;
3380 EPI.Variadic = true;
3381 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3382 Sema::CapturedParamNameType Params[] = {
3383 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003384 std::make_pair(".part_id.", KmpInt32PtrTy),
3385 std::make_pair(".privates.", VoidPtrTy),
3386 std::make_pair(
3387 ".copy_fn.",
3388 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003389 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3390 std::make_pair(StringRef(), QualType()) // __context with shared vars
3391 };
3392 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003393 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003394 // Mark this captured region as inlined, because we don't use outlined
3395 // function directly.
3396 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3397 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003398 Context, {}, AttributeCommonInfo::AS_Keyword,
3399 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003400 Sema::CapturedParamNameType ParamsTarget[] = {
3401 std::make_pair(StringRef(), QualType()) // __context with shared vars
3402 };
3403 // Start a captured region for 'target' with no implicit parameters.
3404 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003405 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003406
3407 Sema::CapturedParamNameType ParamsTeams[] = {
3408 std::make_pair(".global_tid.", KmpInt32PtrTy),
3409 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3410 std::make_pair(StringRef(), QualType()) // __context with shared vars
3411 };
3412 // Start a captured region for 'target' with no implicit parameters.
3413 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003414 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003415
3416 Sema::CapturedParamNameType ParamsParallel[] = {
3417 std::make_pair(".global_tid.", KmpInt32PtrTy),
3418 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003419 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3420 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003421 std::make_pair(StringRef(), QualType()) // __context with shared vars
3422 };
3423 // Start a captured region for 'teams' or 'parallel'. Both regions have
3424 // the same implicit parameters.
3425 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003426 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003427 break;
3428 }
3429
Alexey Bataev46506272017-12-05 17:41:34 +00003430 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003431 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003432 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003433 QualType KmpInt32PtrTy =
3434 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3435
3436 Sema::CapturedParamNameType ParamsTeams[] = {
3437 std::make_pair(".global_tid.", KmpInt32PtrTy),
3438 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3439 std::make_pair(StringRef(), QualType()) // __context with shared vars
3440 };
3441 // Start a captured region for 'target' with no implicit parameters.
3442 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003443 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003444
3445 Sema::CapturedParamNameType ParamsParallel[] = {
3446 std::make_pair(".global_tid.", KmpInt32PtrTy),
3447 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003448 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3449 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003450 std::make_pair(StringRef(), QualType()) // __context with shared vars
3451 };
3452 // Start a captured region for 'teams' or 'parallel'. Both regions have
3453 // the same implicit parameters.
3454 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003455 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003456 break;
3457 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003458 case OMPD_target_update:
3459 case OMPD_target_enter_data:
3460 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003461 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3462 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3463 QualType KmpInt32PtrTy =
3464 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3465 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003466 FunctionProtoType::ExtProtoInfo EPI;
3467 EPI.Variadic = true;
3468 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3469 Sema::CapturedParamNameType Params[] = {
3470 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003471 std::make_pair(".part_id.", KmpInt32PtrTy),
3472 std::make_pair(".privates.", VoidPtrTy),
3473 std::make_pair(
3474 ".copy_fn.",
3475 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003476 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3477 std::make_pair(StringRef(), QualType()) // __context with shared vars
3478 };
3479 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3480 Params);
3481 // Mark this captured region as inlined, because we don't use outlined
3482 // function directly.
3483 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3484 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003485 Context, {}, AttributeCommonInfo::AS_Keyword,
3486 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003487 break;
3488 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003489 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003490 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003491 case OMPD_taskyield:
3492 case OMPD_barrier:
3493 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003494 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003495 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003496 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003497 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003498 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003499 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003500 case OMPD_declare_target:
3501 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003502 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003503 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003504 llvm_unreachable("OpenMP Directive is not allowed");
3505 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003506 llvm_unreachable("Unknown OpenMP directive");
3507 }
3508}
3509
Alexey Bataev0e100032019-10-14 16:44:01 +00003510int Sema::getNumberOfConstructScopes(unsigned Level) const {
3511 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3512}
3513
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003514int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3515 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3516 getOpenMPCaptureRegions(CaptureRegions, DKind);
3517 return CaptureRegions.size();
3518}
3519
Alexey Bataev3392d762016-02-16 11:18:12 +00003520static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003521 Expr *CaptureExpr, bool WithInit,
3522 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003523 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003524 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003525 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003526 QualType Ty = Init->getType();
3527 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003528 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003529 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003530 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003531 Ty = C.getPointerType(Ty);
3532 ExprResult Res =
3533 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3534 if (!Res.isUsable())
3535 return nullptr;
3536 Init = Res.get();
3537 }
Alexey Bataev61205072016-03-02 04:57:40 +00003538 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003539 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003540 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003541 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003542 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003543 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003544 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003545 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003546 return CED;
3547}
3548
Alexey Bataev61205072016-03-02 04:57:40 +00003549static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3550 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003551 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003552 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003553 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003554 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003555 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3556 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003557 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003558 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003559}
3560
Alexey Bataev5a3af132016-03-29 08:58:54 +00003561static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003562 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003563 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003564 OMPCapturedExprDecl *CD = buildCaptureDecl(
3565 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3566 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003567 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3568 CaptureExpr->getExprLoc());
3569 }
3570 ExprResult Res = Ref;
3571 if (!S.getLangOpts().CPlusPlus &&
3572 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003573 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003574 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003575 if (!Res.isUsable())
3576 return ExprError();
3577 }
3578 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003579}
3580
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003581namespace {
3582// OpenMP directives parsed in this section are represented as a
3583// CapturedStatement with an associated statement. If a syntax error
3584// is detected during the parsing of the associated statement, the
3585// compiler must abort processing and close the CapturedStatement.
3586//
3587// Combined directives such as 'target parallel' have more than one
3588// nested CapturedStatements. This RAII ensures that we unwind out
3589// of all the nested CapturedStatements when an error is found.
3590class CaptureRegionUnwinderRAII {
3591private:
3592 Sema &S;
3593 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003594 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003595
3596public:
3597 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3598 OpenMPDirectiveKind DKind)
3599 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3600 ~CaptureRegionUnwinderRAII() {
3601 if (ErrorFound) {
3602 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3603 while (--ThisCaptureLevel >= 0)
3604 S.ActOnCapturedRegionError();
3605 }
3606 }
3607};
3608} // namespace
3609
Alexey Bataevb600ae32019-07-01 17:46:52 +00003610void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3611 // Capture variables captured by reference in lambdas for target-based
3612 // directives.
3613 if (!CurContext->isDependentContext() &&
3614 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3615 isOpenMPTargetDataManagementDirective(
3616 DSAStack->getCurrentDirective()))) {
3617 QualType Type = V->getType();
3618 if (const auto *RD = Type.getCanonicalType()
3619 .getNonReferenceType()
3620 ->getAsCXXRecordDecl()) {
3621 bool SavedForceCaptureByReferenceInTargetExecutable =
3622 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3623 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3624 /*V=*/true);
3625 if (RD->isLambda()) {
3626 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3627 FieldDecl *ThisCapture;
3628 RD->getCaptureFields(Captures, ThisCapture);
3629 for (const LambdaCapture &LC : RD->captures()) {
3630 if (LC.getCaptureKind() == LCK_ByRef) {
3631 VarDecl *VD = LC.getCapturedVar();
3632 DeclContext *VDC = VD->getDeclContext();
3633 if (!VDC->Encloses(CurContext))
3634 continue;
3635 MarkVariableReferenced(LC.getLocation(), VD);
3636 } else if (LC.getCaptureKind() == LCK_This) {
3637 QualType ThisTy = getCurrentThisType();
3638 if (!ThisTy.isNull() &&
3639 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3640 CheckCXXThisCapture(LC.getLocation());
3641 }
3642 }
3643 }
3644 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3645 SavedForceCaptureByReferenceInTargetExecutable);
3646 }
3647 }
3648}
3649
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003650StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3651 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003652 bool ErrorFound = false;
3653 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3654 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003655 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003656 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003657 return StmtError();
3658 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003659
Alexey Bataev2ba67042017-11-28 21:11:44 +00003660 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3661 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003662 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003663 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003664 SmallVector<const OMPLinearClause *, 4> LCs;
3665 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003666 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003667 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003668 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3669 Clause->getClauseKind() == OMPC_in_reduction) {
3670 // Capture taskgroup task_reduction descriptors inside the tasking regions
3671 // with the corresponding in_reduction items.
3672 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003673 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003674 if (E)
3675 MarkDeclarationsReferencedInExpr(E);
3676 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003677 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003678 Clause->getClauseKind() == OMPC_copyprivate ||
3679 (getLangOpts().OpenMPUseTLS &&
3680 getASTContext().getTargetInfo().isTLSSupported() &&
3681 Clause->getClauseKind() == OMPC_copyin)) {
3682 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003683 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003684 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003685 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003686 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003687 }
3688 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003689 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003690 } else if (CaptureRegions.size() > 1 ||
3691 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003692 if (auto *C = OMPClauseWithPreInit::get(Clause))
3693 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003694 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003695 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003696 MarkDeclarationsReferencedInExpr(E);
3697 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003698 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003699 if (Clause->getClauseKind() == OMPC_schedule)
3700 SC = cast<OMPScheduleClause>(Clause);
3701 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003702 OC = cast<OMPOrderedClause>(Clause);
3703 else if (Clause->getClauseKind() == OMPC_linear)
3704 LCs.push_back(cast<OMPLinearClause>(Clause));
3705 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003706 // OpenMP, 2.7.1 Loop Construct, Restrictions
3707 // The nonmonotonic modifier cannot be specified if an ordered clause is
3708 // specified.
3709 if (SC &&
3710 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3711 SC->getSecondScheduleModifier() ==
3712 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3713 OC) {
3714 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3715 ? SC->getFirstScheduleModifierLoc()
3716 : SC->getSecondScheduleModifierLoc(),
3717 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003718 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003719 ErrorFound = true;
3720 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003721 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003722 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003723 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003724 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003725 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003726 ErrorFound = true;
3727 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003728 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3729 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3730 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003731 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003732 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3733 ErrorFound = true;
3734 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003735 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003736 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003737 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003738 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003739 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003740 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003741 // Mark all variables in private list clauses as used in inner region.
3742 // Required for proper codegen of combined directives.
3743 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003744 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003745 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003746 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3747 // Find the particular capture region for the clause if the
3748 // directive is a combined one with multiple capture regions.
3749 // If the directive is not a combined one, the capture region
3750 // associated with the clause is OMPD_unknown and is generated
3751 // only once.
3752 if (CaptureRegion == ThisCaptureRegion ||
3753 CaptureRegion == OMPD_unknown) {
3754 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003755 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003756 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3757 }
3758 }
3759 }
3760 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003761 if (++CompletedRegions == CaptureRegions.size())
3762 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003763 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003764 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003765 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003766}
3767
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003768static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3769 OpenMPDirectiveKind CancelRegion,
3770 SourceLocation StartLoc) {
3771 // CancelRegion is only needed for cancel and cancellation_point.
3772 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3773 return false;
3774
3775 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3776 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3777 return false;
3778
3779 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3780 << getOpenMPDirectiveName(CancelRegion);
3781 return true;
3782}
3783
Alexey Bataeve3727102018-04-18 15:57:46 +00003784static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003785 OpenMPDirectiveKind CurrentRegion,
3786 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003787 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003788 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003789 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003790 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3791 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003792 bool NestingProhibited = false;
3793 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003794 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003795 enum {
3796 NoRecommend,
3797 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003798 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003799 ShouldBeInTargetRegion,
3800 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003801 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003802 if (isOpenMPSimdDirective(ParentRegion) &&
3803 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
3804 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
3805 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003806 // OpenMP [2.16, Nesting of Regions]
3807 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003808 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003809 // An ordered construct with the simd clause is the only OpenMP
3810 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003811 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003812 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3813 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003814 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
3815 // The only OpenMP constructs that can be encountered during execution of
3816 // a simd region are the atomic construct, the loop construct, the simd
3817 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00003818 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3819 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003820 : diag::warn_omp_nesting_simd)
3821 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00003822 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003823 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003824 if (ParentRegion == OMPD_atomic) {
3825 // OpenMP [2.16, Nesting of Regions]
3826 // OpenMP constructs may not be nested inside an atomic region.
3827 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3828 return true;
3829 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003830 if (CurrentRegion == OMPD_section) {
3831 // OpenMP [2.7.2, sections Construct, Restrictions]
3832 // Orphaned section directives are prohibited. That is, the section
3833 // directives must appear within the sections construct and must not be
3834 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003835 if (ParentRegion != OMPD_sections &&
3836 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003837 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3838 << (ParentRegion != OMPD_unknown)
3839 << getOpenMPDirectiveName(ParentRegion);
3840 return true;
3841 }
3842 return false;
3843 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003844 // Allow some constructs (except teams and cancellation constructs) to be
3845 // orphaned (they could be used in functions, called from OpenMP regions
3846 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003847 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003848 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3849 CurrentRegion != OMPD_cancellation_point &&
3850 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003851 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003852 if (CurrentRegion == OMPD_cancellation_point ||
3853 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003854 // OpenMP [2.16, Nesting of Regions]
3855 // A cancellation point construct for which construct-type-clause is
3856 // taskgroup must be nested inside a task construct. A cancellation
3857 // point construct for which construct-type-clause is not taskgroup must
3858 // be closely nested inside an OpenMP construct that matches the type
3859 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003860 // A cancel construct for which construct-type-clause is taskgroup must be
3861 // nested inside a task construct. A cancel construct for which
3862 // construct-type-clause is not taskgroup must be closely nested inside an
3863 // OpenMP construct that matches the type specified in
3864 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003865 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003866 !((CancelRegion == OMPD_parallel &&
3867 (ParentRegion == OMPD_parallel ||
3868 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003869 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003870 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003871 ParentRegion == OMPD_target_parallel_for ||
3872 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003873 ParentRegion == OMPD_teams_distribute_parallel_for ||
3874 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003875 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3876 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003877 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3878 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003879 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003880 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003881 // OpenMP [2.16, Nesting of Regions]
3882 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003883 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003884 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003885 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003886 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3887 // OpenMP [2.16, Nesting of Regions]
3888 // A critical region may not be nested (closely or otherwise) inside a
3889 // critical region with the same name. Note that this restriction is not
3890 // sufficient to prevent deadlock.
3891 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003892 bool DeadLock = Stack->hasDirective(
3893 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3894 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003895 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003896 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3897 PreviousCriticalLoc = Loc;
3898 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003899 }
3900 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003901 },
3902 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003903 if (DeadLock) {
3904 SemaRef.Diag(StartLoc,
3905 diag::err_omp_prohibited_region_critical_same_name)
3906 << CurrentName.getName();
3907 if (PreviousCriticalLoc.isValid())
3908 SemaRef.Diag(PreviousCriticalLoc,
3909 diag::note_omp_previous_critical_region);
3910 return true;
3911 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003912 } else if (CurrentRegion == OMPD_barrier) {
3913 // OpenMP [2.16, Nesting of Regions]
3914 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003915 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003916 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3917 isOpenMPTaskingDirective(ParentRegion) ||
3918 ParentRegion == OMPD_master ||
3919 ParentRegion == OMPD_critical ||
3920 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003921 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003922 !isOpenMPParallelDirective(CurrentRegion) &&
3923 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003924 // OpenMP [2.16, Nesting of Regions]
3925 // A worksharing region may not be closely nested inside a worksharing,
3926 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003927 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3928 isOpenMPTaskingDirective(ParentRegion) ||
3929 ParentRegion == OMPD_master ||
3930 ParentRegion == OMPD_critical ||
3931 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003932 Recommend = ShouldBeInParallelRegion;
3933 } else if (CurrentRegion == OMPD_ordered) {
3934 // OpenMP [2.16, Nesting of Regions]
3935 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003936 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003937 // An ordered region must be closely nested inside a loop region (or
3938 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003939 // OpenMP [2.8.1,simd Construct, Restrictions]
3940 // An ordered construct with the simd clause is the only OpenMP construct
3941 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003942 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003943 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003944 !(isOpenMPSimdDirective(ParentRegion) ||
3945 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003946 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003947 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003948 // OpenMP [2.16, Nesting of Regions]
3949 // If specified, a teams construct must be contained within a target
3950 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00003951 NestingProhibited =
3952 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
3953 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
3954 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00003955 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003956 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003957 }
Kelvin Libf594a52016-12-17 05:48:59 +00003958 if (!NestingProhibited &&
3959 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3960 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3961 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003962 // OpenMP [2.16, Nesting of Regions]
3963 // distribute, parallel, parallel sections, parallel workshare, and the
3964 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3965 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003966 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3967 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003968 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003969 }
David Majnemer9d168222016-08-05 17:44:54 +00003970 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003971 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003972 // OpenMP 4.5 [2.17 Nesting of Regions]
3973 // The region associated with the distribute construct must be strictly
3974 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003975 NestingProhibited =
3976 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003977 Recommend = ShouldBeInTeamsRegion;
3978 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003979 if (!NestingProhibited &&
3980 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3981 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3982 // OpenMP 4.5 [2.17 Nesting of Regions]
3983 // If a target, target update, target data, target enter data, or
3984 // target exit data construct is encountered during execution of a
3985 // target region, the behavior is unspecified.
3986 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003987 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003988 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003989 if (isOpenMPTargetExecutionDirective(K)) {
3990 OffendingRegion = K;
3991 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003992 }
3993 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003994 },
3995 false /* don't skip top directive */);
3996 CloseNesting = false;
3997 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003998 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003999 if (OrphanSeen) {
4000 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4001 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4002 } else {
4003 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4004 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4005 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4006 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004007 return true;
4008 }
4009 }
4010 return false;
4011}
4012
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004013static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4014 ArrayRef<OMPClause *> Clauses,
4015 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4016 bool ErrorFound = false;
4017 unsigned NamedModifiersNumber = 0;
4018 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
4019 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004020 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004021 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004022 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4023 // At most one if clause without a directive-name-modifier can appear on
4024 // the directive.
4025 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4026 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004027 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004028 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4029 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4030 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004031 } else if (CurNM != OMPD_unknown) {
4032 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004033 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004034 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004035 FoundNameModifiers[CurNM] = IC;
4036 if (CurNM == OMPD_unknown)
4037 continue;
4038 // Check if the specified name modifier is allowed for the current
4039 // directive.
4040 // At most one if clause with the particular directive-name-modifier can
4041 // appear on the directive.
4042 bool MatchFound = false;
4043 for (auto NM : AllowedNameModifiers) {
4044 if (CurNM == NM) {
4045 MatchFound = true;
4046 break;
4047 }
4048 }
4049 if (!MatchFound) {
4050 S.Diag(IC->getNameModifierLoc(),
4051 diag::err_omp_wrong_if_directive_name_modifier)
4052 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4053 ErrorFound = true;
4054 }
4055 }
4056 }
4057 // If any if clause on the directive includes a directive-name-modifier then
4058 // all if clauses on the directive must include a directive-name-modifier.
4059 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4060 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004061 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004062 diag::err_omp_no_more_if_clause);
4063 } else {
4064 std::string Values;
4065 std::string Sep(", ");
4066 unsigned AllowedCnt = 0;
4067 unsigned TotalAllowedNum =
4068 AllowedNameModifiers.size() - NamedModifiersNumber;
4069 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4070 ++Cnt) {
4071 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4072 if (!FoundNameModifiers[NM]) {
4073 Values += "'";
4074 Values += getOpenMPDirectiveName(NM);
4075 Values += "'";
4076 if (AllowedCnt + 2 == TotalAllowedNum)
4077 Values += " or ";
4078 else if (AllowedCnt + 1 != TotalAllowedNum)
4079 Values += Sep;
4080 ++AllowedCnt;
4081 }
4082 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004083 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004084 diag::err_omp_unnamed_if_clause)
4085 << (TotalAllowedNum > 1) << Values;
4086 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004087 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004088 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4089 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004090 ErrorFound = true;
4091 }
4092 return ErrorFound;
4093}
4094
Alexey Bataeve106f252019-04-01 14:25:31 +00004095static std::pair<ValueDecl *, bool>
4096getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4097 SourceRange &ERange, bool AllowArraySection = false) {
4098 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4099 RefExpr->containsUnexpandedParameterPack())
4100 return std::make_pair(nullptr, true);
4101
4102 // OpenMP [3.1, C/C++]
4103 // A list item is a variable name.
4104 // OpenMP [2.9.3.3, Restrictions, p.1]
4105 // A variable that is part of another variable (as an array or
4106 // structure element) cannot appear in a private clause.
4107 RefExpr = RefExpr->IgnoreParens();
4108 enum {
4109 NoArrayExpr = -1,
4110 ArraySubscript = 0,
4111 OMPArraySection = 1
4112 } IsArrayExpr = NoArrayExpr;
4113 if (AllowArraySection) {
4114 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4115 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4116 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4117 Base = TempASE->getBase()->IgnoreParenImpCasts();
4118 RefExpr = Base;
4119 IsArrayExpr = ArraySubscript;
4120 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4121 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4122 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4123 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4124 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4125 Base = TempASE->getBase()->IgnoreParenImpCasts();
4126 RefExpr = Base;
4127 IsArrayExpr = OMPArraySection;
4128 }
4129 }
4130 ELoc = RefExpr->getExprLoc();
4131 ERange = RefExpr->getSourceRange();
4132 RefExpr = RefExpr->IgnoreParenImpCasts();
4133 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4134 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4135 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4136 (S.getCurrentThisType().isNull() || !ME ||
4137 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4138 !isa<FieldDecl>(ME->getMemberDecl()))) {
4139 if (IsArrayExpr != NoArrayExpr) {
4140 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4141 << ERange;
4142 } else {
4143 S.Diag(ELoc,
4144 AllowArraySection
4145 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4146 : diag::err_omp_expected_var_name_member_expr)
4147 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4148 }
4149 return std::make_pair(nullptr, false);
4150 }
4151 return std::make_pair(
4152 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4153}
4154
4155static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004156 ArrayRef<OMPClause *> Clauses) {
4157 assert(!S.CurContext->isDependentContext() &&
4158 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004159 auto AllocateRange =
4160 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004161 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4162 DeclToCopy;
4163 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4164 return isOpenMPPrivate(C->getClauseKind());
4165 });
4166 for (OMPClause *Cl : PrivateRange) {
4167 MutableArrayRef<Expr *>::iterator I, It, Et;
4168 if (Cl->getClauseKind() == OMPC_private) {
4169 auto *PC = cast<OMPPrivateClause>(Cl);
4170 I = PC->private_copies().begin();
4171 It = PC->varlist_begin();
4172 Et = PC->varlist_end();
4173 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4174 auto *PC = cast<OMPFirstprivateClause>(Cl);
4175 I = PC->private_copies().begin();
4176 It = PC->varlist_begin();
4177 Et = PC->varlist_end();
4178 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4179 auto *PC = cast<OMPLastprivateClause>(Cl);
4180 I = PC->private_copies().begin();
4181 It = PC->varlist_begin();
4182 Et = PC->varlist_end();
4183 } else if (Cl->getClauseKind() == OMPC_linear) {
4184 auto *PC = cast<OMPLinearClause>(Cl);
4185 I = PC->privates().begin();
4186 It = PC->varlist_begin();
4187 Et = PC->varlist_end();
4188 } else if (Cl->getClauseKind() == OMPC_reduction) {
4189 auto *PC = cast<OMPReductionClause>(Cl);
4190 I = PC->privates().begin();
4191 It = PC->varlist_begin();
4192 Et = PC->varlist_end();
4193 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4194 auto *PC = cast<OMPTaskReductionClause>(Cl);
4195 I = PC->privates().begin();
4196 It = PC->varlist_begin();
4197 Et = PC->varlist_end();
4198 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4199 auto *PC = cast<OMPInReductionClause>(Cl);
4200 I = PC->privates().begin();
4201 It = PC->varlist_begin();
4202 Et = PC->varlist_end();
4203 } else {
4204 llvm_unreachable("Expected private clause.");
4205 }
4206 for (Expr *E : llvm::make_range(It, Et)) {
4207 if (!*I) {
4208 ++I;
4209 continue;
4210 }
4211 SourceLocation ELoc;
4212 SourceRange ERange;
4213 Expr *SimpleRefExpr = E;
4214 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4215 /*AllowArraySection=*/true);
4216 DeclToCopy.try_emplace(Res.first,
4217 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4218 ++I;
4219 }
4220 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004221 for (OMPClause *C : AllocateRange) {
4222 auto *AC = cast<OMPAllocateClause>(C);
4223 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4224 getAllocatorKind(S, Stack, AC->getAllocator());
4225 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4226 // For task, taskloop or target directives, allocation requests to memory
4227 // allocators with the trait access set to thread result in unspecified
4228 // behavior.
4229 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4230 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4231 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4232 S.Diag(AC->getAllocator()->getExprLoc(),
4233 diag::warn_omp_allocate_thread_on_task_target_directive)
4234 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004235 }
4236 for (Expr *E : AC->varlists()) {
4237 SourceLocation ELoc;
4238 SourceRange ERange;
4239 Expr *SimpleRefExpr = E;
4240 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4241 ValueDecl *VD = Res.first;
4242 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4243 if (!isOpenMPPrivate(Data.CKind)) {
4244 S.Diag(E->getExprLoc(),
4245 diag::err_omp_expected_private_copy_for_allocate);
4246 continue;
4247 }
4248 VarDecl *PrivateVD = DeclToCopy[VD];
4249 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4250 AllocatorKind, AC->getAllocator()))
4251 continue;
4252 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4253 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004254 }
4255 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004256}
4257
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004258StmtResult Sema::ActOnOpenMPExecutableDirective(
4259 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4260 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4261 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004262 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004263 // First check CancelRegion which is then used in checkNestingOfRegions.
4264 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4265 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004266 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004267 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004268
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004269 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004270 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004271 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004272 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004273 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004274 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4275
4276 // Check default data sharing attributes for referenced variables.
4277 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004278 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4279 Stmt *S = AStmt;
4280 while (--ThisCaptureLevel >= 0)
4281 S = cast<CapturedStmt>(S)->getCapturedStmt();
4282 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004283 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4284 !isOpenMPTaskingDirective(Kind)) {
4285 // Visit subcaptures to generate implicit clauses for captured vars.
4286 auto *CS = cast<CapturedStmt>(AStmt);
4287 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4288 getOpenMPCaptureRegions(CaptureRegions, Kind);
4289 // Ignore outer tasking regions for target directives.
4290 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4291 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4292 DSAChecker.visitSubCaptures(CS);
4293 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004294 if (DSAChecker.isErrorFound())
4295 return StmtError();
4296 // Generate list of implicitly defined firstprivate variables.
4297 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004298
Alexey Bataev88202be2017-07-27 13:20:36 +00004299 SmallVector<Expr *, 4> ImplicitFirstprivates(
4300 DSAChecker.getImplicitFirstprivate().begin(),
4301 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004302 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4303 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00004304 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004305 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004306 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004307 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004308 if (E)
4309 ImplicitFirstprivates.emplace_back(E);
4310 }
4311 }
4312 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004313 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004314 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4315 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004316 ClausesWithImplicit.push_back(Implicit);
4317 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004318 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004319 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004320 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004321 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004322 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004323 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004324 CXXScopeSpec MapperIdScopeSpec;
4325 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004326 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004327 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4328 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4329 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004330 ClausesWithImplicit.emplace_back(Implicit);
4331 ErrorFound |=
4332 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004333 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004334 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004335 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004336 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004337 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004338
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004339 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004340 switch (Kind) {
4341 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004342 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4343 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004344 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004345 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004346 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004347 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4348 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004349 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004350 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004351 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4352 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004353 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004354 case OMPD_for_simd:
4355 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4356 EndLoc, VarsWithInheritedDSA);
4357 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004358 case OMPD_sections:
4359 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4360 EndLoc);
4361 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004362 case OMPD_section:
4363 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004364 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004365 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4366 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004367 case OMPD_single:
4368 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4369 EndLoc);
4370 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004371 case OMPD_master:
4372 assert(ClausesWithImplicit.empty() &&
4373 "No clauses are allowed for 'omp master' directive");
4374 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4375 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004376 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004377 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4378 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004379 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004380 case OMPD_parallel_for:
4381 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4382 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004383 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004384 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004385 case OMPD_parallel_for_simd:
4386 Res = ActOnOpenMPParallelForSimdDirective(
4387 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004388 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004389 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004390 case OMPD_parallel_sections:
4391 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4392 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004393 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004394 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004395 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004396 Res =
4397 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004398 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004399 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004400 case OMPD_taskyield:
4401 assert(ClausesWithImplicit.empty() &&
4402 "No clauses are allowed for 'omp taskyield' directive");
4403 assert(AStmt == nullptr &&
4404 "No associated statement allowed for 'omp taskyield' directive");
4405 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4406 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004407 case OMPD_barrier:
4408 assert(ClausesWithImplicit.empty() &&
4409 "No clauses are allowed for 'omp barrier' directive");
4410 assert(AStmt == nullptr &&
4411 "No associated statement allowed for 'omp barrier' directive");
4412 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4413 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004414 case OMPD_taskwait:
4415 assert(ClausesWithImplicit.empty() &&
4416 "No clauses are allowed for 'omp taskwait' directive");
4417 assert(AStmt == nullptr &&
4418 "No associated statement allowed for 'omp taskwait' directive");
4419 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4420 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004421 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004422 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4423 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004424 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004425 case OMPD_flush:
4426 assert(AStmt == nullptr &&
4427 "No associated statement allowed for 'omp flush' directive");
4428 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4429 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004430 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004431 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4432 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004433 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004434 case OMPD_atomic:
4435 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4436 EndLoc);
4437 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004438 case OMPD_teams:
4439 Res =
4440 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4441 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004442 case OMPD_target:
4443 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4444 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004445 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004446 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004447 case OMPD_target_parallel:
4448 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4449 StartLoc, EndLoc);
4450 AllowedNameModifiers.push_back(OMPD_target);
4451 AllowedNameModifiers.push_back(OMPD_parallel);
4452 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004453 case OMPD_target_parallel_for:
4454 Res = ActOnOpenMPTargetParallelForDirective(
4455 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4456 AllowedNameModifiers.push_back(OMPD_target);
4457 AllowedNameModifiers.push_back(OMPD_parallel);
4458 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004459 case OMPD_cancellation_point:
4460 assert(ClausesWithImplicit.empty() &&
4461 "No clauses are allowed for 'omp cancellation point' directive");
4462 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4463 "cancellation point' directive");
4464 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4465 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004466 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004467 assert(AStmt == nullptr &&
4468 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004469 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4470 CancelRegion);
4471 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004472 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004473 case OMPD_target_data:
4474 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4475 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004476 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004477 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004478 case OMPD_target_enter_data:
4479 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004480 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004481 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4482 break;
Samuel Antao72590762016-01-19 20:04:50 +00004483 case OMPD_target_exit_data:
4484 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004485 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004486 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4487 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004488 case OMPD_taskloop:
4489 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4490 EndLoc, VarsWithInheritedDSA);
4491 AllowedNameModifiers.push_back(OMPD_taskloop);
4492 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004493 case OMPD_taskloop_simd:
4494 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4495 EndLoc, VarsWithInheritedDSA);
4496 AllowedNameModifiers.push_back(OMPD_taskloop);
4497 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004498 case OMPD_master_taskloop:
4499 Res = ActOnOpenMPMasterTaskLoopDirective(
4500 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4501 AllowedNameModifiers.push_back(OMPD_taskloop);
4502 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004503 case OMPD_master_taskloop_simd:
4504 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4505 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4506 AllowedNameModifiers.push_back(OMPD_taskloop);
4507 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004508 case OMPD_parallel_master_taskloop:
4509 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4510 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4511 AllowedNameModifiers.push_back(OMPD_taskloop);
4512 AllowedNameModifiers.push_back(OMPD_parallel);
4513 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004514 case OMPD_parallel_master_taskloop_simd:
4515 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4516 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4517 AllowedNameModifiers.push_back(OMPD_taskloop);
4518 AllowedNameModifiers.push_back(OMPD_parallel);
4519 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004520 case OMPD_distribute:
4521 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4522 EndLoc, VarsWithInheritedDSA);
4523 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004524 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004525 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4526 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004527 AllowedNameModifiers.push_back(OMPD_target_update);
4528 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004529 case OMPD_distribute_parallel_for:
4530 Res = ActOnOpenMPDistributeParallelForDirective(
4531 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4532 AllowedNameModifiers.push_back(OMPD_parallel);
4533 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004534 case OMPD_distribute_parallel_for_simd:
4535 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4536 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4537 AllowedNameModifiers.push_back(OMPD_parallel);
4538 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004539 case OMPD_distribute_simd:
4540 Res = ActOnOpenMPDistributeSimdDirective(
4541 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4542 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004543 case OMPD_target_parallel_for_simd:
4544 Res = ActOnOpenMPTargetParallelForSimdDirective(
4545 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4546 AllowedNameModifiers.push_back(OMPD_target);
4547 AllowedNameModifiers.push_back(OMPD_parallel);
4548 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004549 case OMPD_target_simd:
4550 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4551 EndLoc, VarsWithInheritedDSA);
4552 AllowedNameModifiers.push_back(OMPD_target);
4553 break;
Kelvin Li02532872016-08-05 14:37:37 +00004554 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004555 Res = ActOnOpenMPTeamsDistributeDirective(
4556 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004557 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004558 case OMPD_teams_distribute_simd:
4559 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4560 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4561 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004562 case OMPD_teams_distribute_parallel_for_simd:
4563 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4564 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4565 AllowedNameModifiers.push_back(OMPD_parallel);
4566 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004567 case OMPD_teams_distribute_parallel_for:
4568 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4569 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4570 AllowedNameModifiers.push_back(OMPD_parallel);
4571 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004572 case OMPD_target_teams:
4573 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4574 EndLoc);
4575 AllowedNameModifiers.push_back(OMPD_target);
4576 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004577 case OMPD_target_teams_distribute:
4578 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4579 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4580 AllowedNameModifiers.push_back(OMPD_target);
4581 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004582 case OMPD_target_teams_distribute_parallel_for:
4583 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4584 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4585 AllowedNameModifiers.push_back(OMPD_target);
4586 AllowedNameModifiers.push_back(OMPD_parallel);
4587 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004588 case OMPD_target_teams_distribute_parallel_for_simd:
4589 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4590 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4591 AllowedNameModifiers.push_back(OMPD_target);
4592 AllowedNameModifiers.push_back(OMPD_parallel);
4593 break;
Kelvin Lida681182017-01-10 18:08:18 +00004594 case OMPD_target_teams_distribute_simd:
4595 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4596 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4597 AllowedNameModifiers.push_back(OMPD_target);
4598 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004599 case OMPD_declare_target:
4600 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004601 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004602 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004603 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004604 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004605 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004606 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004607 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004608 llvm_unreachable("OpenMP Directive is not allowed");
4609 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004610 llvm_unreachable("Unknown OpenMP directive");
4611 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004612
Roman Lebedevb5700602019-03-20 16:32:36 +00004613 ErrorFound = Res.isInvalid() || ErrorFound;
4614
Alexey Bataev412254a2019-05-09 18:44:53 +00004615 // Check variables in the clauses if default(none) was specified.
4616 if (DSAStack->getDefaultDSA() == DSA_none) {
4617 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4618 for (OMPClause *C : Clauses) {
4619 switch (C->getClauseKind()) {
4620 case OMPC_num_threads:
4621 case OMPC_dist_schedule:
4622 // Do not analyse if no parent teams directive.
4623 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4624 break;
4625 continue;
4626 case OMPC_if:
4627 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4628 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4629 break;
4630 continue;
4631 case OMPC_schedule:
4632 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004633 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004634 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004635 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004636 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004637 // Do not analyze if no parent parallel directive.
4638 if (isOpenMPParallelDirective(DSAStack->getCurrentDirective()))
4639 break;
4640 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004641 case OMPC_ordered:
4642 case OMPC_device:
4643 case OMPC_num_teams:
4644 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004645 case OMPC_hint:
4646 case OMPC_collapse:
4647 case OMPC_safelen:
4648 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004649 case OMPC_default:
4650 case OMPC_proc_bind:
4651 case OMPC_private:
4652 case OMPC_firstprivate:
4653 case OMPC_lastprivate:
4654 case OMPC_shared:
4655 case OMPC_reduction:
4656 case OMPC_task_reduction:
4657 case OMPC_in_reduction:
4658 case OMPC_linear:
4659 case OMPC_aligned:
4660 case OMPC_copyin:
4661 case OMPC_copyprivate:
4662 case OMPC_nowait:
4663 case OMPC_untied:
4664 case OMPC_mergeable:
4665 case OMPC_allocate:
4666 case OMPC_read:
4667 case OMPC_write:
4668 case OMPC_update:
4669 case OMPC_capture:
4670 case OMPC_seq_cst:
4671 case OMPC_depend:
4672 case OMPC_threads:
4673 case OMPC_simd:
4674 case OMPC_map:
4675 case OMPC_nogroup:
4676 case OMPC_defaultmap:
4677 case OMPC_to:
4678 case OMPC_from:
4679 case OMPC_use_device_ptr:
4680 case OMPC_is_device_ptr:
4681 continue;
4682 case OMPC_allocator:
4683 case OMPC_flush:
4684 case OMPC_threadprivate:
4685 case OMPC_uniform:
4686 case OMPC_unknown:
4687 case OMPC_unified_address:
4688 case OMPC_unified_shared_memory:
4689 case OMPC_reverse_offload:
4690 case OMPC_dynamic_allocators:
4691 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004692 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004693 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004694 llvm_unreachable("Unexpected clause");
4695 }
4696 for (Stmt *CC : C->children()) {
4697 if (CC)
4698 DSAChecker.Visit(CC);
4699 }
4700 }
4701 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4702 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4703 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004704 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004705 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4706 continue;
4707 ErrorFound = true;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004708 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4709 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004710 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004711 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004712
4713 if (!AllowedNameModifiers.empty())
4714 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4715 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004716
Alexey Bataeved09d242014-05-28 05:53:51 +00004717 if (ErrorFound)
4718 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004719
4720 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4721 Res.getAs<OMPExecutableDirective>()
4722 ->getStructuredBlock()
4723 ->setIsOMPStructuredBlock(true);
4724 }
4725
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004726 if (!CurContext->isDependentContext() &&
4727 isOpenMPTargetExecutionDirective(Kind) &&
4728 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4729 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4730 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4731 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4732 // Register target to DSA Stack.
4733 DSAStack->addTargetDirLocation(StartLoc);
4734 }
4735
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004736 return Res;
4737}
4738
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004739Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4740 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004741 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004742 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4743 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004744 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004745 assert(Linears.size() == LinModifiers.size());
4746 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004747 if (!DG || DG.get().isNull())
4748 return DeclGroupPtrTy();
4749
Alexey Bataevd158cf62019-09-13 20:18:17 +00004750 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004751 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004752 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4753 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004754 return DG;
4755 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004756 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004757 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4758 ADecl = FTD->getTemplatedDecl();
4759
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004760 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4761 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004762 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004763 return DeclGroupPtrTy();
4764 }
4765
Alexey Bataev2af33e32016-04-07 12:45:37 +00004766 // OpenMP [2.8.2, declare simd construct, Description]
4767 // The parameter of the simdlen clause must be a constant positive integer
4768 // expression.
4769 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004770 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004771 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004772 // OpenMP [2.8.2, declare simd construct, Description]
4773 // The special this pointer can be used as if was one of the arguments to the
4774 // function in any of the linear, aligned, or uniform clauses.
4775 // The uniform clause declares one or more arguments to have an invariant
4776 // value for all concurrent invocations of the function in the execution of a
4777 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004778 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4779 const Expr *UniformedLinearThis = nullptr;
4780 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004781 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004782 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4783 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004784 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4785 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004786 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004787 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004788 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004789 }
4790 if (isa<CXXThisExpr>(E)) {
4791 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004792 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004793 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004794 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4795 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004796 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004797 // OpenMP [2.8.2, declare simd construct, Description]
4798 // The aligned clause declares that the object to which each list item points
4799 // is aligned to the number of bytes expressed in the optional parameter of
4800 // the aligned clause.
4801 // The special this pointer can be used as if was one of the arguments to the
4802 // function in any of the linear, aligned, or uniform clauses.
4803 // The type of list items appearing in the aligned clause must be array,
4804 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004805 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4806 const Expr *AlignedThis = nullptr;
4807 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004808 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004809 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4810 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4811 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004812 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4813 FD->getParamDecl(PVD->getFunctionScopeIndex())
4814 ->getCanonicalDecl() == CanonPVD) {
4815 // OpenMP [2.8.1, simd construct, Restrictions]
4816 // A list-item cannot appear in more than one aligned clause.
4817 if (AlignedArgs.count(CanonPVD) > 0) {
4818 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4819 << 1 << E->getSourceRange();
4820 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4821 diag::note_omp_explicit_dsa)
4822 << getOpenMPClauseName(OMPC_aligned);
4823 continue;
4824 }
4825 AlignedArgs[CanonPVD] = E;
4826 QualType QTy = PVD->getType()
4827 .getNonReferenceType()
4828 .getUnqualifiedType()
4829 .getCanonicalType();
4830 const Type *Ty = QTy.getTypePtrOrNull();
4831 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4832 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4833 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4834 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4835 }
4836 continue;
4837 }
4838 }
4839 if (isa<CXXThisExpr>(E)) {
4840 if (AlignedThis) {
4841 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4842 << 2 << E->getSourceRange();
4843 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4844 << getOpenMPClauseName(OMPC_aligned);
4845 }
4846 AlignedThis = E;
4847 continue;
4848 }
4849 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4850 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4851 }
4852 // The optional parameter of the aligned clause, alignment, must be a constant
4853 // positive integer expression. If no optional parameter is specified,
4854 // implementation-defined default alignments for SIMD instructions on the
4855 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004856 SmallVector<const Expr *, 4> NewAligns;
4857 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004858 ExprResult Align;
4859 if (E)
4860 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4861 NewAligns.push_back(Align.get());
4862 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004863 // OpenMP [2.8.2, declare simd construct, Description]
4864 // The linear clause declares one or more list items to be private to a SIMD
4865 // lane and to have a linear relationship with respect to the iteration space
4866 // of a loop.
4867 // The special this pointer can be used as if was one of the arguments to the
4868 // function in any of the linear, aligned, or uniform clauses.
4869 // When a linear-step expression is specified in a linear clause it must be
4870 // either a constant integer expression or an integer-typed parameter that is
4871 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004872 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004873 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4874 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004875 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004876 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4877 ++MI;
4878 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004879 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4880 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4881 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004882 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4883 FD->getParamDecl(PVD->getFunctionScopeIndex())
4884 ->getCanonicalDecl() == CanonPVD) {
4885 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4886 // A list-item cannot appear in more than one linear clause.
4887 if (LinearArgs.count(CanonPVD) > 0) {
4888 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4889 << getOpenMPClauseName(OMPC_linear)
4890 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4891 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4892 diag::note_omp_explicit_dsa)
4893 << getOpenMPClauseName(OMPC_linear);
4894 continue;
4895 }
4896 // Each argument can appear in at most one uniform or linear clause.
4897 if (UniformedArgs.count(CanonPVD) > 0) {
4898 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4899 << getOpenMPClauseName(OMPC_linear)
4900 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4901 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4902 diag::note_omp_explicit_dsa)
4903 << getOpenMPClauseName(OMPC_uniform);
4904 continue;
4905 }
4906 LinearArgs[CanonPVD] = E;
4907 if (E->isValueDependent() || E->isTypeDependent() ||
4908 E->isInstantiationDependent() ||
4909 E->containsUnexpandedParameterPack())
4910 continue;
4911 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4912 PVD->getOriginalType());
4913 continue;
4914 }
4915 }
4916 if (isa<CXXThisExpr>(E)) {
4917 if (UniformedLinearThis) {
4918 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4919 << getOpenMPClauseName(OMPC_linear)
4920 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4921 << E->getSourceRange();
4922 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4923 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4924 : OMPC_linear);
4925 continue;
4926 }
4927 UniformedLinearThis = E;
4928 if (E->isValueDependent() || E->isTypeDependent() ||
4929 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4930 continue;
4931 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4932 E->getType());
4933 continue;
4934 }
4935 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4936 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4937 }
4938 Expr *Step = nullptr;
4939 Expr *NewStep = nullptr;
4940 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004941 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004942 // Skip the same step expression, it was checked already.
4943 if (Step == E || !E) {
4944 NewSteps.push_back(E ? NewStep : nullptr);
4945 continue;
4946 }
4947 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004948 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4949 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4950 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004951 if (UniformedArgs.count(CanonPVD) == 0) {
4952 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4953 << Step->getSourceRange();
4954 } else if (E->isValueDependent() || E->isTypeDependent() ||
4955 E->isInstantiationDependent() ||
4956 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004957 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004958 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004959 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004960 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4961 << Step->getSourceRange();
4962 }
4963 continue;
4964 }
4965 NewStep = Step;
4966 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4967 !Step->isInstantiationDependent() &&
4968 !Step->containsUnexpandedParameterPack()) {
4969 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4970 .get();
4971 if (NewStep)
4972 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4973 }
4974 NewSteps.push_back(NewStep);
4975 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004976 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4977 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004978 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004979 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4980 const_cast<Expr **>(Linears.data()), Linears.size(),
4981 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4982 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004983 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00004984 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004985}
4986
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004987Optional<std::pair<FunctionDecl *, Expr *>>
4988Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
4989 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004990 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004991 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004992
4993 const int VariantId = 1;
4994 // Must be applied only to single decl.
4995 if (!DG.get().isSingleDecl()) {
4996 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4997 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004998 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004999 }
5000 Decl *ADecl = DG.get().getSingleDecl();
5001 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5002 ADecl = FTD->getTemplatedDecl();
5003
5004 // Decl must be a function.
5005 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5006 if (!FD) {
5007 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5008 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005009 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005010 }
5011
5012 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5013 return FD->hasAttrs() &&
5014 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5015 FD->hasAttr<TargetAttr>());
5016 };
5017 // OpenMP is not compatible with CPU-specific attributes.
5018 if (HasMultiVersionAttributes(FD)) {
5019 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5020 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005021 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005022 }
5023
5024 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005025 if (FD->isUsed(false))
5026 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005027 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005028
5029 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005030 const FunctionDecl *Definition;
5031 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5032 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005033 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5034 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005035
5036 // The VariantRef must point to function.
5037 if (!VariantRef) {
5038 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005039 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005040 }
5041
5042 // Do not check templates, wait until instantiation.
5043 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5044 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005045 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5046 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005047
5048 // Convert VariantRef expression to the type of the original function to
5049 // resolve possible conflicts.
5050 ExprResult VariantRefCast;
5051 if (LangOpts.CPlusPlus) {
5052 QualType FnPtrType;
5053 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5054 if (Method && !Method->isStatic()) {
5055 const Type *ClassType =
5056 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5057 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5058 ExprResult ER;
5059 {
5060 // Build adrr_of unary op to correctly handle type checks for member
5061 // functions.
5062 Sema::TentativeAnalysisScope Trap(*this);
5063 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5064 VariantRef);
5065 }
5066 if (!ER.isUsable()) {
5067 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5068 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005069 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005070 }
5071 VariantRef = ER.get();
5072 } else {
5073 FnPtrType = Context.getPointerType(FD->getType());
5074 }
5075 ImplicitConversionSequence ICS =
5076 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5077 /*SuppressUserConversions=*/false,
5078 /*AllowExplicit=*/false,
5079 /*InOverloadResolution=*/false,
5080 /*CStyle=*/false,
5081 /*AllowObjCWritebackConversion=*/false);
5082 if (ICS.isFailure()) {
5083 Diag(VariantRef->getExprLoc(),
5084 diag::err_omp_declare_variant_incompat_types)
5085 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005086 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005087 }
5088 VariantRefCast = PerformImplicitConversion(
5089 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5090 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005091 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005092 // Drop previously built artificial addr_of unary op for member functions.
5093 if (Method && !Method->isStatic()) {
5094 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5095 if (auto *UO = dyn_cast<UnaryOperator>(
5096 PossibleAddrOfVariantRef->IgnoreImplicit()))
5097 VariantRefCast = UO->getSubExpr();
5098 }
5099 } else {
5100 VariantRefCast = VariantRef;
5101 }
5102
5103 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5104 if (!ER.isUsable() ||
5105 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5106 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5107 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005108 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005109 }
5110
5111 // The VariantRef must point to function.
5112 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5113 if (!DRE) {
5114 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5115 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005116 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005117 }
5118 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5119 if (!NewFD) {
5120 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5121 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005122 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005123 }
5124
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005125 // Check if variant function is not marked with declare variant directive.
5126 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5127 Diag(VariantRef->getExprLoc(),
5128 diag::warn_omp_declare_variant_marked_as_declare_variant)
5129 << VariantRef->getSourceRange();
5130 SourceRange SR =
5131 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5132 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005133 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005134 }
5135
Alexey Bataevd158cf62019-09-13 20:18:17 +00005136 enum DoesntSupport {
5137 VirtFuncs = 1,
5138 Constructors = 3,
5139 Destructors = 4,
5140 DeletedFuncs = 5,
5141 DefaultedFuncs = 6,
5142 ConstexprFuncs = 7,
5143 ConstevalFuncs = 8,
5144 };
5145 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5146 if (CXXFD->isVirtual()) {
5147 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5148 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005149 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005150 }
5151
5152 if (isa<CXXConstructorDecl>(FD)) {
5153 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5154 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005155 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005156 }
5157
5158 if (isa<CXXDestructorDecl>(FD)) {
5159 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5160 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005161 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005162 }
5163 }
5164
5165 if (FD->isDeleted()) {
5166 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5167 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005168 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005169 }
5170
5171 if (FD->isDefaulted()) {
5172 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5173 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005174 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005175 }
5176
5177 if (FD->isConstexpr()) {
5178 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5179 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005180 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005181 }
5182
5183 // Check general compatibility.
5184 if (areMultiversionVariantFunctionsCompatible(
5185 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5186 PartialDiagnosticAt(
5187 SR.getBegin(),
5188 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5189 PartialDiagnosticAt(
5190 VariantRef->getExprLoc(),
5191 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5192 PartialDiagnosticAt(VariantRef->getExprLoc(),
5193 PDiag(diag::err_omp_declare_variant_diff)
5194 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005195 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5196 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005197 return None;
5198 return std::make_pair(FD, cast<Expr>(DRE));
5199}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005200
Alexey Bataev9ff34742019-09-25 19:43:37 +00005201void Sema::ActOnOpenMPDeclareVariantDirective(
5202 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005203 ArrayRef<OMPCtxSelectorData> Data) {
5204 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005205 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005206 SmallVector<Expr *, 4> CtxScores;
5207 SmallVector<unsigned, 4> CtxSets;
5208 SmallVector<unsigned, 4> Ctxs;
5209 SmallVector<StringRef, 4> ImplVendors;
5210 bool IsError = false;
5211 for (const OMPCtxSelectorData &D : Data) {
5212 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5213 OpenMPContextSelectorKind Ctx = D.Ctx;
5214 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5215 return;
5216 Expr *Score = nullptr;
5217 if (D.Score.isUsable()) {
5218 Score = D.Score.get();
5219 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5220 !Score->isInstantiationDependent() &&
5221 !Score->containsUnexpandedParameterPack()) {
5222 Score =
5223 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5224 .get();
5225 if (Score)
5226 Score = VerifyIntegerConstantExpression(Score).get();
5227 }
5228 } else {
5229 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005230 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005231 switch (CtxSet) {
5232 case OMP_CTX_SET_implementation:
5233 switch (Ctx) {
5234 case OMP_CTX_vendor:
5235 ImplVendors.append(D.Names.begin(), D.Names.end());
5236 break;
5237 case OMP_CTX_unknown:
5238 llvm_unreachable("Unexpected context selector kind.");
5239 }
5240 break;
5241 case OMP_CTX_SET_unknown:
5242 llvm_unreachable("Unexpected context selector set kind.");
5243 }
5244 IsError = IsError || !Score;
5245 CtxSets.push_back(CtxSet);
5246 Ctxs.push_back(Ctx);
5247 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005248 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005249 if (!IsError) {
5250 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5251 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5252 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
5253 ImplVendors.begin(), ImplVendors.size(), SR);
5254 FD->addAttr(NewAttr);
5255 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005256}
5257
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005258void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5259 FunctionDecl *Func,
5260 bool MightBeOdrUse) {
5261 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5262
5263 if (!Func->isDependentContext() && Func->hasAttrs()) {
5264 for (OMPDeclareVariantAttr *A :
5265 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5266 // TODO: add checks for active OpenMP context where possible.
5267 Expr *VariantRef = A->getVariantFuncRef();
5268 auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
5269 auto *F = cast<FunctionDecl>(DRE->getDecl());
5270 if (!F->isDefined() && F->isTemplateInstantiation())
5271 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5272 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5273 }
5274 }
5275}
5276
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005277StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5278 Stmt *AStmt,
5279 SourceLocation StartLoc,
5280 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005281 if (!AStmt)
5282 return StmtError();
5283
Alexey Bataeve3727102018-04-18 15:57:46 +00005284 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005285 // 1.2.2 OpenMP Language Terminology
5286 // Structured block - An executable statement with a single entry at the
5287 // top and a single exit at the bottom.
5288 // The point of exit cannot be a branch out of the structured block.
5289 // longjmp() and throw() must not violate the entry/exit criteria.
5290 CS->getCapturedDecl()->setNothrow();
5291
Reid Kleckner87a31802018-03-12 21:43:02 +00005292 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005293
Alexey Bataev25e5b442015-09-15 12:52:43 +00005294 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5295 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005296}
5297
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005298namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005299/// Iteration space of a single for loop.
5300struct LoopIterationSpace final {
5301 /// True if the condition operator is the strict compare operator (<, > or
5302 /// !=).
5303 bool IsStrictCompare = false;
5304 /// Condition of the loop.
5305 Expr *PreCond = nullptr;
5306 /// This expression calculates the number of iterations in the loop.
5307 /// It is always possible to calculate it before starting the loop.
5308 Expr *NumIterations = nullptr;
5309 /// The loop counter variable.
5310 Expr *CounterVar = nullptr;
5311 /// Private loop counter variable.
5312 Expr *PrivateCounterVar = nullptr;
5313 /// This is initializer for the initial value of #CounterVar.
5314 Expr *CounterInit = nullptr;
5315 /// This is step for the #CounterVar used to generate its update:
5316 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5317 Expr *CounterStep = nullptr;
5318 /// Should step be subtracted?
5319 bool Subtract = false;
5320 /// Source range of the loop init.
5321 SourceRange InitSrcRange;
5322 /// Source range of the loop condition.
5323 SourceRange CondSrcRange;
5324 /// Source range of the loop increment.
5325 SourceRange IncSrcRange;
5326 /// Minimum value that can have the loop control variable. Used to support
5327 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5328 /// since only such variables can be used in non-loop invariant expressions.
5329 Expr *MinValue = nullptr;
5330 /// Maximum value that can have the loop control variable. Used to support
5331 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5332 /// since only such variables can be used in non-loop invariant expressions.
5333 Expr *MaxValue = nullptr;
5334 /// true, if the lower bound depends on the outer loop control var.
5335 bool IsNonRectangularLB = false;
5336 /// true, if the upper bound depends on the outer loop control var.
5337 bool IsNonRectangularUB = false;
5338 /// Index of the loop this loop depends on and forms non-rectangular loop
5339 /// nest.
5340 unsigned LoopDependentIdx = 0;
5341 /// Final condition for the non-rectangular loop nest support. It is used to
5342 /// check that the number of iterations for this particular counter must be
5343 /// finished.
5344 Expr *FinalCondition = nullptr;
5345};
5346
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005347/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005348/// extracting iteration space of each loop in the loop nest, that will be used
5349/// for IR generation.
5350class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005351 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005352 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005353 /// Data-sharing stack.
5354 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005355 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005356 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005357 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005358 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005359 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005360 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005361 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005362 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005363 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005364 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005365 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005366 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005367 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005368 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005369 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005370 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005371 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005372 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005373 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005374 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005375 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005376 /// Var < UB
5377 /// Var <= UB
5378 /// UB > Var
5379 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005380 /// This will have no value when the condition is !=
5381 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005382 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005383 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005384 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005385 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005386 /// The outer loop counter this loop depends on (if any).
5387 const ValueDecl *DepDecl = nullptr;
5388 /// Contains number of loop (starts from 1) on which loop counter init
5389 /// expression of this loop depends on.
5390 Optional<unsigned> InitDependOnLC;
5391 /// Contains number of loop (starts from 1) on which loop counter condition
5392 /// expression of this loop depends on.
5393 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005394 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005395 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005396 /// Original condition required for checking of the exit condition for
5397 /// non-rectangular loop.
5398 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005399
5400public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005401 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5402 SourceLocation DefaultLoc)
5403 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5404 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005405 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005406 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005407 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005408 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005409 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005410 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005411 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005412 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005413 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005414 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005415 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005416 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005417 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005418 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005419 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005420 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005421 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005422 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005423 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005424 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005425 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005426 /// True, if the compare operator is strict (<, > or !=).
5427 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005428 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005429 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005430 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005431 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005432 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005433 Expr *
5434 buildPreCond(Scope *S, Expr *Cond,
5435 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005436 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005437 DeclRefExpr *
5438 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5439 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005440 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005441 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005442 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005443 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005444 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005445 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005446 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005447 /// Build loop data with counter value for depend clauses in ordered
5448 /// directives.
5449 Expr *
5450 buildOrderedLoopData(Scope *S, Expr *Counter,
5451 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5452 SourceLocation Loc, Expr *Inc = nullptr,
5453 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005454 /// Builds the minimum value for the loop counter.
5455 std::pair<Expr *, Expr *> buildMinMaxValues(
5456 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5457 /// Builds final condition for the non-rectangular loops.
5458 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005459 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005460 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005461 /// Returns true if the initializer forms non-rectangular loop.
5462 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5463 /// Returns true if the condition forms non-rectangular loop.
5464 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5465 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5466 unsigned getLoopDependentIdx() const {
5467 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5468 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005469
5470private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005471 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005472 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005473 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005474 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005475 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5476 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005477 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005478 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5479 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005480 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005481 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005482};
5483
Alexey Bataeve3727102018-04-18 15:57:46 +00005484bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005485 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005486 assert(!LB && !UB && !Step);
5487 return false;
5488 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005489 return LCDecl->getType()->isDependentType() ||
5490 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5491 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005492}
5493
Alexey Bataeve3727102018-04-18 15:57:46 +00005494bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005495 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005496 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005497 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005498 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005499 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005500 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005501 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005502 LCDecl = getCanonicalDecl(NewLCDecl);
5503 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005504 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5505 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005506 if ((Ctor->isCopyOrMoveConstructor() ||
5507 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5508 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005509 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005510 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005511 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005512 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005513 return false;
5514}
5515
Alexey Bataev316ccf62019-01-29 18:51:58 +00005516bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5517 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005518 bool StrictOp, SourceRange SR,
5519 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005520 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005521 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5522 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005523 if (!NewUB)
5524 return true;
5525 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005526 if (LessOp)
5527 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005528 TestIsStrictOp = StrictOp;
5529 ConditionSrcRange = SR;
5530 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005531 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005532 return false;
5533}
5534
Alexey Bataeve3727102018-04-18 15:57:46 +00005535bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005536 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005537 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005538 if (!NewStep)
5539 return true;
5540 if (!NewStep->isValueDependent()) {
5541 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005542 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005543 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5544 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005545 if (Val.isInvalid())
5546 return true;
5547 NewStep = Val.get();
5548
5549 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5550 // If test-expr is of form var relational-op b and relational-op is < or
5551 // <= then incr-expr must cause var to increase on each iteration of the
5552 // loop. If test-expr is of form var relational-op b and relational-op is
5553 // > or >= then incr-expr must cause var to decrease on each iteration of
5554 // the loop.
5555 // If test-expr is of form b relational-op var and relational-op is < or
5556 // <= then incr-expr must cause var to decrease on each iteration of the
5557 // loop. If test-expr is of form b relational-op var and relational-op is
5558 // > or >= then incr-expr must cause var to increase on each iteration of
5559 // the loop.
5560 llvm::APSInt Result;
5561 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5562 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5563 bool IsConstNeg =
5564 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005565 bool IsConstPos =
5566 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005567 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005568
5569 // != with increment is treated as <; != with decrement is treated as >
5570 if (!TestIsLessOp.hasValue())
5571 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005572 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005573 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005574 (IsConstNeg || (IsUnsigned && Subtract)) :
5575 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005576 SemaRef.Diag(NewStep->getExprLoc(),
5577 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005578 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005579 SemaRef.Diag(ConditionLoc,
5580 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005581 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005582 return true;
5583 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005584 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005585 NewStep =
5586 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5587 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005588 Subtract = !Subtract;
5589 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005590 }
5591
5592 Step = NewStep;
5593 SubtractStep = Subtract;
5594 return false;
5595}
5596
Alexey Bataev622af1d2019-04-24 19:58:30 +00005597namespace {
5598/// Checker for the non-rectangular loops. Checks if the initializer or
5599/// condition expression references loop counter variable.
5600class LoopCounterRefChecker final
5601 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5602 Sema &SemaRef;
5603 DSAStackTy &Stack;
5604 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005605 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005606 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005607 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005608 unsigned BaseLoopId = 0;
5609 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5610 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5611 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5612 << (IsInitializer ? 0 : 1);
5613 return false;
5614 }
5615 const auto &&Data = Stack.isLoopControlVariable(VD);
5616 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5617 // The type of the loop iterator on which we depend may not have a random
5618 // access iterator type.
5619 if (Data.first && VD->getType()->isRecordType()) {
5620 SmallString<128> Name;
5621 llvm::raw_svector_ostream OS(Name);
5622 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5623 /*Qualified=*/true);
5624 SemaRef.Diag(E->getExprLoc(),
5625 diag::err_omp_wrong_dependency_iterator_type)
5626 << OS.str();
5627 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5628 return false;
5629 }
5630 if (Data.first &&
5631 (DepDecl || (PrevDepDecl &&
5632 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5633 if (!DepDecl && PrevDepDecl)
5634 DepDecl = PrevDepDecl;
5635 SmallString<128> Name;
5636 llvm::raw_svector_ostream OS(Name);
5637 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5638 /*Qualified=*/true);
5639 SemaRef.Diag(E->getExprLoc(),
5640 diag::err_omp_invariant_or_linear_dependency)
5641 << OS.str();
5642 return false;
5643 }
5644 if (Data.first) {
5645 DepDecl = VD;
5646 BaseLoopId = Data.first;
5647 }
5648 return Data.first;
5649 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005650
5651public:
5652 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5653 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005654 if (isa<VarDecl>(VD))
5655 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005656 return false;
5657 }
5658 bool VisitMemberExpr(const MemberExpr *E) {
5659 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5660 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005661 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5662 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005663 }
5664 return false;
5665 }
5666 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005667 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005668 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005669 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005670 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005671 }
5672 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005673 const ValueDecl *CurLCDecl, bool IsInitializer,
5674 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005675 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005676 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5677 unsigned getBaseLoopId() const {
5678 assert(CurLCDecl && "Expected loop dependency.");
5679 return BaseLoopId;
5680 }
5681 const ValueDecl *getDepDecl() const {
5682 assert(CurLCDecl && "Expected loop dependency.");
5683 return DepDecl;
5684 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005685};
5686} // namespace
5687
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005688Optional<unsigned>
5689OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5690 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005691 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005692 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5693 DepDecl);
5694 if (LoopStmtChecker.Visit(S)) {
5695 DepDecl = LoopStmtChecker.getDepDecl();
5696 return LoopStmtChecker.getBaseLoopId();
5697 }
5698 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005699}
5700
Alexey Bataeve3727102018-04-18 15:57:46 +00005701bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005702 // Check init-expr for canonical loop form and save loop counter
5703 // variable - #Var and its initialization value - #LB.
5704 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5705 // var = lb
5706 // integer-type var = lb
5707 // random-access-iterator-type var = lb
5708 // pointer-type var = lb
5709 //
5710 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005711 if (EmitDiags) {
5712 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5713 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005714 return true;
5715 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005716 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5717 if (!ExprTemp->cleanupsHaveSideEffects())
5718 S = ExprTemp->getSubExpr();
5719
Alexander Musmana5f070a2014-10-01 06:03:56 +00005720 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005721 if (Expr *E = dyn_cast<Expr>(S))
5722 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005723 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005724 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005725 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005726 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5727 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5728 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005729 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5730 EmitDiags);
5731 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005732 }
5733 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5734 if (ME->isArrow() &&
5735 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005736 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5737 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005738 }
5739 }
David Majnemer9d168222016-08-05 17:44:54 +00005740 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005741 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005742 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005743 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005744 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005745 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005746 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005747 diag::ext_omp_loop_not_canonical_init)
5748 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005749 return setLCDeclAndLB(
5750 Var,
5751 buildDeclRefExpr(SemaRef, Var,
5752 Var->getType().getNonReferenceType(),
5753 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005754 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005755 }
5756 }
5757 }
David Majnemer9d168222016-08-05 17:44:54 +00005758 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005759 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005760 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005761 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005762 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5763 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005764 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5765 EmitDiags);
5766 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005767 }
5768 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5769 if (ME->isArrow() &&
5770 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005771 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5772 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005773 }
5774 }
5775 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005776
Alexey Bataeve3727102018-04-18 15:57:46 +00005777 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005778 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005779 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005780 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005781 << S->getSourceRange();
5782 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005783 return true;
5784}
5785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005786/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005787/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005788static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005789 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005790 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005791 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005792 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005793 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005794 if ((Ctor->isCopyOrMoveConstructor() ||
5795 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5796 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005797 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005798 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5799 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005800 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005801 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005802 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005803 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5804 return getCanonicalDecl(ME->getMemberDecl());
5805 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005806}
5807
Alexey Bataeve3727102018-04-18 15:57:46 +00005808bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005809 // Check test-expr for canonical form, save upper-bound UB, flags for
5810 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005811 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005812 // var relational-op b
5813 // b relational-op var
5814 //
Alexey Bataev1be63402019-09-11 15:44:06 +00005815 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005816 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00005817 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
5818 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005819 return true;
5820 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00005821 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005822 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005823 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005824 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005825 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005826 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5827 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005828 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5829 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5830 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005831 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5832 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005833 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5834 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5835 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00005836 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
5837 return setUB(
5838 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
5839 /*LessOp=*/llvm::None,
5840 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005841 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005842 if (CE->getNumArgs() == 2) {
5843 auto Op = CE->getOperator();
5844 switch (Op) {
5845 case OO_Greater:
5846 case OO_GreaterEqual:
5847 case OO_Less:
5848 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005849 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5850 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005851 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5852 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005853 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5854 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005855 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5856 CE->getOperatorLoc());
5857 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005858 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00005859 if (IneqCondIsCanonical)
5860 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
5861 : CE->getArg(0),
5862 /*LessOp=*/llvm::None,
5863 /*StrictOp=*/true, CE->getSourceRange(),
5864 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005865 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005866 default:
5867 break;
5868 }
5869 }
5870 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005871 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005872 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005873 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00005874 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005875 return true;
5876}
5877
Alexey Bataeve3727102018-04-18 15:57:46 +00005878bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005879 // RHS of canonical loop form increment can be:
5880 // var + incr
5881 // incr + var
5882 // var - incr
5883 //
5884 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005885 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005886 if (BO->isAdditiveOp()) {
5887 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005888 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5889 return setStep(BO->getRHS(), !IsAdd);
5890 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5891 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005892 }
David Majnemer9d168222016-08-05 17:44:54 +00005893 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005894 bool IsAdd = CE->getOperator() == OO_Plus;
5895 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005896 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5897 return setStep(CE->getArg(1), !IsAdd);
5898 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5899 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005900 }
5901 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005902 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005903 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005904 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005905 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005906 return true;
5907}
5908
Alexey Bataeve3727102018-04-18 15:57:46 +00005909bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005910 // Check incr-expr for canonical loop form and return true if it
5911 // does not conform.
5912 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5913 // ++var
5914 // var++
5915 // --var
5916 // var--
5917 // var += incr
5918 // var -= incr
5919 // var = var + incr
5920 // var = incr + var
5921 // var = var - incr
5922 //
5923 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005924 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005925 return true;
5926 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005927 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5928 if (!ExprTemp->cleanupsHaveSideEffects())
5929 S = ExprTemp->getSubExpr();
5930
Alexander Musmana5f070a2014-10-01 06:03:56 +00005931 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005932 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005933 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005934 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005935 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5936 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005937 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005938 (UO->isDecrementOp() ? -1 : 1))
5939 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005940 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005941 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005942 switch (BO->getOpcode()) {
5943 case BO_AddAssign:
5944 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005945 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5946 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005947 break;
5948 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005949 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5950 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005951 break;
5952 default:
5953 break;
5954 }
David Majnemer9d168222016-08-05 17:44:54 +00005955 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005956 switch (CE->getOperator()) {
5957 case OO_PlusPlus:
5958 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005959 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5960 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005961 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005962 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005963 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5964 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005965 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005966 break;
5967 case OO_PlusEqual:
5968 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005969 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5970 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005971 break;
5972 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005973 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5974 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005975 break;
5976 default:
5977 break;
5978 }
5979 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005980 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005981 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005982 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005983 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005984 return true;
5985}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005986
Alexey Bataev5a3af132016-03-29 08:58:54 +00005987static ExprResult
5988tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005989 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005990 if (SemaRef.CurContext->isDependentContext())
5991 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005992 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5993 return SemaRef.PerformImplicitConversion(
5994 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5995 /*AllowExplicit=*/true);
5996 auto I = Captures.find(Capture);
5997 if (I != Captures.end())
5998 return buildCapture(SemaRef, Capture, I->second);
5999 DeclRefExpr *Ref = nullptr;
6000 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6001 Captures[Capture] = Ref;
6002 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006003}
6004
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006005/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006006Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006007 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006008 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006009 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006010 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006011 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006012 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006013 Expr *LBVal = LB;
6014 Expr *UBVal = UB;
6015 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6016 // max(LB(MinVal), LB(MaxVal))
6017 if (InitDependOnLC) {
6018 const LoopIterationSpace &IS =
6019 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6020 InitDependOnLC.getValueOr(
6021 CondDependOnLC.getValueOr(0))];
6022 if (!IS.MinValue || !IS.MaxValue)
6023 return nullptr;
6024 // OuterVar = Min
6025 ExprResult MinValue =
6026 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6027 if (!MinValue.isUsable())
6028 return nullptr;
6029
6030 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6031 IS.CounterVar, MinValue.get());
6032 if (!LBMinVal.isUsable())
6033 return nullptr;
6034 // OuterVar = Min, LBVal
6035 LBMinVal =
6036 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6037 if (!LBMinVal.isUsable())
6038 return nullptr;
6039 // (OuterVar = Min, LBVal)
6040 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6041 if (!LBMinVal.isUsable())
6042 return nullptr;
6043
6044 // OuterVar = Max
6045 ExprResult MaxValue =
6046 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6047 if (!MaxValue.isUsable())
6048 return nullptr;
6049
6050 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6051 IS.CounterVar, MaxValue.get());
6052 if (!LBMaxVal.isUsable())
6053 return nullptr;
6054 // OuterVar = Max, LBVal
6055 LBMaxVal =
6056 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6057 if (!LBMaxVal.isUsable())
6058 return nullptr;
6059 // (OuterVar = Max, LBVal)
6060 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6061 if (!LBMaxVal.isUsable())
6062 return nullptr;
6063
6064 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6065 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6066 if (!LBMin || !LBMax)
6067 return nullptr;
6068 // LB(MinVal) < LB(MaxVal)
6069 ExprResult MinLessMaxRes =
6070 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6071 if (!MinLessMaxRes.isUsable())
6072 return nullptr;
6073 Expr *MinLessMax =
6074 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6075 if (!MinLessMax)
6076 return nullptr;
6077 if (TestIsLessOp.getValue()) {
6078 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6079 // LB(MaxVal))
6080 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6081 MinLessMax, LBMin, LBMax);
6082 if (!MinLB.isUsable())
6083 return nullptr;
6084 LBVal = MinLB.get();
6085 } else {
6086 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6087 // LB(MaxVal))
6088 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6089 MinLessMax, LBMax, LBMin);
6090 if (!MaxLB.isUsable())
6091 return nullptr;
6092 LBVal = MaxLB.get();
6093 }
6094 }
6095 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6096 // min(UB(MinVal), UB(MaxVal))
6097 if (CondDependOnLC) {
6098 const LoopIterationSpace &IS =
6099 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6100 InitDependOnLC.getValueOr(
6101 CondDependOnLC.getValueOr(0))];
6102 if (!IS.MinValue || !IS.MaxValue)
6103 return nullptr;
6104 // OuterVar = Min
6105 ExprResult MinValue =
6106 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6107 if (!MinValue.isUsable())
6108 return nullptr;
6109
6110 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6111 IS.CounterVar, MinValue.get());
6112 if (!UBMinVal.isUsable())
6113 return nullptr;
6114 // OuterVar = Min, UBVal
6115 UBMinVal =
6116 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6117 if (!UBMinVal.isUsable())
6118 return nullptr;
6119 // (OuterVar = Min, UBVal)
6120 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6121 if (!UBMinVal.isUsable())
6122 return nullptr;
6123
6124 // OuterVar = Max
6125 ExprResult MaxValue =
6126 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6127 if (!MaxValue.isUsable())
6128 return nullptr;
6129
6130 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6131 IS.CounterVar, MaxValue.get());
6132 if (!UBMaxVal.isUsable())
6133 return nullptr;
6134 // OuterVar = Max, UBVal
6135 UBMaxVal =
6136 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6137 if (!UBMaxVal.isUsable())
6138 return nullptr;
6139 // (OuterVar = Max, UBVal)
6140 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6141 if (!UBMaxVal.isUsable())
6142 return nullptr;
6143
6144 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6145 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6146 if (!UBMin || !UBMax)
6147 return nullptr;
6148 // UB(MinVal) > UB(MaxVal)
6149 ExprResult MinGreaterMaxRes =
6150 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6151 if (!MinGreaterMaxRes.isUsable())
6152 return nullptr;
6153 Expr *MinGreaterMax =
6154 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6155 if (!MinGreaterMax)
6156 return nullptr;
6157 if (TestIsLessOp.getValue()) {
6158 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6159 // UB(MaxVal))
6160 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6161 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6162 if (!MaxUB.isUsable())
6163 return nullptr;
6164 UBVal = MaxUB.get();
6165 } else {
6166 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6167 // UB(MaxVal))
6168 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6169 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6170 if (!MinUB.isUsable())
6171 return nullptr;
6172 UBVal = MinUB.get();
6173 }
6174 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006175 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006176 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6177 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006178 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6179 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006180 if (!Upper || !Lower)
6181 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006182
6183 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6184
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006185 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006186 // BuildBinOp already emitted error, this one is to point user to upper
6187 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006188 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006189 << Upper->getSourceRange() << Lower->getSourceRange();
6190 return nullptr;
6191 }
6192 }
6193
6194 if (!Diff.isUsable())
6195 return nullptr;
6196
6197 // Upper - Lower [- 1]
6198 if (TestIsStrictOp)
6199 Diff = SemaRef.BuildBinOp(
6200 S, DefaultLoc, BO_Sub, Diff.get(),
6201 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6202 if (!Diff.isUsable())
6203 return nullptr;
6204
6205 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006206 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006207 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006208 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006209 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006210 if (!Diff.isUsable())
6211 return nullptr;
6212
6213 // Parentheses (for dumping/debugging purposes only).
6214 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6215 if (!Diff.isUsable())
6216 return nullptr;
6217
6218 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006219 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006220 if (!Diff.isUsable())
6221 return nullptr;
6222
Alexander Musman174b3ca2014-10-06 11:16:29 +00006223 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006224 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006225 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006226 bool UseVarType = VarType->hasIntegerRepresentation() &&
6227 C.getTypeSize(Type) > C.getTypeSize(VarType);
6228 if (!Type->isIntegerType() || UseVarType) {
6229 unsigned NewSize =
6230 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6231 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6232 : Type->hasSignedIntegerRepresentation();
6233 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006234 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6235 Diff = SemaRef.PerformImplicitConversion(
6236 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6237 if (!Diff.isUsable())
6238 return nullptr;
6239 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006240 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006241 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006242 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6243 if (NewSize != C.getTypeSize(Type)) {
6244 if (NewSize < C.getTypeSize(Type)) {
6245 assert(NewSize == 64 && "incorrect loop var size");
6246 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6247 << InitSrcRange << ConditionSrcRange;
6248 }
6249 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006250 NewSize, Type->hasSignedIntegerRepresentation() ||
6251 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006252 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6253 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6254 Sema::AA_Converting, true);
6255 if (!Diff.isUsable())
6256 return nullptr;
6257 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006258 }
6259 }
6260
Alexander Musmana5f070a2014-10-01 06:03:56 +00006261 return Diff.get();
6262}
6263
Alexey Bataevf8be4762019-08-14 19:30:06 +00006264std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6265 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6266 // Do not build for iterators, they cannot be used in non-rectangular loop
6267 // nests.
6268 if (LCDecl->getType()->isRecordType())
6269 return std::make_pair(nullptr, nullptr);
6270 // If we subtract, the min is in the condition, otherwise the min is in the
6271 // init value.
6272 Expr *MinExpr = nullptr;
6273 Expr *MaxExpr = nullptr;
6274 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6275 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6276 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6277 : CondDependOnLC.hasValue();
6278 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6279 : InitDependOnLC.hasValue();
6280 Expr *Lower =
6281 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6282 Expr *Upper =
6283 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6284 if (!Upper || !Lower)
6285 return std::make_pair(nullptr, nullptr);
6286
6287 if (TestIsLessOp.getValue())
6288 MinExpr = Lower;
6289 else
6290 MaxExpr = Upper;
6291
6292 // Build minimum/maximum value based on number of iterations.
6293 ExprResult Diff;
6294 QualType VarType = LCDecl->getType().getNonReferenceType();
6295
6296 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6297 if (!Diff.isUsable())
6298 return std::make_pair(nullptr, nullptr);
6299
6300 // Upper - Lower [- 1]
6301 if (TestIsStrictOp)
6302 Diff = SemaRef.BuildBinOp(
6303 S, DefaultLoc, BO_Sub, Diff.get(),
6304 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6305 if (!Diff.isUsable())
6306 return std::make_pair(nullptr, nullptr);
6307
6308 // Upper - Lower [- 1] + Step
6309 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6310 if (!NewStep.isUsable())
6311 return std::make_pair(nullptr, nullptr);
6312
6313 // Parentheses (for dumping/debugging purposes only).
6314 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6315 if (!Diff.isUsable())
6316 return std::make_pair(nullptr, nullptr);
6317
6318 // (Upper - Lower [- 1]) / Step
6319 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6320 if (!Diff.isUsable())
6321 return std::make_pair(nullptr, nullptr);
6322
6323 // ((Upper - Lower [- 1]) / Step) * Step
6324 // Parentheses (for dumping/debugging purposes only).
6325 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6326 if (!Diff.isUsable())
6327 return std::make_pair(nullptr, nullptr);
6328
6329 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6330 if (!Diff.isUsable())
6331 return std::make_pair(nullptr, nullptr);
6332
6333 // Convert to the original type or ptrdiff_t, if original type is pointer.
6334 if (!VarType->isAnyPointerType() &&
6335 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6336 Diff = SemaRef.PerformImplicitConversion(
6337 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6338 } else if (VarType->isAnyPointerType() &&
6339 !SemaRef.Context.hasSameType(
6340 Diff.get()->getType(),
6341 SemaRef.Context.getUnsignedPointerDiffType())) {
6342 Diff = SemaRef.PerformImplicitConversion(
6343 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6344 Sema::AA_Converting, /*AllowExplicit=*/true);
6345 }
6346 if (!Diff.isUsable())
6347 return std::make_pair(nullptr, nullptr);
6348
6349 // Parentheses (for dumping/debugging purposes only).
6350 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6351 if (!Diff.isUsable())
6352 return std::make_pair(nullptr, nullptr);
6353
6354 if (TestIsLessOp.getValue()) {
6355 // MinExpr = Lower;
6356 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6357 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6358 if (!Diff.isUsable())
6359 return std::make_pair(nullptr, nullptr);
6360 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6361 if (!Diff.isUsable())
6362 return std::make_pair(nullptr, nullptr);
6363 MaxExpr = Diff.get();
6364 } else {
6365 // MaxExpr = Upper;
6366 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6367 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6368 if (!Diff.isUsable())
6369 return std::make_pair(nullptr, nullptr);
6370 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6371 if (!Diff.isUsable())
6372 return std::make_pair(nullptr, nullptr);
6373 MinExpr = Diff.get();
6374 }
6375
6376 return std::make_pair(MinExpr, MaxExpr);
6377}
6378
6379Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6380 if (InitDependOnLC || CondDependOnLC)
6381 return Condition;
6382 return nullptr;
6383}
6384
Alexey Bataeve3727102018-04-18 15:57:46 +00006385Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006386 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006387 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006388 // Do not build a precondition when the condition/initialization is dependent
6389 // to prevent pessimistic early loop exit.
6390 // TODO: this can be improved by calculating min/max values but not sure that
6391 // it will be very effective.
6392 if (CondDependOnLC || InitDependOnLC)
6393 return SemaRef.PerformImplicitConversion(
6394 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6395 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6396 /*AllowExplicit=*/true).get();
6397
Alexey Bataev62dbb972015-04-22 11:59:37 +00006398 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006399 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006400
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006401 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6402 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006403 if (!NewLB.isUsable() || !NewUB.isUsable())
6404 return nullptr;
6405
Alexey Bataeve3727102018-04-18 15:57:46 +00006406 ExprResult CondExpr =
6407 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006408 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006409 (TestIsStrictOp ? BO_LT : BO_LE) :
6410 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006411 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006412 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006413 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6414 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006415 CondExpr = SemaRef.PerformImplicitConversion(
6416 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6417 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006418 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006419
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006420 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006421 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6422}
6423
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006424/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006425DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006426 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6427 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006428 auto *VD = dyn_cast<VarDecl>(LCDecl);
6429 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006430 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6431 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006432 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006433 const DSAStackTy::DSAVarData Data =
6434 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006435 // If the loop control decl is explicitly marked as private, do not mark it
6436 // as captured again.
6437 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6438 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006439 return Ref;
6440 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006441 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006442}
6443
Alexey Bataeve3727102018-04-18 15:57:46 +00006444Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006445 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006446 QualType Type = LCDecl->getType().getNonReferenceType();
6447 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006448 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6449 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6450 isa<VarDecl>(LCDecl)
6451 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6452 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006453 if (PrivateVar->isInvalidDecl())
6454 return nullptr;
6455 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6456 }
6457 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006458}
6459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006460/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006461Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006463/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006464Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006465
Alexey Bataevf138fda2018-08-13 19:04:24 +00006466Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6467 Scope *S, Expr *Counter,
6468 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6469 Expr *Inc, OverloadedOperatorKind OOK) {
6470 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6471 if (!Cnt)
6472 return nullptr;
6473 if (Inc) {
6474 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6475 "Expected only + or - operations for depend clauses.");
6476 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6477 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6478 if (!Cnt)
6479 return nullptr;
6480 }
6481 ExprResult Diff;
6482 QualType VarType = LCDecl->getType().getNonReferenceType();
6483 if (VarType->isIntegerType() || VarType->isPointerType() ||
6484 SemaRef.getLangOpts().CPlusPlus) {
6485 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006486 Expr *Upper = TestIsLessOp.getValue()
6487 ? Cnt
6488 : tryBuildCapture(SemaRef, UB, Captures).get();
6489 Expr *Lower = TestIsLessOp.getValue()
6490 ? tryBuildCapture(SemaRef, LB, Captures).get()
6491 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006492 if (!Upper || !Lower)
6493 return nullptr;
6494
6495 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6496
6497 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6498 // BuildBinOp already emitted error, this one is to point user to upper
6499 // and lower bound, and to tell what is passed to 'operator-'.
6500 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6501 << Upper->getSourceRange() << Lower->getSourceRange();
6502 return nullptr;
6503 }
6504 }
6505
6506 if (!Diff.isUsable())
6507 return nullptr;
6508
6509 // Parentheses (for dumping/debugging purposes only).
6510 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6511 if (!Diff.isUsable())
6512 return nullptr;
6513
6514 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6515 if (!NewStep.isUsable())
6516 return nullptr;
6517 // (Upper - Lower) / Step
6518 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6519 if (!Diff.isUsable())
6520 return nullptr;
6521
6522 return Diff.get();
6523}
Alexey Bataev23b69422014-06-18 07:08:49 +00006524} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006525
Alexey Bataev9c821032015-04-30 04:23:23 +00006526void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6527 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6528 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006529 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6530 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006531 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006532 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006533 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006534 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6535 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006536 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006537 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006538 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006539 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006540 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006541 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006542 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6543 /*WithInit=*/false);
6544 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006545 }
6546 }
6547 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006548 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6549 if (LD != D->getCanonicalDecl()) {
6550 DSAStack->resetPossibleLoopCounter();
6551 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6552 MarkDeclarationsReferencedInExpr(
6553 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6554 Var->getType().getNonLValueExprType(Context),
6555 ForLoc, /*RefersToCapture=*/true));
6556 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006557 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6558 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6559 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6560 // associated for-loop of a simd construct with just one associated
6561 // for-loop may be listed in a linear clause with a constant-linear-step
6562 // that is the increment of the associated for-loop. The loop iteration
6563 // variable(s) in the associated for-loop(s) of a for or parallel for
6564 // construct may be listed in a private or lastprivate clause.
6565 DSAStackTy::DSAVarData DVar =
6566 DSAStack->getTopDSA(D, /*FromParent=*/false);
6567 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6568 // is declared in the loop and it is predetermined as a private.
6569 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6570 OpenMPClauseKind PredeterminedCKind =
6571 isOpenMPSimdDirective(DKind)
6572 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6573 : OMPC_private;
6574 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6575 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6576 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6577 DVar.CKind != OMPC_private))) ||
6578 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006579 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006580 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006581 isOpenMPDistributeDirective(DKind)) &&
6582 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6583 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6584 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6585 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6586 << getOpenMPClauseName(DVar.CKind)
6587 << getOpenMPDirectiveName(DKind)
6588 << getOpenMPClauseName(PredeterminedCKind);
6589 if (DVar.RefExpr == nullptr)
6590 DVar.CKind = PredeterminedCKind;
6591 reportOriginalDsa(*this, DSAStack, D, DVar,
6592 /*IsLoopIterVar=*/true);
6593 } else if (LoopDeclRefExpr) {
6594 // Make the loop iteration variable private (for worksharing
6595 // constructs), linear (for simd directives with the only one
6596 // associated loop) or lastprivate (for simd directives with several
6597 // collapsed or ordered loops).
6598 if (DVar.CKind == OMPC_unknown)
6599 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6600 PrivateRef);
6601 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006602 }
6603 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006604 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006605 }
6606}
6607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006608/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006609/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006610static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006611 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6612 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006613 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6614 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006615 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006616 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006617 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006618 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006619 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006620 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006621 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006622 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6623 // Ranged for is supported only in OpenMP 5.0.
6624 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006625 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006626 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006627 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006628 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006629 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006630 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6631 SemaRef.Diag(DSA.getConstructLoc(),
6632 diag::note_omp_collapse_ordered_expr)
6633 << 2 << CollapseLoopCountExpr->getSourceRange()
6634 << OrderedLoopCountExpr->getSourceRange();
6635 else if (CollapseLoopCountExpr)
6636 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6637 diag::note_omp_collapse_ordered_expr)
6638 << 0 << CollapseLoopCountExpr->getSourceRange();
6639 else
6640 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6641 diag::note_omp_collapse_ordered_expr)
6642 << 1 << OrderedLoopCountExpr->getSourceRange();
6643 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006644 return true;
6645 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006646 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6647 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006648
Alexey Bataevbef93a92019-10-07 18:54:57 +00006649 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6650 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006651
6652 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006653 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006654 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006655 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006656
6657 bool HasErrors = false;
6658
6659 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006660 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006661 // OpenMP [2.6, Canonical Loop Form]
6662 // Var is one of the following:
6663 // A variable of signed or unsigned integer type.
6664 // For C++, a variable of a random access iterator type.
6665 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006666 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006667 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6668 !VarType->isPointerType() &&
6669 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006670 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006671 << SemaRef.getLangOpts().CPlusPlus;
6672 HasErrors = true;
6673 }
6674
6675 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6676 // a Construct
6677 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6678 // parallel for construct is (are) private.
6679 // The loop iteration variable in the associated for-loop of a simd
6680 // construct with just one associated for-loop is linear with a
6681 // constant-linear-step that is the increment of the associated for-loop.
6682 // Exclude loop var from the list of variables with implicitly defined data
6683 // sharing attributes.
6684 VarsWithImplicitDSA.erase(LCDecl);
6685
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006686 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6687
6688 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006689 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006690
6691 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006692 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006693 }
6694
Alexey Bataeve3727102018-04-18 15:57:46 +00006695 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006696 return HasErrors;
6697
Alexander Musmana5f070a2014-10-01 06:03:56 +00006698 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006699 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6700 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006701 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6702 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6703 (isOpenMPWorksharingDirective(DKind) ||
6704 isOpenMPTaskLoopDirective(DKind) ||
6705 isOpenMPDistributeDirective(DKind)),
6706 Captures);
6707 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6708 ISC.buildCounterVar(Captures, DSA);
6709 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6710 ISC.buildPrivateCounterVar();
6711 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6712 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6713 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6714 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6715 ISC.getConditionSrcRange();
6716 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6717 ISC.getIncrementSrcRange();
6718 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6719 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6720 ISC.isStrictTestOp();
6721 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6722 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6723 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6724 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6725 ISC.buildFinalCondition(DSA.getCurScope());
6726 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6727 ISC.doesInitDependOnLC();
6728 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6729 ISC.doesCondDependOnLC();
6730 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6731 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006732
Alexey Bataevf8be4762019-08-14 19:30:06 +00006733 HasErrors |=
6734 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6735 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6736 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6737 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6738 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6739 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006740 if (!HasErrors && DSA.isOrderedRegion()) {
6741 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6742 if (CurrentNestedLoopCount <
6743 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6744 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006745 CurrentNestedLoopCount,
6746 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006747 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006748 CurrentNestedLoopCount,
6749 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006750 }
6751 }
6752 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6753 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6754 // Erroneous case - clause has some problems.
6755 continue;
6756 }
6757 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6758 Pair.second.size() <= CurrentNestedLoopCount) {
6759 // Erroneous case - clause has some problems.
6760 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6761 continue;
6762 }
6763 Expr *CntValue;
6764 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6765 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006766 DSA.getCurScope(),
6767 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006768 Pair.first->getDependencyLoc());
6769 else
6770 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006771 DSA.getCurScope(),
6772 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006773 Pair.first->getDependencyLoc(),
6774 Pair.second[CurrentNestedLoopCount].first,
6775 Pair.second[CurrentNestedLoopCount].second);
6776 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6777 }
6778 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006779
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006780 return HasErrors;
6781}
6782
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006783/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006784static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006785buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006786 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006787 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006788 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006789 ExprResult NewStart = IsNonRectangularLB
6790 ? Start.get()
6791 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006792 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006793 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006794 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006795 VarRef.get()->getType())) {
6796 NewStart = SemaRef.PerformImplicitConversion(
6797 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6798 /*AllowExplicit=*/true);
6799 if (!NewStart.isUsable())
6800 return ExprError();
6801 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006802
Alexey Bataeve3727102018-04-18 15:57:46 +00006803 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006804 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6805 return Init;
6806}
6807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006808/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006809static ExprResult buildCounterUpdate(
6810 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6811 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006812 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006813 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006814 // Add parentheses (for debugging purposes only).
6815 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
6816 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
6817 !Step.isUsable())
6818 return ExprError();
6819
Alexey Bataev5a3af132016-03-29 08:58:54 +00006820 ExprResult NewStep = Step;
6821 if (Captures)
6822 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006823 if (NewStep.isInvalid())
6824 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006825 ExprResult Update =
6826 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006827 if (!Update.isUsable())
6828 return ExprError();
6829
Alexey Bataevc0214e02016-02-16 12:13:49 +00006830 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
6831 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006832 if (!Start.isUsable())
6833 return ExprError();
6834 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
6835 if (!NewStart.isUsable())
6836 return ExprError();
6837 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006838 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006839 if (NewStart.isInvalid())
6840 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006841
Alexey Bataevc0214e02016-02-16 12:13:49 +00006842 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
6843 ExprResult SavedUpdate = Update;
6844 ExprResult UpdateVal;
6845 if (VarRef.get()->getType()->isOverloadableType() ||
6846 NewStart.get()->getType()->isOverloadableType() ||
6847 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006848 Sema::TentativeAnalysisScope Trap(SemaRef);
6849
Alexey Bataevc0214e02016-02-16 12:13:49 +00006850 Update =
6851 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6852 if (Update.isUsable()) {
6853 UpdateVal =
6854 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
6855 VarRef.get(), SavedUpdate.get());
6856 if (UpdateVal.isUsable()) {
6857 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
6858 UpdateVal.get());
6859 }
6860 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006861 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006862
Alexey Bataevc0214e02016-02-16 12:13:49 +00006863 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
6864 if (!Update.isUsable() || !UpdateVal.isUsable()) {
6865 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
6866 NewStart.get(), SavedUpdate.get());
6867 if (!Update.isUsable())
6868 return ExprError();
6869
Alexey Bataev11481f52016-02-17 10:29:05 +00006870 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
6871 VarRef.get()->getType())) {
6872 Update = SemaRef.PerformImplicitConversion(
6873 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
6874 if (!Update.isUsable())
6875 return ExprError();
6876 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006877
6878 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
6879 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006880 return Update;
6881}
6882
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006883/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006884/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006885static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006886 if (E == nullptr)
6887 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006888 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006889 QualType OldType = E->getType();
6890 unsigned HasBits = C.getTypeSize(OldType);
6891 if (HasBits >= Bits)
6892 return ExprResult(E);
6893 // OK to convert to signed, because new type has more bits than old.
6894 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
6895 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
6896 true);
6897}
6898
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006899/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006900/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006901static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006902 if (E == nullptr)
6903 return false;
6904 llvm::APSInt Result;
6905 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
6906 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
6907 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006908}
6909
Alexey Bataev5a3af132016-03-29 08:58:54 +00006910/// Build preinits statement for the given declarations.
6911static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00006912 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006913 if (!PreInits.empty()) {
6914 return new (Context) DeclStmt(
6915 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
6916 SourceLocation(), SourceLocation());
6917 }
6918 return nullptr;
6919}
6920
6921/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00006922static Stmt *
6923buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00006924 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006925 if (!Captures.empty()) {
6926 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00006927 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006928 PreInits.push_back(Pair.second->getDecl());
6929 return buildPreInits(Context, PreInits);
6930 }
6931 return nullptr;
6932}
6933
6934/// Build postupdate expression for the given list of postupdates expressions.
6935static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
6936 Expr *PostUpdate = nullptr;
6937 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006938 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006939 Expr *ConvE = S.BuildCStyleCastExpr(
6940 E->getExprLoc(),
6941 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
6942 E->getExprLoc(), E)
6943 .get();
6944 PostUpdate = PostUpdate
6945 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
6946 PostUpdate, ConvE)
6947 .get()
6948 : ConvE;
6949 }
6950 }
6951 return PostUpdate;
6952}
6953
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006954/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00006955/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
6956/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006957static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00006958checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00006959 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
6960 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00006961 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00006962 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006963 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006964 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006965 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006966 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006967 if (!CollapseLoopCountExpr->isValueDependent() &&
6968 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006969 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006970 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006971 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006972 return 1;
6973 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00006974 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006975 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006976 if (OrderedLoopCountExpr) {
6977 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006978 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006979 if (!OrderedLoopCountExpr->isValueDependent() &&
6980 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
6981 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006982 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006983 if (Result.getLimitedValue() < NestedLoopCount) {
6984 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6985 diag::err_omp_wrong_ordered_loop_count)
6986 << OrderedLoopCountExpr->getSourceRange();
6987 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6988 diag::note_collapse_loop_count)
6989 << CollapseLoopCountExpr->getSourceRange();
6990 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006991 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006992 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006993 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006994 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006995 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006996 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006997 // This is helper routine for loop directives (e.g., 'for', 'simd',
6998 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006999 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007000 SmallVector<LoopIterationSpace, 4> IterSpaces(
7001 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007002 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007003 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007004 if (checkOpenMPIterationSpace(
7005 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7006 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007007 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007008 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007009 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007010 // OpenMP [2.8.1, simd construct, Restrictions]
7011 // All loops associated with the construct must be perfectly nested; that
7012 // is, there must be no intervening code nor any OpenMP directive between
7013 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007014 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7015 CurStmt = For->getBody();
7016 } else {
7017 assert(isa<CXXForRangeStmt>(CurStmt) &&
7018 "Expected canonical for or range-based for loops.");
7019 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7020 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007021 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7022 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007023 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007024 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7025 if (checkOpenMPIterationSpace(
7026 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7027 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007028 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007029 return 0;
7030 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7031 // Handle initialization of captured loop iterator variables.
7032 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7033 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7034 Captures[DRE] = DRE;
7035 }
7036 }
7037 // Move on to the next nested for loop, or to the loop body.
7038 // OpenMP [2.8.1, simd construct, Restrictions]
7039 // All loops associated with the construct must be perfectly nested; that
7040 // is, there must be no intervening code nor any OpenMP directive between
7041 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007042 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7043 CurStmt = For->getBody();
7044 } else {
7045 assert(isa<CXXForRangeStmt>(CurStmt) &&
7046 "Expected canonical for or range-based for loops.");
7047 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7048 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007049 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7050 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007051 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007052
Alexander Musmana5f070a2014-10-01 06:03:56 +00007053 Built.clear(/* size */ NestedLoopCount);
7054
7055 if (SemaRef.CurContext->isDependentContext())
7056 return NestedLoopCount;
7057
7058 // An example of what is generated for the following code:
7059 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007060 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007061 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007062 // for (k = 0; k < NK; ++k)
7063 // for (j = J0; j < NJ; j+=2) {
7064 // <loop body>
7065 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007066 //
7067 // We generate the code below.
7068 // Note: the loop body may be outlined in CodeGen.
7069 // Note: some counters may be C++ classes, operator- is used to find number of
7070 // iterations and operator+= to calculate counter value.
7071 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7072 // or i64 is currently supported).
7073 //
7074 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7075 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7076 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7077 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7078 // // similar updates for vars in clauses (e.g. 'linear')
7079 // <loop body (using local i and j)>
7080 // }
7081 // i = NI; // assign final values of counters
7082 // j = NJ;
7083 //
7084
7085 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7086 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007087 // Precondition tests if there is at least one iteration (all conditions are
7088 // true).
7089 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007090 Expr *N0 = IterSpaces[0].NumIterations;
7091 ExprResult LastIteration32 =
7092 widenIterationCount(/*Bits=*/32,
7093 SemaRef
7094 .PerformImplicitConversion(
7095 N0->IgnoreImpCasts(), N0->getType(),
7096 Sema::AA_Converting, /*AllowExplicit=*/true)
7097 .get(),
7098 SemaRef);
7099 ExprResult LastIteration64 = widenIterationCount(
7100 /*Bits=*/64,
7101 SemaRef
7102 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7103 Sema::AA_Converting,
7104 /*AllowExplicit=*/true)
7105 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007106 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007107
7108 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7109 return NestedLoopCount;
7110
Alexey Bataeve3727102018-04-18 15:57:46 +00007111 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007112 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7113
7114 Scope *CurScope = DSA.getCurScope();
7115 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007116 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007117 PreCond =
7118 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7119 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007120 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007121 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007122 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007123 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7124 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007125 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007126 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007127 SemaRef
7128 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7129 Sema::AA_Converting,
7130 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007131 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007132 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007133 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007134 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007135 SemaRef
7136 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7137 Sema::AA_Converting,
7138 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007139 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007140 }
7141
7142 // Choose either the 32-bit or 64-bit version.
7143 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007144 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7145 (LastIteration32.isUsable() &&
7146 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7147 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7148 fitsInto(
7149 /*Bits=*/32,
7150 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7151 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007152 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007153 QualType VType = LastIteration.get()->getType();
7154 QualType RealVType = VType;
7155 QualType StrideVType = VType;
7156 if (isOpenMPTaskLoopDirective(DKind)) {
7157 VType =
7158 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7159 StrideVType =
7160 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7161 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007162
7163 if (!LastIteration.isUsable())
7164 return 0;
7165
7166 // Save the number of iterations.
7167 ExprResult NumIterations = LastIteration;
7168 {
7169 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007170 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7171 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007172 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7173 if (!LastIteration.isUsable())
7174 return 0;
7175 }
7176
7177 // Calculate the last iteration number beforehand instead of doing this on
7178 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7179 llvm::APSInt Result;
7180 bool IsConstant =
7181 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7182 ExprResult CalcLastIteration;
7183 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007184 ExprResult SaveRef =
7185 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007186 LastIteration = SaveRef;
7187
7188 // Prepare SaveRef + 1.
7189 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007190 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007191 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7192 if (!NumIterations.isUsable())
7193 return 0;
7194 }
7195
7196 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7197
David Majnemer9d168222016-08-05 17:44:54 +00007198 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007199 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007200 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7201 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007202 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007203 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7204 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007205 SemaRef.AddInitializerToDecl(LBDecl,
7206 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7207 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007208
7209 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007210 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7211 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007212 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007213 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007214
7215 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7216 // This will be used to implement clause 'lastprivate'.
7217 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007218 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7219 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007220 SemaRef.AddInitializerToDecl(ILDecl,
7221 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7222 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007223
7224 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007225 VarDecl *STDecl =
7226 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7227 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007228 SemaRef.AddInitializerToDecl(STDecl,
7229 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7230 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007231
7232 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007233 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007234 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7235 UB.get(), LastIteration.get());
7236 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007237 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7238 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007239 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7240 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007241 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007242
7243 // If we have a combined directive that combines 'distribute', 'for' or
7244 // 'simd' we need to be able to access the bounds of the schedule of the
7245 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7246 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7247 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007248 // Lower bound variable, initialized with zero.
7249 VarDecl *CombLBDecl =
7250 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7251 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7252 SemaRef.AddInitializerToDecl(
7253 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7254 /*DirectInit*/ false);
7255
7256 // Upper bound variable, initialized with last iteration number.
7257 VarDecl *CombUBDecl =
7258 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7259 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7260 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7261 /*DirectInit*/ false);
7262
7263 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7264 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7265 ExprResult CombCondOp =
7266 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7267 LastIteration.get(), CombUB.get());
7268 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7269 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007270 CombEUB =
7271 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007272
Alexey Bataeve3727102018-04-18 15:57:46 +00007273 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007274 // We expect to have at least 2 more parameters than the 'parallel'
7275 // directive does - the lower and upper bounds of the previous schedule.
7276 assert(CD->getNumParams() >= 4 &&
7277 "Unexpected number of parameters in loop combined directive");
7278
7279 // Set the proper type for the bounds given what we learned from the
7280 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007281 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7282 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007283
7284 // Previous lower and upper bounds are obtained from the region
7285 // parameters.
7286 PrevLB =
7287 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7288 PrevUB =
7289 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7290 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007291 }
7292
7293 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007294 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007295 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007296 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007297 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7298 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007299 Expr *RHS =
7300 (isOpenMPWorksharingDirective(DKind) ||
7301 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7302 ? LB.get()
7303 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007304 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007305 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007306
7307 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7308 Expr *CombRHS =
7309 (isOpenMPWorksharingDirective(DKind) ||
7310 isOpenMPTaskLoopDirective(DKind) ||
7311 isOpenMPDistributeDirective(DKind))
7312 ? CombLB.get()
7313 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7314 CombInit =
7315 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007316 CombInit =
7317 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007318 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007319 }
7320
Alexey Bataev316ccf62019-01-29 18:51:58 +00007321 bool UseStrictCompare =
7322 RealVType->hasUnsignedIntegerRepresentation() &&
7323 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7324 return LIS.IsStrictCompare;
7325 });
7326 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7327 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007328 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007329 Expr *BoundUB = UB.get();
7330 if (UseStrictCompare) {
7331 BoundUB =
7332 SemaRef
7333 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7334 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7335 .get();
7336 BoundUB =
7337 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7338 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007339 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007340 (isOpenMPWorksharingDirective(DKind) ||
7341 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007342 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7343 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7344 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007345 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7346 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007347 ExprResult CombDistCond;
7348 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007349 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7350 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007351 }
7352
Carlo Bertolliffafe102017-04-20 00:39:39 +00007353 ExprResult CombCond;
7354 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007355 Expr *BoundCombUB = CombUB.get();
7356 if (UseStrictCompare) {
7357 BoundCombUB =
7358 SemaRef
7359 .BuildBinOp(
7360 CurScope, CondLoc, BO_Add, BoundCombUB,
7361 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7362 .get();
7363 BoundCombUB =
7364 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7365 .get();
7366 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007367 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007368 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7369 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007370 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007371 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007372 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007373 ExprResult Inc =
7374 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7375 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7376 if (!Inc.isUsable())
7377 return 0;
7378 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007379 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007380 if (!Inc.isUsable())
7381 return 0;
7382
7383 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7384 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007385 // In combined construct, add combined version that use CombLB and CombUB
7386 // base variables for the update
7387 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007388 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7389 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007390 // LB + ST
7391 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7392 if (!NextLB.isUsable())
7393 return 0;
7394 // LB = LB + ST
7395 NextLB =
7396 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007397 NextLB =
7398 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007399 if (!NextLB.isUsable())
7400 return 0;
7401 // UB + ST
7402 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7403 if (!NextUB.isUsable())
7404 return 0;
7405 // UB = UB + ST
7406 NextUB =
7407 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007408 NextUB =
7409 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007410 if (!NextUB.isUsable())
7411 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007412 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7413 CombNextLB =
7414 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7415 if (!NextLB.isUsable())
7416 return 0;
7417 // LB = LB + ST
7418 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7419 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007420 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7421 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007422 if (!CombNextLB.isUsable())
7423 return 0;
7424 // UB + ST
7425 CombNextUB =
7426 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7427 if (!CombNextUB.isUsable())
7428 return 0;
7429 // UB = UB + ST
7430 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7431 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007432 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7433 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007434 if (!CombNextUB.isUsable())
7435 return 0;
7436 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007437 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007438
Carlo Bertolliffafe102017-04-20 00:39:39 +00007439 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007440 // directive with for as IV = IV + ST; ensure upper bound expression based
7441 // on PrevUB instead of NumIterations - used to implement 'for' when found
7442 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007443 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007444 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007445 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007446 DistCond = SemaRef.BuildBinOp(
7447 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007448 assert(DistCond.isUsable() && "distribute cond expr was not built");
7449
7450 DistInc =
7451 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7452 assert(DistInc.isUsable() && "distribute inc expr was not built");
7453 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7454 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007455 DistInc =
7456 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007457 assert(DistInc.isUsable() && "distribute inc expr was not built");
7458
7459 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7460 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007461 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007462 ExprResult IsUBGreater =
7463 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7464 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7465 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7466 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7467 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007468 PrevEUB =
7469 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007470
Alexey Bataev316ccf62019-01-29 18:51:58 +00007471 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7472 // parallel for is in combination with a distribute directive with
7473 // schedule(static, 1)
7474 Expr *BoundPrevUB = PrevUB.get();
7475 if (UseStrictCompare) {
7476 BoundPrevUB =
7477 SemaRef
7478 .BuildBinOp(
7479 CurScope, CondLoc, BO_Add, BoundPrevUB,
7480 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7481 .get();
7482 BoundPrevUB =
7483 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7484 .get();
7485 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007486 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007487 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7488 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007489 }
7490
Alexander Musmana5f070a2014-10-01 06:03:56 +00007491 // Build updates and final values of the loop counters.
7492 bool HasErrors = false;
7493 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007494 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007495 Built.Updates.resize(NestedLoopCount);
7496 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007497 Built.DependentCounters.resize(NestedLoopCount);
7498 Built.DependentInits.resize(NestedLoopCount);
7499 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007500 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007501 // We implement the following algorithm for obtaining the
7502 // original loop iteration variable values based on the
7503 // value of the collapsed loop iteration variable IV.
7504 //
7505 // Let n+1 be the number of collapsed loops in the nest.
7506 // Iteration variables (I0, I1, .... In)
7507 // Iteration counts (N0, N1, ... Nn)
7508 //
7509 // Acc = IV;
7510 //
7511 // To compute Ik for loop k, 0 <= k <= n, generate:
7512 // Prod = N(k+1) * N(k+2) * ... * Nn;
7513 // Ik = Acc / Prod;
7514 // Acc -= Ik * Prod;
7515 //
7516 ExprResult Acc = IV;
7517 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007518 LoopIterationSpace &IS = IterSpaces[Cnt];
7519 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007520 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007521
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007522 // Compute prod
7523 ExprResult Prod =
7524 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7525 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7526 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7527 IterSpaces[K].NumIterations);
7528
7529 // Iter = Acc / Prod
7530 // If there is at least one more inner loop to avoid
7531 // multiplication by 1.
7532 if (Cnt + 1 < NestedLoopCount)
7533 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7534 Acc.get(), Prod.get());
7535 else
7536 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007537 if (!Iter.isUsable()) {
7538 HasErrors = true;
7539 break;
7540 }
7541
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007542 // Update Acc:
7543 // Acc -= Iter * Prod
7544 // Check if there is at least one more inner loop to avoid
7545 // multiplication by 1.
7546 if (Cnt + 1 < NestedLoopCount)
7547 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7548 Iter.get(), Prod.get());
7549 else
7550 Prod = Iter;
7551 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7552 Acc.get(), Prod.get());
7553
Alexey Bataev39f915b82015-05-08 10:41:21 +00007554 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007555 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007556 DeclRefExpr *CounterVar = buildDeclRefExpr(
7557 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7558 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007559 ExprResult Init =
7560 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7561 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007562 if (!Init.isUsable()) {
7563 HasErrors = true;
7564 break;
7565 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007566 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007567 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007568 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007569 if (!Update.isUsable()) {
7570 HasErrors = true;
7571 break;
7572 }
7573
7574 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007575 ExprResult Final =
7576 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7577 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7578 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007579 if (!Final.isUsable()) {
7580 HasErrors = true;
7581 break;
7582 }
7583
Alexander Musmana5f070a2014-10-01 06:03:56 +00007584 if (!Update.isUsable() || !Final.isUsable()) {
7585 HasErrors = true;
7586 break;
7587 }
7588 // Save results
7589 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007590 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007591 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007592 Built.Updates[Cnt] = Update.get();
7593 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007594 Built.DependentCounters[Cnt] = nullptr;
7595 Built.DependentInits[Cnt] = nullptr;
7596 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007597 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007598 Built.DependentCounters[Cnt] =
7599 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7600 Built.DependentInits[Cnt] =
7601 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7602 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7603 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007604 }
7605 }
7606
7607 if (HasErrors)
7608 return 0;
7609
7610 // Save results
7611 Built.IterationVarRef = IV.get();
7612 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007613 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007614 Built.CalcLastIteration = SemaRef
7615 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007616 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007617 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007618 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007619 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007620 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007621 Built.Init = Init.get();
7622 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007623 Built.LB = LB.get();
7624 Built.UB = UB.get();
7625 Built.IL = IL.get();
7626 Built.ST = ST.get();
7627 Built.EUB = EUB.get();
7628 Built.NLB = NextLB.get();
7629 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007630 Built.PrevLB = PrevLB.get();
7631 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007632 Built.DistInc = DistInc.get();
7633 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007634 Built.DistCombinedFields.LB = CombLB.get();
7635 Built.DistCombinedFields.UB = CombUB.get();
7636 Built.DistCombinedFields.EUB = CombEUB.get();
7637 Built.DistCombinedFields.Init = CombInit.get();
7638 Built.DistCombinedFields.Cond = CombCond.get();
7639 Built.DistCombinedFields.NLB = CombNextLB.get();
7640 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007641 Built.DistCombinedFields.DistCond = CombDistCond.get();
7642 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007643
Alexey Bataevabfc0692014-06-25 06:52:00 +00007644 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007645}
7646
Alexey Bataev10e775f2015-07-30 11:36:16 +00007647static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007648 auto CollapseClauses =
7649 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7650 if (CollapseClauses.begin() != CollapseClauses.end())
7651 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007652 return nullptr;
7653}
7654
Alexey Bataev10e775f2015-07-30 11:36:16 +00007655static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007656 auto OrderedClauses =
7657 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7658 if (OrderedClauses.begin() != OrderedClauses.end())
7659 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007660 return nullptr;
7661}
7662
Kelvin Lic5609492016-07-15 04:39:07 +00007663static bool checkSimdlenSafelenSpecified(Sema &S,
7664 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007665 const OMPSafelenClause *Safelen = nullptr;
7666 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007667
Alexey Bataeve3727102018-04-18 15:57:46 +00007668 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007669 if (Clause->getClauseKind() == OMPC_safelen)
7670 Safelen = cast<OMPSafelenClause>(Clause);
7671 else if (Clause->getClauseKind() == OMPC_simdlen)
7672 Simdlen = cast<OMPSimdlenClause>(Clause);
7673 if (Safelen && Simdlen)
7674 break;
7675 }
7676
7677 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007678 const Expr *SimdlenLength = Simdlen->getSimdlen();
7679 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007680 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7681 SimdlenLength->isInstantiationDependent() ||
7682 SimdlenLength->containsUnexpandedParameterPack())
7683 return false;
7684 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7685 SafelenLength->isInstantiationDependent() ||
7686 SafelenLength->containsUnexpandedParameterPack())
7687 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007688 Expr::EvalResult SimdlenResult, SafelenResult;
7689 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7690 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7691 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7692 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007693 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7694 // If both simdlen and safelen clauses are specified, the value of the
7695 // simdlen parameter must be less than or equal to the value of the safelen
7696 // parameter.
7697 if (SimdlenRes > SafelenRes) {
7698 S.Diag(SimdlenLength->getExprLoc(),
7699 diag::err_omp_wrong_simdlen_safelen_values)
7700 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7701 return true;
7702 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007703 }
7704 return false;
7705}
7706
Alexey Bataeve3727102018-04-18 15:57:46 +00007707StmtResult
7708Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7709 SourceLocation StartLoc, SourceLocation EndLoc,
7710 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007711 if (!AStmt)
7712 return StmtError();
7713
7714 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007715 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007716 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7717 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007718 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007719 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7720 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007721 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007722 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007723
Alexander Musmana5f070a2014-10-01 06:03:56 +00007724 assert((CurContext->isDependentContext() || B.builtAll()) &&
7725 "omp simd loop exprs were not built");
7726
Alexander Musman3276a272015-03-21 10:12:56 +00007727 if (!CurContext->isDependentContext()) {
7728 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007729 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007730 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007731 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007732 B.NumIterations, *this, CurScope,
7733 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007734 return StmtError();
7735 }
7736 }
7737
Kelvin Lic5609492016-07-15 04:39:07 +00007738 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007739 return StmtError();
7740
Reid Kleckner87a31802018-03-12 21:43:02 +00007741 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007742 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7743 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007744}
7745
Alexey Bataeve3727102018-04-18 15:57:46 +00007746StmtResult
7747Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7748 SourceLocation StartLoc, SourceLocation EndLoc,
7749 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007750 if (!AStmt)
7751 return StmtError();
7752
7753 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007754 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007755 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7756 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007757 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007758 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7759 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007760 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007761 return StmtError();
7762
Alexander Musmana5f070a2014-10-01 06:03:56 +00007763 assert((CurContext->isDependentContext() || B.builtAll()) &&
7764 "omp for loop exprs were not built");
7765
Alexey Bataev54acd402015-08-04 11:18:19 +00007766 if (!CurContext->isDependentContext()) {
7767 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007768 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007769 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007770 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007771 B.NumIterations, *this, CurScope,
7772 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007773 return StmtError();
7774 }
7775 }
7776
Reid Kleckner87a31802018-03-12 21:43:02 +00007777 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007778 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007779 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007780}
7781
Alexander Musmanf82886e2014-09-18 05:12:34 +00007782StmtResult Sema::ActOnOpenMPForSimdDirective(
7783 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007784 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007785 if (!AStmt)
7786 return StmtError();
7787
7788 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007789 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007790 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7791 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007792 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007793 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007794 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7795 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007796 if (NestedLoopCount == 0)
7797 return StmtError();
7798
Alexander Musmanc6388682014-12-15 07:07:06 +00007799 assert((CurContext->isDependentContext() || B.builtAll()) &&
7800 "omp for simd loop exprs were not built");
7801
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007802 if (!CurContext->isDependentContext()) {
7803 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007804 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007805 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007806 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007807 B.NumIterations, *this, CurScope,
7808 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007809 return StmtError();
7810 }
7811 }
7812
Kelvin Lic5609492016-07-15 04:39:07 +00007813 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007814 return StmtError();
7815
Reid Kleckner87a31802018-03-12 21:43:02 +00007816 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007817 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7818 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007819}
7820
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007821StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7822 Stmt *AStmt,
7823 SourceLocation StartLoc,
7824 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007825 if (!AStmt)
7826 return StmtError();
7827
7828 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007829 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007830 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007831 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007832 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007833 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007834 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007835 return StmtError();
7836 // All associated statements must be '#pragma omp section' except for
7837 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007838 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007839 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7840 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007841 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007842 diag::err_omp_sections_substmt_not_section);
7843 return StmtError();
7844 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007845 cast<OMPSectionDirective>(SectionStmt)
7846 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007847 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007848 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007849 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007850 return StmtError();
7851 }
7852
Reid Kleckner87a31802018-03-12 21:43:02 +00007853 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007854
Alexey Bataev25e5b442015-09-15 12:52:43 +00007855 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7856 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007857}
7858
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007859StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
7860 SourceLocation StartLoc,
7861 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007862 if (!AStmt)
7863 return StmtError();
7864
7865 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007866
Reid Kleckner87a31802018-03-12 21:43:02 +00007867 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00007868 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007869
Alexey Bataev25e5b442015-09-15 12:52:43 +00007870 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
7871 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007872}
7873
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007874StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7875 Stmt *AStmt,
7876 SourceLocation StartLoc,
7877 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007878 if (!AStmt)
7879 return StmtError();
7880
7881 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00007882
Reid Kleckner87a31802018-03-12 21:43:02 +00007883 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00007884
Alexey Bataev3255bf32015-01-19 05:20:46 +00007885 // OpenMP [2.7.3, single Construct, Restrictions]
7886 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00007887 const OMPClause *Nowait = nullptr;
7888 const OMPClause *Copyprivate = nullptr;
7889 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00007890 if (Clause->getClauseKind() == OMPC_nowait)
7891 Nowait = Clause;
7892 else if (Clause->getClauseKind() == OMPC_copyprivate)
7893 Copyprivate = Clause;
7894 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007895 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00007896 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007897 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00007898 return StmtError();
7899 }
7900 }
7901
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007902 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7903}
7904
Alexander Musman80c22892014-07-17 08:54:58 +00007905StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
7906 SourceLocation StartLoc,
7907 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007908 if (!AStmt)
7909 return StmtError();
7910
7911 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00007912
Reid Kleckner87a31802018-03-12 21:43:02 +00007913 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00007914
7915 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
7916}
7917
Alexey Bataev28c75412015-12-15 08:19:24 +00007918StmtResult Sema::ActOnOpenMPCriticalDirective(
7919 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
7920 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007921 if (!AStmt)
7922 return StmtError();
7923
7924 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007925
Alexey Bataev28c75412015-12-15 08:19:24 +00007926 bool ErrorFound = false;
7927 llvm::APSInt Hint;
7928 SourceLocation HintLoc;
7929 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007930 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007931 if (C->getClauseKind() == OMPC_hint) {
7932 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007933 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00007934 ErrorFound = true;
7935 }
7936 Expr *E = cast<OMPHintClause>(C)->getHint();
7937 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00007938 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007939 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007940 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00007941 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007942 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00007943 }
7944 }
7945 }
7946 if (ErrorFound)
7947 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007948 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00007949 if (Pair.first && DirName.getName() && !DependentHint) {
7950 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
7951 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00007952 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00007953 Diag(HintLoc, diag::note_omp_critical_hint_here)
7954 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007955 else
Alexey Bataev28c75412015-12-15 08:19:24 +00007956 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00007957 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007958 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00007959 << 1
7960 << C->getHint()->EvaluateKnownConstInt(Context).toString(
7961 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007962 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007963 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00007964 }
Alexey Bataev28c75412015-12-15 08:19:24 +00007965 }
7966 }
7967
Reid Kleckner87a31802018-03-12 21:43:02 +00007968 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007969
Alexey Bataev28c75412015-12-15 08:19:24 +00007970 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
7971 Clauses, AStmt);
7972 if (!Pair.first && DirName.getName() && !DependentHint)
7973 DSAStack->addCriticalWithHint(Dir, Hint);
7974 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007975}
7976
Alexey Bataev4acb8592014-07-07 13:01:15 +00007977StmtResult Sema::ActOnOpenMPParallelForDirective(
7978 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007979 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007980 if (!AStmt)
7981 return StmtError();
7982
Alexey Bataeve3727102018-04-18 15:57:46 +00007983 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007984 // 1.2.2 OpenMP Language Terminology
7985 // Structured block - An executable statement with a single entry at the
7986 // top and a single exit at the bottom.
7987 // The point of exit cannot be a branch out of the structured block.
7988 // longjmp() and throw() must not violate the entry/exit criteria.
7989 CS->getCapturedDecl()->setNothrow();
7990
Alexander Musmanc6388682014-12-15 07:07:06 +00007991 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007992 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7993 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007994 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007995 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007996 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7997 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007998 if (NestedLoopCount == 0)
7999 return StmtError();
8000
Alexander Musmana5f070a2014-10-01 06:03:56 +00008001 assert((CurContext->isDependentContext() || B.builtAll()) &&
8002 "omp parallel for loop exprs were not built");
8003
Alexey Bataev54acd402015-08-04 11:18:19 +00008004 if (!CurContext->isDependentContext()) {
8005 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008006 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008007 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008008 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008009 B.NumIterations, *this, CurScope,
8010 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008011 return StmtError();
8012 }
8013 }
8014
Reid Kleckner87a31802018-03-12 21:43:02 +00008015 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008016 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008017 NestedLoopCount, Clauses, AStmt, B,
8018 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008019}
8020
Alexander Musmane4e893b2014-09-23 09:33:00 +00008021StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8022 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008023 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008024 if (!AStmt)
8025 return StmtError();
8026
Alexey Bataeve3727102018-04-18 15:57:46 +00008027 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008028 // 1.2.2 OpenMP Language Terminology
8029 // Structured block - An executable statement with a single entry at the
8030 // top and a single exit at the bottom.
8031 // The point of exit cannot be a branch out of the structured block.
8032 // longjmp() and throw() must not violate the entry/exit criteria.
8033 CS->getCapturedDecl()->setNothrow();
8034
Alexander Musmanc6388682014-12-15 07:07:06 +00008035 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008036 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8037 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008038 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008039 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008040 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8041 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008042 if (NestedLoopCount == 0)
8043 return StmtError();
8044
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008045 if (!CurContext->isDependentContext()) {
8046 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008047 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008048 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008049 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008050 B.NumIterations, *this, CurScope,
8051 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008052 return StmtError();
8053 }
8054 }
8055
Kelvin Lic5609492016-07-15 04:39:07 +00008056 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008057 return StmtError();
8058
Reid Kleckner87a31802018-03-12 21:43:02 +00008059 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008060 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008061 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008062}
8063
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008064StmtResult
8065Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8066 Stmt *AStmt, SourceLocation StartLoc,
8067 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008068 if (!AStmt)
8069 return StmtError();
8070
8071 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008072 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008073 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008074 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008075 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008076 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008077 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008078 return StmtError();
8079 // All associated statements must be '#pragma omp section' except for
8080 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008081 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008082 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8083 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008084 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008085 diag::err_omp_parallel_sections_substmt_not_section);
8086 return StmtError();
8087 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008088 cast<OMPSectionDirective>(SectionStmt)
8089 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008090 }
8091 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008092 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008093 diag::err_omp_parallel_sections_not_compound_stmt);
8094 return StmtError();
8095 }
8096
Reid Kleckner87a31802018-03-12 21:43:02 +00008097 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008098
Alexey Bataev25e5b442015-09-15 12:52:43 +00008099 return OMPParallelSectionsDirective::Create(
8100 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008101}
8102
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008103StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8104 Stmt *AStmt, SourceLocation StartLoc,
8105 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008106 if (!AStmt)
8107 return StmtError();
8108
David Majnemer9d168222016-08-05 17:44:54 +00008109 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008110 // 1.2.2 OpenMP Language Terminology
8111 // Structured block - An executable statement with a single entry at the
8112 // top and a single exit at the bottom.
8113 // The point of exit cannot be a branch out of the structured block.
8114 // longjmp() and throw() must not violate the entry/exit criteria.
8115 CS->getCapturedDecl()->setNothrow();
8116
Reid Kleckner87a31802018-03-12 21:43:02 +00008117 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008118
Alexey Bataev25e5b442015-09-15 12:52:43 +00008119 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8120 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008121}
8122
Alexey Bataev68446b72014-07-18 07:47:19 +00008123StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8124 SourceLocation EndLoc) {
8125 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8126}
8127
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008128StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8129 SourceLocation EndLoc) {
8130 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8131}
8132
Alexey Bataev2df347a2014-07-18 10:17:07 +00008133StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8134 SourceLocation EndLoc) {
8135 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8136}
8137
Alexey Bataev169d96a2017-07-18 20:17:46 +00008138StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8139 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008140 SourceLocation StartLoc,
8141 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008142 if (!AStmt)
8143 return StmtError();
8144
8145 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008146
Reid Kleckner87a31802018-03-12 21:43:02 +00008147 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008148
Alexey Bataev169d96a2017-07-18 20:17:46 +00008149 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008150 AStmt,
8151 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008152}
8153
Alexey Bataev6125da92014-07-21 11:26:11 +00008154StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8155 SourceLocation StartLoc,
8156 SourceLocation EndLoc) {
8157 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8158 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8159}
8160
Alexey Bataev346265e2015-09-25 10:37:12 +00008161StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8162 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008163 SourceLocation StartLoc,
8164 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008165 const OMPClause *DependFound = nullptr;
8166 const OMPClause *DependSourceClause = nullptr;
8167 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008168 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008169 const OMPThreadsClause *TC = nullptr;
8170 const OMPSIMDClause *SC = nullptr;
8171 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008172 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8173 DependFound = C;
8174 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8175 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008176 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008177 << getOpenMPDirectiveName(OMPD_ordered)
8178 << getOpenMPClauseName(OMPC_depend) << 2;
8179 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008180 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008181 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008182 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008183 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008184 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008185 << 0;
8186 ErrorFound = true;
8187 }
8188 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8189 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008190 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008191 << 1;
8192 ErrorFound = true;
8193 }
8194 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008195 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008196 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008197 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008198 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008199 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008200 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008201 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008202 if (!ErrorFound && !SC &&
8203 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008204 // OpenMP [2.8.1,simd Construct, Restrictions]
8205 // An ordered construct with the simd clause is the only OpenMP construct
8206 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008207 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8208 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008209 ErrorFound = true;
8210 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008211 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008212 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8213 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008214 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008215 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008216 diag::err_omp_ordered_directive_without_param);
8217 ErrorFound = true;
8218 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008219 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008220 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008221 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8222 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008223 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008224 ErrorFound = true;
8225 }
8226 }
8227 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008228 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008229
8230 if (AStmt) {
8231 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8232
Reid Kleckner87a31802018-03-12 21:43:02 +00008233 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008234 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008235
8236 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008237}
8238
Alexey Bataev1d160b12015-03-13 12:27:31 +00008239namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008240/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008241/// construct.
8242class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008243 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008244 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008245 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008246 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008247 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008248 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008249 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008250 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008251 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008252 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008253 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008254 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008255 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008256 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008257 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008258 /// expression.
8259 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008260 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008261 /// part.
8262 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008263 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008264 NoError
8265 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008266 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008267 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008268 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008269 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008270 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008271 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008272 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008273 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008274 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008275 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8276 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8277 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008278 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008279 /// important for non-associative operations.
8280 bool IsXLHSInRHSPart;
8281 BinaryOperatorKind Op;
8282 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008283 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008284 /// if it is a prefix unary operation.
8285 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008286
8287public:
8288 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008289 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008290 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008291 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008292 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008293 /// expression. If DiagId and NoteId == 0, then only check is performed
8294 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008295 /// \param DiagId Diagnostic which should be emitted if error is found.
8296 /// \param NoteId Diagnostic note for the main error message.
8297 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008298 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008299 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008300 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008301 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008302 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008303 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008304 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8305 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8306 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008307 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008308 /// false otherwise.
8309 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008311 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008312 /// if it is a prefix unary operation.
8313 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8314
Alexey Bataev1d160b12015-03-13 12:27:31 +00008315private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008316 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8317 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008318};
8319} // namespace
8320
8321bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8322 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8323 ExprAnalysisErrorCode ErrorFound = NoError;
8324 SourceLocation ErrorLoc, NoteLoc;
8325 SourceRange ErrorRange, NoteRange;
8326 // Allowed constructs are:
8327 // x = x binop expr;
8328 // x = expr binop x;
8329 if (AtomicBinOp->getOpcode() == BO_Assign) {
8330 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008331 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008332 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8333 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8334 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8335 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008336 Op = AtomicInnerBinOp->getOpcode();
8337 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008338 Expr *LHS = AtomicInnerBinOp->getLHS();
8339 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008340 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8341 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8342 /*Canonical=*/true);
8343 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8344 /*Canonical=*/true);
8345 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8346 /*Canonical=*/true);
8347 if (XId == LHSId) {
8348 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008349 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008350 } else if (XId == RHSId) {
8351 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008352 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008353 } else {
8354 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8355 ErrorRange = AtomicInnerBinOp->getSourceRange();
8356 NoteLoc = X->getExprLoc();
8357 NoteRange = X->getSourceRange();
8358 ErrorFound = NotAnUpdateExpression;
8359 }
8360 } else {
8361 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8362 ErrorRange = AtomicInnerBinOp->getSourceRange();
8363 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8364 NoteRange = SourceRange(NoteLoc, NoteLoc);
8365 ErrorFound = NotABinaryOperator;
8366 }
8367 } else {
8368 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8369 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8370 ErrorFound = NotABinaryExpression;
8371 }
8372 } else {
8373 ErrorLoc = AtomicBinOp->getExprLoc();
8374 ErrorRange = AtomicBinOp->getSourceRange();
8375 NoteLoc = AtomicBinOp->getOperatorLoc();
8376 NoteRange = SourceRange(NoteLoc, NoteLoc);
8377 ErrorFound = NotAnAssignmentOp;
8378 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008379 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008380 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8381 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8382 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008383 }
8384 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008385 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008386 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008387}
8388
8389bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8390 unsigned NoteId) {
8391 ExprAnalysisErrorCode ErrorFound = NoError;
8392 SourceLocation ErrorLoc, NoteLoc;
8393 SourceRange ErrorRange, NoteRange;
8394 // Allowed constructs are:
8395 // x++;
8396 // x--;
8397 // ++x;
8398 // --x;
8399 // x binop= expr;
8400 // x = x binop expr;
8401 // x = expr binop x;
8402 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8403 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8404 if (AtomicBody->getType()->isScalarType() ||
8405 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008406 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008407 AtomicBody->IgnoreParenImpCasts())) {
8408 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008409 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008410 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008411 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008412 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008413 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008414 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008415 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8416 AtomicBody->IgnoreParenImpCasts())) {
8417 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008418 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008419 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008420 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008421 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008422 // Check for Unary Operation
8423 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008424 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008425 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8426 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008427 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008428 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8429 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008430 } else {
8431 ErrorFound = NotAnUnaryIncDecExpression;
8432 ErrorLoc = AtomicUnaryOp->getExprLoc();
8433 ErrorRange = AtomicUnaryOp->getSourceRange();
8434 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8435 NoteRange = SourceRange(NoteLoc, NoteLoc);
8436 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008437 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008438 ErrorFound = NotABinaryOrUnaryExpression;
8439 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8440 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8441 }
8442 } else {
8443 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008444 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008445 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8446 }
8447 } else {
8448 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008449 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008450 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8451 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008452 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008453 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8454 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8455 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008456 }
8457 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008458 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008459 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008460 // Build an update expression of form 'OpaqueValueExpr(x) binop
8461 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8462 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8463 auto *OVEX = new (SemaRef.getASTContext())
8464 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8465 auto *OVEExpr = new (SemaRef.getASTContext())
8466 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008467 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008468 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8469 IsXLHSInRHSPart ? OVEExpr : OVEX);
8470 if (Update.isInvalid())
8471 return true;
8472 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8473 Sema::AA_Casting);
8474 if (Update.isInvalid())
8475 return true;
8476 UpdateExpr = Update.get();
8477 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008478 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008479}
8480
Alexey Bataev0162e452014-07-22 10:10:35 +00008481StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8482 Stmt *AStmt,
8483 SourceLocation StartLoc,
8484 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008485 if (!AStmt)
8486 return StmtError();
8487
David Majnemer9d168222016-08-05 17:44:54 +00008488 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008489 // 1.2.2 OpenMP Language Terminology
8490 // Structured block - An executable statement with a single entry at the
8491 // top and a single exit at the bottom.
8492 // The point of exit cannot be a branch out of the structured block.
8493 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008494 OpenMPClauseKind AtomicKind = OMPC_unknown;
8495 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008496 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008497 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008498 C->getClauseKind() == OMPC_update ||
8499 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008500 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008501 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008502 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008503 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8504 << getOpenMPClauseName(AtomicKind);
8505 } else {
8506 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008507 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008508 }
8509 }
8510 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008511
Alexey Bataeve3727102018-04-18 15:57:46 +00008512 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008513 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8514 Body = EWC->getSubExpr();
8515
Alexey Bataev62cec442014-11-18 10:14:22 +00008516 Expr *X = nullptr;
8517 Expr *V = nullptr;
8518 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008519 Expr *UE = nullptr;
8520 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008521 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008522 // OpenMP [2.12.6, atomic Construct]
8523 // In the next expressions:
8524 // * x and v (as applicable) are both l-value expressions with scalar type.
8525 // * During the execution of an atomic region, multiple syntactic
8526 // occurrences of x must designate the same storage location.
8527 // * Neither of v and expr (as applicable) may access the storage location
8528 // designated by x.
8529 // * Neither of x and expr (as applicable) may access the storage location
8530 // designated by v.
8531 // * expr is an expression with scalar type.
8532 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8533 // * binop, binop=, ++, and -- are not overloaded operators.
8534 // * The expression x binop expr must be numerically equivalent to x binop
8535 // (expr). This requirement is satisfied if the operators in expr have
8536 // precedence greater than binop, or by using parentheses around expr or
8537 // subexpressions of expr.
8538 // * The expression expr binop x must be numerically equivalent to (expr)
8539 // binop x. This requirement is satisfied if the operators in expr have
8540 // precedence equal to or greater than binop, or by using parentheses around
8541 // expr or subexpressions of expr.
8542 // * For forms that allow multiple occurrences of x, the number of times
8543 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008544 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008545 enum {
8546 NotAnExpression,
8547 NotAnAssignmentOp,
8548 NotAScalarType,
8549 NotAnLValue,
8550 NoError
8551 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008552 SourceLocation ErrorLoc, NoteLoc;
8553 SourceRange ErrorRange, NoteRange;
8554 // If clause is read:
8555 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008556 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8557 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008558 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8559 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8560 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8561 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8562 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8563 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8564 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008565 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008566 ErrorFound = NotAnLValue;
8567 ErrorLoc = AtomicBinOp->getExprLoc();
8568 ErrorRange = AtomicBinOp->getSourceRange();
8569 NoteLoc = NotLValueExpr->getExprLoc();
8570 NoteRange = NotLValueExpr->getSourceRange();
8571 }
8572 } else if (!X->isInstantiationDependent() ||
8573 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008574 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008575 (X->isInstantiationDependent() || X->getType()->isScalarType())
8576 ? V
8577 : X;
8578 ErrorFound = NotAScalarType;
8579 ErrorLoc = AtomicBinOp->getExprLoc();
8580 ErrorRange = AtomicBinOp->getSourceRange();
8581 NoteLoc = NotScalarExpr->getExprLoc();
8582 NoteRange = NotScalarExpr->getSourceRange();
8583 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008584 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008585 ErrorFound = NotAnAssignmentOp;
8586 ErrorLoc = AtomicBody->getExprLoc();
8587 ErrorRange = AtomicBody->getSourceRange();
8588 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8589 : AtomicBody->getExprLoc();
8590 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8591 : AtomicBody->getSourceRange();
8592 }
8593 } else {
8594 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008595 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008596 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008597 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008598 if (ErrorFound != NoError) {
8599 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8600 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008601 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8602 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008603 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008604 }
8605 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008606 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008607 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008608 enum {
8609 NotAnExpression,
8610 NotAnAssignmentOp,
8611 NotAScalarType,
8612 NotAnLValue,
8613 NoError
8614 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008615 SourceLocation ErrorLoc, NoteLoc;
8616 SourceRange ErrorRange, NoteRange;
8617 // If clause is write:
8618 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008619 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8620 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008621 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8622 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008623 X = AtomicBinOp->getLHS();
8624 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008625 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8626 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8627 if (!X->isLValue()) {
8628 ErrorFound = NotAnLValue;
8629 ErrorLoc = AtomicBinOp->getExprLoc();
8630 ErrorRange = AtomicBinOp->getSourceRange();
8631 NoteLoc = X->getExprLoc();
8632 NoteRange = X->getSourceRange();
8633 }
8634 } else if (!X->isInstantiationDependent() ||
8635 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008636 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008637 (X->isInstantiationDependent() || X->getType()->isScalarType())
8638 ? E
8639 : X;
8640 ErrorFound = NotAScalarType;
8641 ErrorLoc = AtomicBinOp->getExprLoc();
8642 ErrorRange = AtomicBinOp->getSourceRange();
8643 NoteLoc = NotScalarExpr->getExprLoc();
8644 NoteRange = NotScalarExpr->getSourceRange();
8645 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008646 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008647 ErrorFound = NotAnAssignmentOp;
8648 ErrorLoc = AtomicBody->getExprLoc();
8649 ErrorRange = AtomicBody->getSourceRange();
8650 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8651 : AtomicBody->getExprLoc();
8652 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8653 : AtomicBody->getSourceRange();
8654 }
8655 } else {
8656 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008657 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008658 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008659 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008660 if (ErrorFound != NoError) {
8661 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8662 << ErrorRange;
8663 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8664 << NoteRange;
8665 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008666 }
8667 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008668 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008669 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008670 // If clause is update:
8671 // x++;
8672 // x--;
8673 // ++x;
8674 // --x;
8675 // x binop= expr;
8676 // x = x binop expr;
8677 // x = expr binop x;
8678 OpenMPAtomicUpdateChecker Checker(*this);
8679 if (Checker.checkStatement(
8680 Body, (AtomicKind == OMPC_update)
8681 ? diag::err_omp_atomic_update_not_expression_statement
8682 : diag::err_omp_atomic_not_expression_statement,
8683 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008684 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008685 if (!CurContext->isDependentContext()) {
8686 E = Checker.getExpr();
8687 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008688 UE = Checker.getUpdateExpr();
8689 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008690 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008691 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008692 enum {
8693 NotAnAssignmentOp,
8694 NotACompoundStatement,
8695 NotTwoSubstatements,
8696 NotASpecificExpression,
8697 NoError
8698 } ErrorFound = NoError;
8699 SourceLocation ErrorLoc, NoteLoc;
8700 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008701 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008702 // If clause is a capture:
8703 // v = x++;
8704 // v = x--;
8705 // v = ++x;
8706 // v = --x;
8707 // v = x binop= expr;
8708 // v = x = x binop expr;
8709 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008710 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008711 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8712 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8713 V = AtomicBinOp->getLHS();
8714 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8715 OpenMPAtomicUpdateChecker Checker(*this);
8716 if (Checker.checkStatement(
8717 Body, diag::err_omp_atomic_capture_not_expression_statement,
8718 diag::note_omp_atomic_update))
8719 return StmtError();
8720 E = Checker.getExpr();
8721 X = Checker.getX();
8722 UE = Checker.getUpdateExpr();
8723 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8724 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008725 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008726 ErrorLoc = AtomicBody->getExprLoc();
8727 ErrorRange = AtomicBody->getSourceRange();
8728 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8729 : AtomicBody->getExprLoc();
8730 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8731 : AtomicBody->getSourceRange();
8732 ErrorFound = NotAnAssignmentOp;
8733 }
8734 if (ErrorFound != NoError) {
8735 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8736 << ErrorRange;
8737 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8738 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008739 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008740 if (CurContext->isDependentContext())
8741 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008742 } else {
8743 // If clause is a capture:
8744 // { v = x; x = expr; }
8745 // { v = x; x++; }
8746 // { v = x; x--; }
8747 // { v = x; ++x; }
8748 // { v = x; --x; }
8749 // { v = x; x binop= expr; }
8750 // { v = x; x = x binop expr; }
8751 // { v = x; x = expr binop x; }
8752 // { x++; v = x; }
8753 // { x--; v = x; }
8754 // { ++x; v = x; }
8755 // { --x; v = x; }
8756 // { x binop= expr; v = x; }
8757 // { x = x binop expr; v = x; }
8758 // { x = expr binop x; v = x; }
8759 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8760 // Check that this is { expr1; expr2; }
8761 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008762 Stmt *First = CS->body_front();
8763 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008764 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8765 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8766 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8767 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8768 // Need to find what subexpression is 'v' and what is 'x'.
8769 OpenMPAtomicUpdateChecker Checker(*this);
8770 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8771 BinaryOperator *BinOp = nullptr;
8772 if (IsUpdateExprFound) {
8773 BinOp = dyn_cast<BinaryOperator>(First);
8774 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8775 }
8776 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8777 // { v = x; x++; }
8778 // { v = x; x--; }
8779 // { v = x; ++x; }
8780 // { v = x; --x; }
8781 // { v = x; x binop= expr; }
8782 // { v = x; x = x binop expr; }
8783 // { v = x; x = expr binop x; }
8784 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008785 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008786 llvm::FoldingSetNodeID XId, PossibleXId;
8787 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8788 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8789 IsUpdateExprFound = XId == PossibleXId;
8790 if (IsUpdateExprFound) {
8791 V = BinOp->getLHS();
8792 X = Checker.getX();
8793 E = Checker.getExpr();
8794 UE = Checker.getUpdateExpr();
8795 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008796 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008797 }
8798 }
8799 if (!IsUpdateExprFound) {
8800 IsUpdateExprFound = !Checker.checkStatement(First);
8801 BinOp = nullptr;
8802 if (IsUpdateExprFound) {
8803 BinOp = dyn_cast<BinaryOperator>(Second);
8804 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8805 }
8806 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8807 // { x++; v = x; }
8808 // { x--; v = x; }
8809 // { ++x; v = x; }
8810 // { --x; v = x; }
8811 // { x binop= expr; v = x; }
8812 // { x = x binop expr; v = x; }
8813 // { x = expr binop x; v = x; }
8814 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008815 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008816 llvm::FoldingSetNodeID XId, PossibleXId;
8817 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8818 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8819 IsUpdateExprFound = XId == PossibleXId;
8820 if (IsUpdateExprFound) {
8821 V = BinOp->getLHS();
8822 X = Checker.getX();
8823 E = Checker.getExpr();
8824 UE = Checker.getUpdateExpr();
8825 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008826 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008827 }
8828 }
8829 }
8830 if (!IsUpdateExprFound) {
8831 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00008832 auto *FirstExpr = dyn_cast<Expr>(First);
8833 auto *SecondExpr = dyn_cast<Expr>(Second);
8834 if (!FirstExpr || !SecondExpr ||
8835 !(FirstExpr->isInstantiationDependent() ||
8836 SecondExpr->isInstantiationDependent())) {
8837 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
8838 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008839 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00008840 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008841 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008842 NoteRange = ErrorRange = FirstBinOp
8843 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00008844 : SourceRange(ErrorLoc, ErrorLoc);
8845 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00008846 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
8847 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
8848 ErrorFound = NotAnAssignmentOp;
8849 NoteLoc = ErrorLoc = SecondBinOp
8850 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008851 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008852 NoteRange = ErrorRange =
8853 SecondBinOp ? SecondBinOp->getSourceRange()
8854 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00008855 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008856 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00008857 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00008858 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00008859 SecondBinOp->getLHS()->IgnoreParenImpCasts();
8860 llvm::FoldingSetNodeID X1Id, X2Id;
8861 PossibleXRHSInFirst->Profile(X1Id, Context,
8862 /*Canonical=*/true);
8863 PossibleXLHSInSecond->Profile(X2Id, Context,
8864 /*Canonical=*/true);
8865 IsUpdateExprFound = X1Id == X2Id;
8866 if (IsUpdateExprFound) {
8867 V = FirstBinOp->getLHS();
8868 X = SecondBinOp->getLHS();
8869 E = SecondBinOp->getRHS();
8870 UE = nullptr;
8871 IsXLHSInRHSPart = false;
8872 IsPostfixUpdate = true;
8873 } else {
8874 ErrorFound = NotASpecificExpression;
8875 ErrorLoc = FirstBinOp->getExprLoc();
8876 ErrorRange = FirstBinOp->getSourceRange();
8877 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
8878 NoteRange = SecondBinOp->getRHS()->getSourceRange();
8879 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008880 }
8881 }
8882 }
8883 }
8884 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008885 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008886 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008887 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008888 ErrorFound = NotTwoSubstatements;
8889 }
8890 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008891 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008892 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008893 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008894 ErrorFound = NotACompoundStatement;
8895 }
8896 if (ErrorFound != NoError) {
8897 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
8898 << ErrorRange;
8899 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8900 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008901 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008902 if (CurContext->isDependentContext())
8903 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00008904 }
Alexey Bataevdea47612014-07-23 07:46:59 +00008905 }
Alexey Bataev0162e452014-07-22 10:10:35 +00008906
Reid Kleckner87a31802018-03-12 21:43:02 +00008907 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00008908
Alexey Bataev62cec442014-11-18 10:14:22 +00008909 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00008910 X, V, E, UE, IsXLHSInRHSPart,
8911 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00008912}
8913
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008914StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8915 Stmt *AStmt,
8916 SourceLocation StartLoc,
8917 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008918 if (!AStmt)
8919 return StmtError();
8920
Alexey Bataeve3727102018-04-18 15:57:46 +00008921 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00008922 // 1.2.2 OpenMP Language Terminology
8923 // Structured block - An executable statement with a single entry at the
8924 // top and a single exit at the bottom.
8925 // The point of exit cannot be a branch out of the structured block.
8926 // longjmp() and throw() must not violate the entry/exit criteria.
8927 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008928 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
8929 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8930 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8931 // 1.2.2 OpenMP Language Terminology
8932 // Structured block - An executable statement with a single entry at the
8933 // top and a single exit at the bottom.
8934 // The point of exit cannot be a branch out of the structured block.
8935 // longjmp() and throw() must not violate the entry/exit criteria.
8936 CS->getCapturedDecl()->setNothrow();
8937 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008938
Alexey Bataev13314bf2014-10-09 04:18:56 +00008939 // OpenMP [2.16, Nesting of Regions]
8940 // If specified, a teams construct must be contained within a target
8941 // construct. That target construct must contain no statements or directives
8942 // outside of the teams construct.
8943 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008944 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008945 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008946 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00008947 auto I = CS->body_begin();
8948 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008949 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00008950 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
8951 OMPTeamsFound) {
8952
Alexey Bataev13314bf2014-10-09 04:18:56 +00008953 OMPTeamsFound = false;
8954 break;
8955 }
8956 ++I;
8957 }
8958 assert(I != CS->body_end() && "Not found statement");
8959 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00008960 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008961 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00008962 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00008963 }
8964 if (!OMPTeamsFound) {
8965 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
8966 Diag(DSAStack->getInnerTeamsRegionLoc(),
8967 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008968 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00008969 << isa<OMPExecutableDirective>(S);
8970 return StmtError();
8971 }
8972 }
8973
Reid Kleckner87a31802018-03-12 21:43:02 +00008974 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008975
8976 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8977}
8978
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008979StmtResult
8980Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8981 Stmt *AStmt, SourceLocation StartLoc,
8982 SourceLocation EndLoc) {
8983 if (!AStmt)
8984 return StmtError();
8985
Alexey Bataeve3727102018-04-18 15:57:46 +00008986 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008987 // 1.2.2 OpenMP Language Terminology
8988 // Structured block - An executable statement with a single entry at the
8989 // top and a single exit at the bottom.
8990 // The point of exit cannot be a branch out of the structured block.
8991 // longjmp() and throw() must not violate the entry/exit criteria.
8992 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008993 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
8994 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8995 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8996 // 1.2.2 OpenMP Language Terminology
8997 // Structured block - An executable statement with a single entry at the
8998 // top and a single exit at the bottom.
8999 // The point of exit cannot be a branch out of the structured block.
9000 // longjmp() and throw() must not violate the entry/exit criteria.
9001 CS->getCapturedDecl()->setNothrow();
9002 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009003
Reid Kleckner87a31802018-03-12 21:43:02 +00009004 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009005
9006 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9007 AStmt);
9008}
9009
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009010StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9011 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009012 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009013 if (!AStmt)
9014 return StmtError();
9015
Alexey Bataeve3727102018-04-18 15:57:46 +00009016 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009017 // 1.2.2 OpenMP Language Terminology
9018 // Structured block - An executable statement with a single entry at the
9019 // top and a single exit at the bottom.
9020 // The point of exit cannot be a branch out of the structured block.
9021 // longjmp() and throw() must not violate the entry/exit criteria.
9022 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009023 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9024 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9025 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9026 // 1.2.2 OpenMP Language Terminology
9027 // Structured block - An executable statement with a single entry at the
9028 // top and a single exit at the bottom.
9029 // The point of exit cannot be a branch out of the structured block.
9030 // longjmp() and throw() must not violate the entry/exit criteria.
9031 CS->getCapturedDecl()->setNothrow();
9032 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009033
9034 OMPLoopDirective::HelperExprs B;
9035 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9036 // define the nested loops number.
9037 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009038 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009039 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009040 VarsWithImplicitDSA, B);
9041 if (NestedLoopCount == 0)
9042 return StmtError();
9043
9044 assert((CurContext->isDependentContext() || B.builtAll()) &&
9045 "omp target parallel for loop exprs were not built");
9046
9047 if (!CurContext->isDependentContext()) {
9048 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009049 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009050 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009051 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009052 B.NumIterations, *this, CurScope,
9053 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009054 return StmtError();
9055 }
9056 }
9057
Reid Kleckner87a31802018-03-12 21:43:02 +00009058 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009059 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9060 NestedLoopCount, Clauses, AStmt,
9061 B, DSAStack->isCancelRegion());
9062}
9063
Alexey Bataev95b64a92017-05-30 16:00:04 +00009064/// Check for existence of a map clause in the list of clauses.
9065static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9066 const OpenMPClauseKind K) {
9067 return llvm::any_of(
9068 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9069}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009070
Alexey Bataev95b64a92017-05-30 16:00:04 +00009071template <typename... Params>
9072static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9073 const Params... ClauseTypes) {
9074 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009075}
9076
Michael Wong65f367f2015-07-21 13:44:28 +00009077StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9078 Stmt *AStmt,
9079 SourceLocation StartLoc,
9080 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009081 if (!AStmt)
9082 return StmtError();
9083
9084 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9085
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009086 // OpenMP [2.10.1, Restrictions, p. 97]
9087 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009088 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9089 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9090 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009091 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009092 return StmtError();
9093 }
9094
Reid Kleckner87a31802018-03-12 21:43:02 +00009095 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009096
9097 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9098 AStmt);
9099}
9100
Samuel Antaodf67fc42016-01-19 19:15:56 +00009101StmtResult
9102Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9103 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009104 SourceLocation EndLoc, Stmt *AStmt) {
9105 if (!AStmt)
9106 return StmtError();
9107
Alexey Bataeve3727102018-04-18 15:57:46 +00009108 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009109 // 1.2.2 OpenMP Language Terminology
9110 // Structured block - An executable statement with a single entry at the
9111 // top and a single exit at the bottom.
9112 // The point of exit cannot be a branch out of the structured block.
9113 // longjmp() and throw() must not violate the entry/exit criteria.
9114 CS->getCapturedDecl()->setNothrow();
9115 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9116 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9117 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9118 // 1.2.2 OpenMP Language Terminology
9119 // Structured block - An executable statement with a single entry at the
9120 // top and a single exit at the bottom.
9121 // The point of exit cannot be a branch out of the structured block.
9122 // longjmp() and throw() must not violate the entry/exit criteria.
9123 CS->getCapturedDecl()->setNothrow();
9124 }
9125
Samuel Antaodf67fc42016-01-19 19:15:56 +00009126 // OpenMP [2.10.2, Restrictions, p. 99]
9127 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009128 if (!hasClauses(Clauses, OMPC_map)) {
9129 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9130 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009131 return StmtError();
9132 }
9133
Alexey Bataev7828b252017-11-21 17:08:48 +00009134 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9135 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009136}
9137
Samuel Antao72590762016-01-19 20:04:50 +00009138StmtResult
9139Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9140 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009141 SourceLocation EndLoc, Stmt *AStmt) {
9142 if (!AStmt)
9143 return StmtError();
9144
Alexey Bataeve3727102018-04-18 15:57:46 +00009145 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009146 // 1.2.2 OpenMP Language Terminology
9147 // Structured block - An executable statement with a single entry at the
9148 // top and a single exit at the bottom.
9149 // The point of exit cannot be a branch out of the structured block.
9150 // longjmp() and throw() must not violate the entry/exit criteria.
9151 CS->getCapturedDecl()->setNothrow();
9152 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9153 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9154 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9155 // 1.2.2 OpenMP Language Terminology
9156 // Structured block - An executable statement with a single entry at the
9157 // top and a single exit at the bottom.
9158 // The point of exit cannot be a branch out of the structured block.
9159 // longjmp() and throw() must not violate the entry/exit criteria.
9160 CS->getCapturedDecl()->setNothrow();
9161 }
9162
Samuel Antao72590762016-01-19 20:04:50 +00009163 // OpenMP [2.10.3, Restrictions, p. 102]
9164 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009165 if (!hasClauses(Clauses, OMPC_map)) {
9166 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9167 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009168 return StmtError();
9169 }
9170
Alexey Bataev7828b252017-11-21 17:08:48 +00009171 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9172 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009173}
9174
Samuel Antao686c70c2016-05-26 17:30:50 +00009175StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9176 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009177 SourceLocation EndLoc,
9178 Stmt *AStmt) {
9179 if (!AStmt)
9180 return StmtError();
9181
Alexey Bataeve3727102018-04-18 15:57:46 +00009182 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009183 // 1.2.2 OpenMP Language Terminology
9184 // Structured block - An executable statement with a single entry at the
9185 // top and a single exit at the bottom.
9186 // The point of exit cannot be a branch out of the structured block.
9187 // longjmp() and throw() must not violate the entry/exit criteria.
9188 CS->getCapturedDecl()->setNothrow();
9189 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9190 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9191 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9192 // 1.2.2 OpenMP Language Terminology
9193 // Structured block - An executable statement with a single entry at the
9194 // top and a single exit at the bottom.
9195 // The point of exit cannot be a branch out of the structured block.
9196 // longjmp() and throw() must not violate the entry/exit criteria.
9197 CS->getCapturedDecl()->setNothrow();
9198 }
9199
Alexey Bataev95b64a92017-05-30 16:00:04 +00009200 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009201 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9202 return StmtError();
9203 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009204 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9205 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009206}
9207
Alexey Bataev13314bf2014-10-09 04:18:56 +00009208StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9209 Stmt *AStmt, SourceLocation StartLoc,
9210 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009211 if (!AStmt)
9212 return StmtError();
9213
Alexey Bataeve3727102018-04-18 15:57:46 +00009214 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009215 // 1.2.2 OpenMP Language Terminology
9216 // Structured block - An executable statement with a single entry at the
9217 // top and a single exit at the bottom.
9218 // The point of exit cannot be a branch out of the structured block.
9219 // longjmp() and throw() must not violate the entry/exit criteria.
9220 CS->getCapturedDecl()->setNothrow();
9221
Reid Kleckner87a31802018-03-12 21:43:02 +00009222 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009223
Alexey Bataevceabd412017-11-30 18:01:54 +00009224 DSAStack->setParentTeamsRegionLoc(StartLoc);
9225
Alexey Bataev13314bf2014-10-09 04:18:56 +00009226 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9227}
9228
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009229StmtResult
9230Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9231 SourceLocation EndLoc,
9232 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009233 if (DSAStack->isParentNowaitRegion()) {
9234 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9235 return StmtError();
9236 }
9237 if (DSAStack->isParentOrderedRegion()) {
9238 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9239 return StmtError();
9240 }
9241 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9242 CancelRegion);
9243}
9244
Alexey Bataev87933c72015-09-18 08:07:34 +00009245StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9246 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009247 SourceLocation EndLoc,
9248 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009249 if (DSAStack->isParentNowaitRegion()) {
9250 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9251 return StmtError();
9252 }
9253 if (DSAStack->isParentOrderedRegion()) {
9254 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9255 return StmtError();
9256 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009257 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009258 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9259 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009260}
9261
Alexey Bataev382967a2015-12-08 12:06:20 +00009262static bool checkGrainsizeNumTasksClauses(Sema &S,
9263 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009264 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009265 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009266 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009267 if (C->getClauseKind() == OMPC_grainsize ||
9268 C->getClauseKind() == OMPC_num_tasks) {
9269 if (!PrevClause)
9270 PrevClause = C;
9271 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009272 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009273 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9274 << getOpenMPClauseName(C->getClauseKind())
9275 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009276 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009277 diag::note_omp_previous_grainsize_num_tasks)
9278 << getOpenMPClauseName(PrevClause->getClauseKind());
9279 ErrorFound = true;
9280 }
9281 }
9282 }
9283 return ErrorFound;
9284}
9285
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009286static bool checkReductionClauseWithNogroup(Sema &S,
9287 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009288 const OMPClause *ReductionClause = nullptr;
9289 const OMPClause *NogroupClause = nullptr;
9290 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009291 if (C->getClauseKind() == OMPC_reduction) {
9292 ReductionClause = C;
9293 if (NogroupClause)
9294 break;
9295 continue;
9296 }
9297 if (C->getClauseKind() == OMPC_nogroup) {
9298 NogroupClause = C;
9299 if (ReductionClause)
9300 break;
9301 continue;
9302 }
9303 }
9304 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009305 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9306 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009307 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009308 return true;
9309 }
9310 return false;
9311}
9312
Alexey Bataev49f6e782015-12-01 04:18:41 +00009313StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9314 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009315 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009316 if (!AStmt)
9317 return StmtError();
9318
9319 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9320 OMPLoopDirective::HelperExprs B;
9321 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9322 // define the nested loops number.
9323 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009324 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009325 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009326 VarsWithImplicitDSA, B);
9327 if (NestedLoopCount == 0)
9328 return StmtError();
9329
9330 assert((CurContext->isDependentContext() || B.builtAll()) &&
9331 "omp for loop exprs were not built");
9332
Alexey Bataev382967a2015-12-08 12:06:20 +00009333 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9334 // The grainsize clause and num_tasks clause are mutually exclusive and may
9335 // not appear on the same taskloop directive.
9336 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9337 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009338 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9339 // If a reduction clause is present on the taskloop directive, the nogroup
9340 // clause must not be specified.
9341 if (checkReductionClauseWithNogroup(*this, Clauses))
9342 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009343
Reid Kleckner87a31802018-03-12 21:43:02 +00009344 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009345 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9346 NestedLoopCount, Clauses, AStmt, B);
9347}
9348
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009349StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9350 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009351 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009352 if (!AStmt)
9353 return StmtError();
9354
9355 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9356 OMPLoopDirective::HelperExprs B;
9357 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9358 // define the nested loops number.
9359 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009360 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009361 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9362 VarsWithImplicitDSA, B);
9363 if (NestedLoopCount == 0)
9364 return StmtError();
9365
9366 assert((CurContext->isDependentContext() || B.builtAll()) &&
9367 "omp for loop exprs were not built");
9368
Alexey Bataev5a3af132016-03-29 08:58:54 +00009369 if (!CurContext->isDependentContext()) {
9370 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009371 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009372 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009373 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009374 B.NumIterations, *this, CurScope,
9375 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009376 return StmtError();
9377 }
9378 }
9379
Alexey Bataev382967a2015-12-08 12:06:20 +00009380 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9381 // The grainsize clause and num_tasks clause are mutually exclusive and may
9382 // not appear on the same taskloop directive.
9383 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9384 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009385 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9386 // If a reduction clause is present on the taskloop directive, the nogroup
9387 // clause must not be specified.
9388 if (checkReductionClauseWithNogroup(*this, Clauses))
9389 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009390 if (checkSimdlenSafelenSpecified(*this, Clauses))
9391 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009392
Reid Kleckner87a31802018-03-12 21:43:02 +00009393 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009394 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9395 NestedLoopCount, Clauses, AStmt, B);
9396}
9397
Alexey Bataev60e51c42019-10-10 20:13:02 +00009398StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9399 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9400 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9401 if (!AStmt)
9402 return StmtError();
9403
9404 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9405 OMPLoopDirective::HelperExprs B;
9406 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9407 // define the nested loops number.
9408 unsigned NestedLoopCount =
9409 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9410 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9411 VarsWithImplicitDSA, B);
9412 if (NestedLoopCount == 0)
9413 return StmtError();
9414
9415 assert((CurContext->isDependentContext() || B.builtAll()) &&
9416 "omp for loop exprs were not built");
9417
9418 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9419 // The grainsize clause and num_tasks clause are mutually exclusive and may
9420 // not appear on the same taskloop directive.
9421 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9422 return StmtError();
9423 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9424 // If a reduction clause is present on the taskloop directive, the nogroup
9425 // clause must not be specified.
9426 if (checkReductionClauseWithNogroup(*this, Clauses))
9427 return StmtError();
9428
9429 setFunctionHasBranchProtectedScope();
9430 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9431 NestedLoopCount, Clauses, AStmt, B);
9432}
9433
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009434StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9435 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9436 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9437 if (!AStmt)
9438 return StmtError();
9439
9440 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9441 OMPLoopDirective::HelperExprs B;
9442 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9443 // define the nested loops number.
9444 unsigned NestedLoopCount =
9445 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9446 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9447 VarsWithImplicitDSA, B);
9448 if (NestedLoopCount == 0)
9449 return StmtError();
9450
9451 assert((CurContext->isDependentContext() || B.builtAll()) &&
9452 "omp for loop exprs were not built");
9453
9454 if (!CurContext->isDependentContext()) {
9455 // Finalize the clauses that need pre-built expressions for CodeGen.
9456 for (OMPClause *C : Clauses) {
9457 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9458 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9459 B.NumIterations, *this, CurScope,
9460 DSAStack))
9461 return StmtError();
9462 }
9463 }
9464
9465 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9466 // The grainsize clause and num_tasks clause are mutually exclusive and may
9467 // not appear on the same taskloop directive.
9468 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9469 return StmtError();
9470 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9471 // If a reduction clause is present on the taskloop directive, the nogroup
9472 // clause must not be specified.
9473 if (checkReductionClauseWithNogroup(*this, Clauses))
9474 return StmtError();
9475 if (checkSimdlenSafelenSpecified(*this, Clauses))
9476 return StmtError();
9477
9478 setFunctionHasBranchProtectedScope();
9479 return OMPMasterTaskLoopSimdDirective::Create(
9480 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9481}
9482
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009483StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9484 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9485 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9486 if (!AStmt)
9487 return StmtError();
9488
9489 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9490 auto *CS = cast<CapturedStmt>(AStmt);
9491 // 1.2.2 OpenMP Language Terminology
9492 // Structured block - An executable statement with a single entry at the
9493 // top and a single exit at the bottom.
9494 // The point of exit cannot be a branch out of the structured block.
9495 // longjmp() and throw() must not violate the entry/exit criteria.
9496 CS->getCapturedDecl()->setNothrow();
9497 for (int ThisCaptureLevel =
9498 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9499 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9500 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9501 // 1.2.2 OpenMP Language Terminology
9502 // Structured block - An executable statement with a single entry at the
9503 // top and a single exit at the bottom.
9504 // The point of exit cannot be a branch out of the structured block.
9505 // longjmp() and throw() must not violate the entry/exit criteria.
9506 CS->getCapturedDecl()->setNothrow();
9507 }
9508
9509 OMPLoopDirective::HelperExprs B;
9510 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9511 // define the nested loops number.
9512 unsigned NestedLoopCount = checkOpenMPLoop(
9513 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9514 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9515 VarsWithImplicitDSA, B);
9516 if (NestedLoopCount == 0)
9517 return StmtError();
9518
9519 assert((CurContext->isDependentContext() || B.builtAll()) &&
9520 "omp for loop exprs were not built");
9521
9522 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9523 // The grainsize clause and num_tasks clause are mutually exclusive and may
9524 // not appear on the same taskloop directive.
9525 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9526 return StmtError();
9527 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9528 // If a reduction clause is present on the taskloop directive, the nogroup
9529 // clause must not be specified.
9530 if (checkReductionClauseWithNogroup(*this, Clauses))
9531 return StmtError();
9532
9533 setFunctionHasBranchProtectedScope();
9534 return OMPParallelMasterTaskLoopDirective::Create(
9535 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9536}
9537
Alexey Bataev14a388f2019-10-25 10:27:13 -04009538StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9539 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9540 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9541 if (!AStmt)
9542 return StmtError();
9543
9544 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9545 auto *CS = cast<CapturedStmt>(AStmt);
9546 // 1.2.2 OpenMP Language Terminology
9547 // Structured block - An executable statement with a single entry at the
9548 // top and a single exit at the bottom.
9549 // The point of exit cannot be a branch out of the structured block.
9550 // longjmp() and throw() must not violate the entry/exit criteria.
9551 CS->getCapturedDecl()->setNothrow();
9552 for (int ThisCaptureLevel =
9553 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9554 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9555 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9556 // 1.2.2 OpenMP Language Terminology
9557 // Structured block - An executable statement with a single entry at the
9558 // top and a single exit at the bottom.
9559 // The point of exit cannot be a branch out of the structured block.
9560 // longjmp() and throw() must not violate the entry/exit criteria.
9561 CS->getCapturedDecl()->setNothrow();
9562 }
9563
9564 OMPLoopDirective::HelperExprs B;
9565 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9566 // define the nested loops number.
9567 unsigned NestedLoopCount = checkOpenMPLoop(
9568 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9569 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9570 VarsWithImplicitDSA, B);
9571 if (NestedLoopCount == 0)
9572 return StmtError();
9573
9574 assert((CurContext->isDependentContext() || B.builtAll()) &&
9575 "omp for loop exprs were not built");
9576
9577 if (!CurContext->isDependentContext()) {
9578 // Finalize the clauses that need pre-built expressions for CodeGen.
9579 for (OMPClause *C : Clauses) {
9580 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9581 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9582 B.NumIterations, *this, CurScope,
9583 DSAStack))
9584 return StmtError();
9585 }
9586 }
9587
9588 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9589 // The grainsize clause and num_tasks clause are mutually exclusive and may
9590 // not appear on the same taskloop directive.
9591 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9592 return StmtError();
9593 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9594 // If a reduction clause is present on the taskloop directive, the nogroup
9595 // clause must not be specified.
9596 if (checkReductionClauseWithNogroup(*this, Clauses))
9597 return StmtError();
9598 if (checkSimdlenSafelenSpecified(*this, Clauses))
9599 return StmtError();
9600
9601 setFunctionHasBranchProtectedScope();
9602 return OMPParallelMasterTaskLoopSimdDirective::Create(
9603 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9604}
9605
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009606StmtResult Sema::ActOnOpenMPDistributeDirective(
9607 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009608 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009609 if (!AStmt)
9610 return StmtError();
9611
9612 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9613 OMPLoopDirective::HelperExprs B;
9614 // In presence of clause 'collapse' with number of loops, it will
9615 // define the nested loops number.
9616 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009617 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009618 nullptr /*ordered not a clause on distribute*/, AStmt,
9619 *this, *DSAStack, VarsWithImplicitDSA, B);
9620 if (NestedLoopCount == 0)
9621 return StmtError();
9622
9623 assert((CurContext->isDependentContext() || B.builtAll()) &&
9624 "omp for loop exprs were not built");
9625
Reid Kleckner87a31802018-03-12 21:43:02 +00009626 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009627 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9628 NestedLoopCount, Clauses, AStmt, B);
9629}
9630
Carlo Bertolli9925f152016-06-27 14:55:37 +00009631StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9632 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009633 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009634 if (!AStmt)
9635 return StmtError();
9636
Alexey Bataeve3727102018-04-18 15:57:46 +00009637 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009638 // 1.2.2 OpenMP Language Terminology
9639 // Structured block - An executable statement with a single entry at the
9640 // top and a single exit at the bottom.
9641 // The point of exit cannot be a branch out of the structured block.
9642 // longjmp() and throw() must not violate the entry/exit criteria.
9643 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009644 for (int ThisCaptureLevel =
9645 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9646 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9647 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9648 // 1.2.2 OpenMP Language Terminology
9649 // Structured block - An executable statement with a single entry at the
9650 // top and a single exit at the bottom.
9651 // The point of exit cannot be a branch out of the structured block.
9652 // longjmp() and throw() must not violate the entry/exit criteria.
9653 CS->getCapturedDecl()->setNothrow();
9654 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009655
9656 OMPLoopDirective::HelperExprs B;
9657 // In presence of clause 'collapse' with number of loops, it will
9658 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009659 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009660 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009661 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009662 VarsWithImplicitDSA, B);
9663 if (NestedLoopCount == 0)
9664 return StmtError();
9665
9666 assert((CurContext->isDependentContext() || B.builtAll()) &&
9667 "omp for loop exprs were not built");
9668
Reid Kleckner87a31802018-03-12 21:43:02 +00009669 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009670 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009671 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9672 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009673}
9674
Kelvin Li4a39add2016-07-05 05:00:15 +00009675StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9676 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009677 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009678 if (!AStmt)
9679 return StmtError();
9680
Alexey Bataeve3727102018-04-18 15:57:46 +00009681 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009682 // 1.2.2 OpenMP Language Terminology
9683 // Structured block - An executable statement with a single entry at the
9684 // top and a single exit at the bottom.
9685 // The point of exit cannot be a branch out of the structured block.
9686 // longjmp() and throw() must not violate the entry/exit criteria.
9687 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009688 for (int ThisCaptureLevel =
9689 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9690 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9691 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9692 // 1.2.2 OpenMP Language Terminology
9693 // Structured block - An executable statement with a single entry at the
9694 // top and a single exit at the bottom.
9695 // The point of exit cannot be a branch out of the structured block.
9696 // longjmp() and throw() must not violate the entry/exit criteria.
9697 CS->getCapturedDecl()->setNothrow();
9698 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009699
9700 OMPLoopDirective::HelperExprs B;
9701 // In presence of clause 'collapse' with number of loops, it will
9702 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009703 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009704 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009705 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009706 VarsWithImplicitDSA, B);
9707 if (NestedLoopCount == 0)
9708 return StmtError();
9709
9710 assert((CurContext->isDependentContext() || B.builtAll()) &&
9711 "omp for loop exprs were not built");
9712
Alexey Bataev438388c2017-11-22 18:34:02 +00009713 if (!CurContext->isDependentContext()) {
9714 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009715 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009716 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9717 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9718 B.NumIterations, *this, CurScope,
9719 DSAStack))
9720 return StmtError();
9721 }
9722 }
9723
Kelvin Lic5609492016-07-15 04:39:07 +00009724 if (checkSimdlenSafelenSpecified(*this, Clauses))
9725 return StmtError();
9726
Reid Kleckner87a31802018-03-12 21:43:02 +00009727 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009728 return OMPDistributeParallelForSimdDirective::Create(
9729 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9730}
9731
Kelvin Li787f3fc2016-07-06 04:45:38 +00009732StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9733 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009734 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009735 if (!AStmt)
9736 return StmtError();
9737
Alexey Bataeve3727102018-04-18 15:57:46 +00009738 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009739 // 1.2.2 OpenMP Language Terminology
9740 // Structured block - An executable statement with a single entry at the
9741 // top and a single exit at the bottom.
9742 // The point of exit cannot be a branch out of the structured block.
9743 // longjmp() and throw() must not violate the entry/exit criteria.
9744 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009745 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9746 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9747 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9748 // 1.2.2 OpenMP Language Terminology
9749 // Structured block - An executable statement with a single entry at the
9750 // top and a single exit at the bottom.
9751 // The point of exit cannot be a branch out of the structured block.
9752 // longjmp() and throw() must not violate the entry/exit criteria.
9753 CS->getCapturedDecl()->setNothrow();
9754 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009755
9756 OMPLoopDirective::HelperExprs B;
9757 // In presence of clause 'collapse' with number of loops, it will
9758 // define the nested loops number.
9759 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009760 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009761 nullptr /*ordered not a clause on distribute*/, CS, *this,
9762 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009763 if (NestedLoopCount == 0)
9764 return StmtError();
9765
9766 assert((CurContext->isDependentContext() || B.builtAll()) &&
9767 "omp for loop exprs were not built");
9768
Alexey Bataev438388c2017-11-22 18:34:02 +00009769 if (!CurContext->isDependentContext()) {
9770 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009771 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009772 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9773 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9774 B.NumIterations, *this, CurScope,
9775 DSAStack))
9776 return StmtError();
9777 }
9778 }
9779
Kelvin Lic5609492016-07-15 04:39:07 +00009780 if (checkSimdlenSafelenSpecified(*this, Clauses))
9781 return StmtError();
9782
Reid Kleckner87a31802018-03-12 21:43:02 +00009783 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009784 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9785 NestedLoopCount, Clauses, AStmt, B);
9786}
9787
Kelvin Lia579b912016-07-14 02:54:56 +00009788StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9789 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009790 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009791 if (!AStmt)
9792 return StmtError();
9793
Alexey Bataeve3727102018-04-18 15:57:46 +00009794 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009795 // 1.2.2 OpenMP Language Terminology
9796 // Structured block - An executable statement with a single entry at the
9797 // top and a single exit at the bottom.
9798 // The point of exit cannot be a branch out of the structured block.
9799 // longjmp() and throw() must not violate the entry/exit criteria.
9800 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009801 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9802 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9803 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9804 // 1.2.2 OpenMP Language Terminology
9805 // Structured block - An executable statement with a single entry at the
9806 // top and a single exit at the bottom.
9807 // The point of exit cannot be a branch out of the structured block.
9808 // longjmp() and throw() must not violate the entry/exit criteria.
9809 CS->getCapturedDecl()->setNothrow();
9810 }
Kelvin Lia579b912016-07-14 02:54:56 +00009811
9812 OMPLoopDirective::HelperExprs B;
9813 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9814 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009815 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00009816 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009817 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00009818 VarsWithImplicitDSA, B);
9819 if (NestedLoopCount == 0)
9820 return StmtError();
9821
9822 assert((CurContext->isDependentContext() || B.builtAll()) &&
9823 "omp target parallel for simd loop exprs were not built");
9824
9825 if (!CurContext->isDependentContext()) {
9826 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009827 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009828 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00009829 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9830 B.NumIterations, *this, CurScope,
9831 DSAStack))
9832 return StmtError();
9833 }
9834 }
Kelvin Lic5609492016-07-15 04:39:07 +00009835 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00009836 return StmtError();
9837
Reid Kleckner87a31802018-03-12 21:43:02 +00009838 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00009839 return OMPTargetParallelForSimdDirective::Create(
9840 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9841}
9842
Kelvin Li986330c2016-07-20 22:57:10 +00009843StmtResult Sema::ActOnOpenMPTargetSimdDirective(
9844 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009845 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00009846 if (!AStmt)
9847 return StmtError();
9848
Alexey Bataeve3727102018-04-18 15:57:46 +00009849 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00009850 // 1.2.2 OpenMP Language Terminology
9851 // Structured block - An executable statement with a single entry at the
9852 // top and a single exit at the bottom.
9853 // The point of exit cannot be a branch out of the structured block.
9854 // longjmp() and throw() must not violate the entry/exit criteria.
9855 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00009856 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
9857 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9858 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9859 // 1.2.2 OpenMP Language Terminology
9860 // Structured block - An executable statement with a single entry at the
9861 // top and a single exit at the bottom.
9862 // The point of exit cannot be a branch out of the structured block.
9863 // longjmp() and throw() must not violate the entry/exit criteria.
9864 CS->getCapturedDecl()->setNothrow();
9865 }
9866
Kelvin Li986330c2016-07-20 22:57:10 +00009867 OMPLoopDirective::HelperExprs B;
9868 // In presence of clause 'collapse' with number of loops, it will define the
9869 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00009870 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009871 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00009872 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00009873 VarsWithImplicitDSA, B);
9874 if (NestedLoopCount == 0)
9875 return StmtError();
9876
9877 assert((CurContext->isDependentContext() || B.builtAll()) &&
9878 "omp target simd loop exprs were not built");
9879
9880 if (!CurContext->isDependentContext()) {
9881 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009882 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009883 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00009884 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9885 B.NumIterations, *this, CurScope,
9886 DSAStack))
9887 return StmtError();
9888 }
9889 }
9890
9891 if (checkSimdlenSafelenSpecified(*this, Clauses))
9892 return StmtError();
9893
Reid Kleckner87a31802018-03-12 21:43:02 +00009894 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00009895 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
9896 NestedLoopCount, Clauses, AStmt, B);
9897}
9898
Kelvin Li02532872016-08-05 14:37:37 +00009899StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
9900 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009901 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00009902 if (!AStmt)
9903 return StmtError();
9904
Alexey Bataeve3727102018-04-18 15:57:46 +00009905 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00009906 // 1.2.2 OpenMP Language Terminology
9907 // Structured block - An executable statement with a single entry at the
9908 // top and a single exit at the bottom.
9909 // The point of exit cannot be a branch out of the structured block.
9910 // longjmp() and throw() must not violate the entry/exit criteria.
9911 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009912 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
9913 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9914 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9915 // 1.2.2 OpenMP Language Terminology
9916 // Structured block - An executable statement with a single entry at the
9917 // top and a single exit at the bottom.
9918 // The point of exit cannot be a branch out of the structured block.
9919 // longjmp() and throw() must not violate the entry/exit criteria.
9920 CS->getCapturedDecl()->setNothrow();
9921 }
Kelvin Li02532872016-08-05 14:37:37 +00009922
9923 OMPLoopDirective::HelperExprs B;
9924 // In presence of clause 'collapse' with number of loops, it will
9925 // define the nested loops number.
9926 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009927 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009928 nullptr /*ordered not a clause on distribute*/, CS, *this,
9929 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00009930 if (NestedLoopCount == 0)
9931 return StmtError();
9932
9933 assert((CurContext->isDependentContext() || B.builtAll()) &&
9934 "omp teams distribute loop exprs were not built");
9935
Reid Kleckner87a31802018-03-12 21:43:02 +00009936 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009937
9938 DSAStack->setParentTeamsRegionLoc(StartLoc);
9939
David Majnemer9d168222016-08-05 17:44:54 +00009940 return OMPTeamsDistributeDirective::Create(
9941 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00009942}
9943
Kelvin Li4e325f72016-10-25 12:50:55 +00009944StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
9945 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009946 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009947 if (!AStmt)
9948 return StmtError();
9949
Alexey Bataeve3727102018-04-18 15:57:46 +00009950 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00009951 // 1.2.2 OpenMP Language Terminology
9952 // Structured block - An executable statement with a single entry at the
9953 // top and a single exit at the bottom.
9954 // The point of exit cannot be a branch out of the structured block.
9955 // longjmp() and throw() must not violate the entry/exit criteria.
9956 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00009957 for (int ThisCaptureLevel =
9958 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
9959 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9960 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9961 // 1.2.2 OpenMP Language Terminology
9962 // Structured block - An executable statement with a single entry at the
9963 // top and a single exit at the bottom.
9964 // The point of exit cannot be a branch out of the structured block.
9965 // longjmp() and throw() must not violate the entry/exit criteria.
9966 CS->getCapturedDecl()->setNothrow();
9967 }
9968
Kelvin Li4e325f72016-10-25 12:50:55 +00009969
9970 OMPLoopDirective::HelperExprs B;
9971 // In presence of clause 'collapse' with number of loops, it will
9972 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009973 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00009974 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00009975 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00009976 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00009977
9978 if (NestedLoopCount == 0)
9979 return StmtError();
9980
9981 assert((CurContext->isDependentContext() || B.builtAll()) &&
9982 "omp teams distribute simd loop exprs were not built");
9983
9984 if (!CurContext->isDependentContext()) {
9985 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009986 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009987 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9988 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9989 B.NumIterations, *this, CurScope,
9990 DSAStack))
9991 return StmtError();
9992 }
9993 }
9994
9995 if (checkSimdlenSafelenSpecified(*this, Clauses))
9996 return StmtError();
9997
Reid Kleckner87a31802018-03-12 21:43:02 +00009998 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009999
10000 DSAStack->setParentTeamsRegionLoc(StartLoc);
10001
Kelvin Li4e325f72016-10-25 12:50:55 +000010002 return OMPTeamsDistributeSimdDirective::Create(
10003 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10004}
10005
Kelvin Li579e41c2016-11-30 23:51:03 +000010006StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10007 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010008 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010009 if (!AStmt)
10010 return StmtError();
10011
Alexey Bataeve3727102018-04-18 15:57:46 +000010012 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010013 // 1.2.2 OpenMP Language Terminology
10014 // Structured block - An executable statement with a single entry at the
10015 // top and a single exit at the bottom.
10016 // The point of exit cannot be a branch out of the structured block.
10017 // longjmp() and throw() must not violate the entry/exit criteria.
10018 CS->getCapturedDecl()->setNothrow();
10019
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010020 for (int ThisCaptureLevel =
10021 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10022 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10023 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10024 // 1.2.2 OpenMP Language Terminology
10025 // Structured block - An executable statement with a single entry at the
10026 // top and a single exit at the bottom.
10027 // The point of exit cannot be a branch out of the structured block.
10028 // longjmp() and throw() must not violate the entry/exit criteria.
10029 CS->getCapturedDecl()->setNothrow();
10030 }
10031
Kelvin Li579e41c2016-11-30 23:51:03 +000010032 OMPLoopDirective::HelperExprs B;
10033 // In presence of clause 'collapse' with number of loops, it will
10034 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010035 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010036 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010037 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010038 VarsWithImplicitDSA, B);
10039
10040 if (NestedLoopCount == 0)
10041 return StmtError();
10042
10043 assert((CurContext->isDependentContext() || B.builtAll()) &&
10044 "omp for loop exprs were not built");
10045
10046 if (!CurContext->isDependentContext()) {
10047 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010048 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010049 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10050 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10051 B.NumIterations, *this, CurScope,
10052 DSAStack))
10053 return StmtError();
10054 }
10055 }
10056
10057 if (checkSimdlenSafelenSpecified(*this, Clauses))
10058 return StmtError();
10059
Reid Kleckner87a31802018-03-12 21:43:02 +000010060 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010061
10062 DSAStack->setParentTeamsRegionLoc(StartLoc);
10063
Kelvin Li579e41c2016-11-30 23:51:03 +000010064 return OMPTeamsDistributeParallelForSimdDirective::Create(
10065 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10066}
10067
Kelvin Li7ade93f2016-12-09 03:24:30 +000010068StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10069 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010070 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010071 if (!AStmt)
10072 return StmtError();
10073
Alexey Bataeve3727102018-04-18 15:57:46 +000010074 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010075 // 1.2.2 OpenMP Language Terminology
10076 // Structured block - An executable statement with a single entry at the
10077 // top and a single exit at the bottom.
10078 // The point of exit cannot be a branch out of the structured block.
10079 // longjmp() and throw() must not violate the entry/exit criteria.
10080 CS->getCapturedDecl()->setNothrow();
10081
Carlo Bertolli62fae152017-11-20 20:46:39 +000010082 for (int ThisCaptureLevel =
10083 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10084 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10085 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10086 // 1.2.2 OpenMP Language Terminology
10087 // Structured block - An executable statement with a single entry at the
10088 // top and a single exit at the bottom.
10089 // The point of exit cannot be a branch out of the structured block.
10090 // longjmp() and throw() must not violate the entry/exit criteria.
10091 CS->getCapturedDecl()->setNothrow();
10092 }
10093
Kelvin Li7ade93f2016-12-09 03:24:30 +000010094 OMPLoopDirective::HelperExprs B;
10095 // In presence of clause 'collapse' with number of loops, it will
10096 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010097 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010098 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010099 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010100 VarsWithImplicitDSA, B);
10101
10102 if (NestedLoopCount == 0)
10103 return StmtError();
10104
10105 assert((CurContext->isDependentContext() || B.builtAll()) &&
10106 "omp for loop exprs were not built");
10107
Reid Kleckner87a31802018-03-12 21:43:02 +000010108 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010109
10110 DSAStack->setParentTeamsRegionLoc(StartLoc);
10111
Kelvin Li7ade93f2016-12-09 03:24:30 +000010112 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010113 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10114 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010115}
10116
Kelvin Libf594a52016-12-17 05:48:59 +000010117StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10118 Stmt *AStmt,
10119 SourceLocation StartLoc,
10120 SourceLocation EndLoc) {
10121 if (!AStmt)
10122 return StmtError();
10123
Alexey Bataeve3727102018-04-18 15:57:46 +000010124 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010125 // 1.2.2 OpenMP Language Terminology
10126 // Structured block - An executable statement with a single entry at the
10127 // top and a single exit at the bottom.
10128 // The point of exit cannot be a branch out of the structured block.
10129 // longjmp() and throw() must not violate the entry/exit criteria.
10130 CS->getCapturedDecl()->setNothrow();
10131
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010132 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10133 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10134 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10135 // 1.2.2 OpenMP Language Terminology
10136 // Structured block - An executable statement with a single entry at the
10137 // top and a single exit at the bottom.
10138 // The point of exit cannot be a branch out of the structured block.
10139 // longjmp() and throw() must not violate the entry/exit criteria.
10140 CS->getCapturedDecl()->setNothrow();
10141 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010142 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010143
10144 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10145 AStmt);
10146}
10147
Kelvin Li83c451e2016-12-25 04:52:54 +000010148StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010150 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010151 if (!AStmt)
10152 return StmtError();
10153
Alexey Bataeve3727102018-04-18 15:57:46 +000010154 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010155 // 1.2.2 OpenMP Language Terminology
10156 // Structured block - An executable statement with a single entry at the
10157 // top and a single exit at the bottom.
10158 // The point of exit cannot be a branch out of the structured block.
10159 // longjmp() and throw() must not violate the entry/exit criteria.
10160 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010161 for (int ThisCaptureLevel =
10162 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10163 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10164 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10165 // 1.2.2 OpenMP Language Terminology
10166 // Structured block - An executable statement with a single entry at the
10167 // top and a single exit at the bottom.
10168 // The point of exit cannot be a branch out of the structured block.
10169 // longjmp() and throw() must not violate the entry/exit criteria.
10170 CS->getCapturedDecl()->setNothrow();
10171 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010172
10173 OMPLoopDirective::HelperExprs B;
10174 // In presence of clause 'collapse' with number of loops, it will
10175 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010176 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010177 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10178 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010179 VarsWithImplicitDSA, B);
10180 if (NestedLoopCount == 0)
10181 return StmtError();
10182
10183 assert((CurContext->isDependentContext() || B.builtAll()) &&
10184 "omp target teams distribute loop exprs were not built");
10185
Reid Kleckner87a31802018-03-12 21:43:02 +000010186 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010187 return OMPTargetTeamsDistributeDirective::Create(
10188 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10189}
10190
Kelvin Li80e8f562016-12-29 22:16:30 +000010191StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10192 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010193 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010194 if (!AStmt)
10195 return StmtError();
10196
Alexey Bataeve3727102018-04-18 15:57:46 +000010197 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010198 // 1.2.2 OpenMP Language Terminology
10199 // Structured block - An executable statement with a single entry at the
10200 // top and a single exit at the bottom.
10201 // The point of exit cannot be a branch out of the structured block.
10202 // longjmp() and throw() must not violate the entry/exit criteria.
10203 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010204 for (int ThisCaptureLevel =
10205 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10206 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10207 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10208 // 1.2.2 OpenMP Language Terminology
10209 // Structured block - An executable statement with a single entry at the
10210 // top and a single exit at the bottom.
10211 // The point of exit cannot be a branch out of the structured block.
10212 // longjmp() and throw() must not violate the entry/exit criteria.
10213 CS->getCapturedDecl()->setNothrow();
10214 }
10215
Kelvin Li80e8f562016-12-29 22:16:30 +000010216 OMPLoopDirective::HelperExprs B;
10217 // In presence of clause 'collapse' with number of loops, it will
10218 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010219 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010220 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10221 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010222 VarsWithImplicitDSA, B);
10223 if (NestedLoopCount == 0)
10224 return StmtError();
10225
10226 assert((CurContext->isDependentContext() || B.builtAll()) &&
10227 "omp target teams distribute parallel for loop exprs were not built");
10228
Alexey Bataev647dd842018-01-15 20:59:40 +000010229 if (!CurContext->isDependentContext()) {
10230 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010231 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010232 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10233 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10234 B.NumIterations, *this, CurScope,
10235 DSAStack))
10236 return StmtError();
10237 }
10238 }
10239
Reid Kleckner87a31802018-03-12 21:43:02 +000010240 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010241 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010242 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10243 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010244}
10245
Kelvin Li1851df52017-01-03 05:23:48 +000010246StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10247 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010248 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010249 if (!AStmt)
10250 return StmtError();
10251
Alexey Bataeve3727102018-04-18 15:57:46 +000010252 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010253 // 1.2.2 OpenMP Language Terminology
10254 // Structured block - An executable statement with a single entry at the
10255 // top and a single exit at the bottom.
10256 // The point of exit cannot be a branch out of the structured block.
10257 // longjmp() and throw() must not violate the entry/exit criteria.
10258 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010259 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10260 OMPD_target_teams_distribute_parallel_for_simd);
10261 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10262 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10263 // 1.2.2 OpenMP Language Terminology
10264 // Structured block - An executable statement with a single entry at the
10265 // top and a single exit at the bottom.
10266 // The point of exit cannot be a branch out of the structured block.
10267 // longjmp() and throw() must not violate the entry/exit criteria.
10268 CS->getCapturedDecl()->setNothrow();
10269 }
Kelvin Li1851df52017-01-03 05:23:48 +000010270
10271 OMPLoopDirective::HelperExprs B;
10272 // In presence of clause 'collapse' with number of loops, it will
10273 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010274 unsigned NestedLoopCount =
10275 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010276 getCollapseNumberExpr(Clauses),
10277 nullptr /*ordered not a clause on distribute*/, CS, *this,
10278 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010279 if (NestedLoopCount == 0)
10280 return StmtError();
10281
10282 assert((CurContext->isDependentContext() || B.builtAll()) &&
10283 "omp target teams distribute parallel for simd loop exprs were not "
10284 "built");
10285
10286 if (!CurContext->isDependentContext()) {
10287 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010288 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010289 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10290 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10291 B.NumIterations, *this, CurScope,
10292 DSAStack))
10293 return StmtError();
10294 }
10295 }
10296
Alexey Bataev438388c2017-11-22 18:34:02 +000010297 if (checkSimdlenSafelenSpecified(*this, Clauses))
10298 return StmtError();
10299
Reid Kleckner87a31802018-03-12 21:43:02 +000010300 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010301 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10302 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10303}
10304
Kelvin Lida681182017-01-10 18:08:18 +000010305StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10306 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010307 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010308 if (!AStmt)
10309 return StmtError();
10310
10311 auto *CS = cast<CapturedStmt>(AStmt);
10312 // 1.2.2 OpenMP Language Terminology
10313 // Structured block - An executable statement with a single entry at the
10314 // top and a single exit at the bottom.
10315 // The point of exit cannot be a branch out of the structured block.
10316 // longjmp() and throw() must not violate the entry/exit criteria.
10317 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010318 for (int ThisCaptureLevel =
10319 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10320 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10321 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10322 // 1.2.2 OpenMP Language Terminology
10323 // Structured block - An executable statement with a single entry at the
10324 // top and a single exit at the bottom.
10325 // The point of exit cannot be a branch out of the structured block.
10326 // longjmp() and throw() must not violate the entry/exit criteria.
10327 CS->getCapturedDecl()->setNothrow();
10328 }
Kelvin Lida681182017-01-10 18:08:18 +000010329
10330 OMPLoopDirective::HelperExprs B;
10331 // In presence of clause 'collapse' with number of loops, it will
10332 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010333 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010334 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010335 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010336 VarsWithImplicitDSA, B);
10337 if (NestedLoopCount == 0)
10338 return StmtError();
10339
10340 assert((CurContext->isDependentContext() || B.builtAll()) &&
10341 "omp target teams distribute simd loop exprs were not built");
10342
Alexey Bataev438388c2017-11-22 18:34:02 +000010343 if (!CurContext->isDependentContext()) {
10344 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010345 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010346 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10347 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10348 B.NumIterations, *this, CurScope,
10349 DSAStack))
10350 return StmtError();
10351 }
10352 }
10353
10354 if (checkSimdlenSafelenSpecified(*this, Clauses))
10355 return StmtError();
10356
Reid Kleckner87a31802018-03-12 21:43:02 +000010357 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010358 return OMPTargetTeamsDistributeSimdDirective::Create(
10359 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10360}
10361
Alexey Bataeved09d242014-05-28 05:53:51 +000010362OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010363 SourceLocation StartLoc,
10364 SourceLocation LParenLoc,
10365 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010366 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010367 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010368 case OMPC_final:
10369 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10370 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010371 case OMPC_num_threads:
10372 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10373 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010374 case OMPC_safelen:
10375 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10376 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010377 case OMPC_simdlen:
10378 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10379 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010380 case OMPC_allocator:
10381 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10382 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010383 case OMPC_collapse:
10384 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10385 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010386 case OMPC_ordered:
10387 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10388 break;
Michael Wonge710d542015-08-07 16:16:36 +000010389 case OMPC_device:
10390 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10391 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010392 case OMPC_num_teams:
10393 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10394 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010395 case OMPC_thread_limit:
10396 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10397 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010398 case OMPC_priority:
10399 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10400 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010401 case OMPC_grainsize:
10402 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10403 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010404 case OMPC_num_tasks:
10405 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10406 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010407 case OMPC_hint:
10408 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10409 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010410 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010411 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010412 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010413 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010414 case OMPC_private:
10415 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010416 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010417 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010418 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010419 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010420 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010421 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010422 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010423 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010424 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010425 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010426 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010427 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010428 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010429 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010430 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010431 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010432 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010433 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010434 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010435 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010436 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010437 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010438 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010439 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010440 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010441 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010442 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010443 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010444 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010445 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010446 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010447 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010448 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010449 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010450 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010451 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010452 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010453 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010454 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010455 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010456 llvm_unreachable("Clause is not allowed.");
10457 }
10458 return Res;
10459}
10460
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010461// An OpenMP directive such as 'target parallel' has two captured regions:
10462// for the 'target' and 'parallel' respectively. This function returns
10463// the region in which to capture expressions associated with a clause.
10464// A return value of OMPD_unknown signifies that the expression should not
10465// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010466static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
10467 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
10468 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010469 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010470 switch (CKind) {
10471 case OMPC_if:
10472 switch (DKind) {
10473 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010474 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010475 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010476 // If this clause applies to the nested 'parallel' region, capture within
10477 // the 'target' region, otherwise do not capture.
10478 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10479 CaptureRegion = OMPD_target;
10480 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010481 case OMPD_target_teams_distribute_parallel_for:
10482 case OMPD_target_teams_distribute_parallel_for_simd:
10483 // If this clause applies to the nested 'parallel' region, capture within
10484 // the 'teams' region, otherwise do not capture.
10485 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10486 CaptureRegion = OMPD_teams;
10487 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010488 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010489 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010490 CaptureRegion = OMPD_teams;
10491 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010492 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010493 case OMPD_target_enter_data:
10494 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010495 CaptureRegion = OMPD_task;
10496 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010497 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010498 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010499 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10500 CaptureRegion = OMPD_parallel;
10501 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010502 case OMPD_cancel:
10503 case OMPD_parallel:
10504 case OMPD_parallel_sections:
10505 case OMPD_parallel_for:
10506 case OMPD_parallel_for_simd:
10507 case OMPD_target:
10508 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010509 case OMPD_target_teams:
10510 case OMPD_target_teams_distribute:
10511 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010512 case OMPD_distribute_parallel_for:
10513 case OMPD_distribute_parallel_for_simd:
10514 case OMPD_task:
10515 case OMPD_taskloop:
10516 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010517 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010518 case OMPD_master_taskloop_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010519 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010520 // Do not capture if-clause expressions.
10521 break;
10522 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010523 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010524 case OMPD_taskyield:
10525 case OMPD_barrier:
10526 case OMPD_taskwait:
10527 case OMPD_cancellation_point:
10528 case OMPD_flush:
10529 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010530 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010531 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010532 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010533 case OMPD_declare_target:
10534 case OMPD_end_declare_target:
10535 case OMPD_teams:
10536 case OMPD_simd:
10537 case OMPD_for:
10538 case OMPD_for_simd:
10539 case OMPD_sections:
10540 case OMPD_section:
10541 case OMPD_single:
10542 case OMPD_master:
10543 case OMPD_critical:
10544 case OMPD_taskgroup:
10545 case OMPD_distribute:
10546 case OMPD_ordered:
10547 case OMPD_atomic:
10548 case OMPD_distribute_simd:
10549 case OMPD_teams_distribute:
10550 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010551 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010552 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10553 case OMPD_unknown:
10554 llvm_unreachable("Unknown OpenMP directive");
10555 }
10556 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010557 case OMPC_num_threads:
10558 switch (DKind) {
10559 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010560 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010561 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010562 CaptureRegion = OMPD_target;
10563 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010564 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010565 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010566 case OMPD_target_teams_distribute_parallel_for:
10567 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010568 CaptureRegion = OMPD_teams;
10569 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010570 case OMPD_parallel:
10571 case OMPD_parallel_sections:
10572 case OMPD_parallel_for:
10573 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010574 case OMPD_distribute_parallel_for:
10575 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010576 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010577 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010578 // Do not capture num_threads-clause expressions.
10579 break;
10580 case OMPD_target_data:
10581 case OMPD_target_enter_data:
10582 case OMPD_target_exit_data:
10583 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010584 case OMPD_target:
10585 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010586 case OMPD_target_teams:
10587 case OMPD_target_teams_distribute:
10588 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010589 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010590 case OMPD_task:
10591 case OMPD_taskloop:
10592 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010593 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010594 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010595 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010596 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010597 case OMPD_taskyield:
10598 case OMPD_barrier:
10599 case OMPD_taskwait:
10600 case OMPD_cancellation_point:
10601 case OMPD_flush:
10602 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010603 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010604 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010605 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010606 case OMPD_declare_target:
10607 case OMPD_end_declare_target:
10608 case OMPD_teams:
10609 case OMPD_simd:
10610 case OMPD_for:
10611 case OMPD_for_simd:
10612 case OMPD_sections:
10613 case OMPD_section:
10614 case OMPD_single:
10615 case OMPD_master:
10616 case OMPD_critical:
10617 case OMPD_taskgroup:
10618 case OMPD_distribute:
10619 case OMPD_ordered:
10620 case OMPD_atomic:
10621 case OMPD_distribute_simd:
10622 case OMPD_teams_distribute:
10623 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010624 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010625 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10626 case OMPD_unknown:
10627 llvm_unreachable("Unknown OpenMP directive");
10628 }
10629 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010630 case OMPC_num_teams:
10631 switch (DKind) {
10632 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010633 case OMPD_target_teams_distribute:
10634 case OMPD_target_teams_distribute_simd:
10635 case OMPD_target_teams_distribute_parallel_for:
10636 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010637 CaptureRegion = OMPD_target;
10638 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010639 case OMPD_teams_distribute_parallel_for:
10640 case OMPD_teams_distribute_parallel_for_simd:
10641 case OMPD_teams:
10642 case OMPD_teams_distribute:
10643 case OMPD_teams_distribute_simd:
10644 // Do not capture num_teams-clause expressions.
10645 break;
10646 case OMPD_distribute_parallel_for:
10647 case OMPD_distribute_parallel_for_simd:
10648 case OMPD_task:
10649 case OMPD_taskloop:
10650 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010651 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010652 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010653 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010654 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010655 case OMPD_target_data:
10656 case OMPD_target_enter_data:
10657 case OMPD_target_exit_data:
10658 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010659 case OMPD_cancel:
10660 case OMPD_parallel:
10661 case OMPD_parallel_sections:
10662 case OMPD_parallel_for:
10663 case OMPD_parallel_for_simd:
10664 case OMPD_target:
10665 case OMPD_target_simd:
10666 case OMPD_target_parallel:
10667 case OMPD_target_parallel_for:
10668 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010669 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010670 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010671 case OMPD_taskyield:
10672 case OMPD_barrier:
10673 case OMPD_taskwait:
10674 case OMPD_cancellation_point:
10675 case OMPD_flush:
10676 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010677 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010678 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010679 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010680 case OMPD_declare_target:
10681 case OMPD_end_declare_target:
10682 case OMPD_simd:
10683 case OMPD_for:
10684 case OMPD_for_simd:
10685 case OMPD_sections:
10686 case OMPD_section:
10687 case OMPD_single:
10688 case OMPD_master:
10689 case OMPD_critical:
10690 case OMPD_taskgroup:
10691 case OMPD_distribute:
10692 case OMPD_ordered:
10693 case OMPD_atomic:
10694 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010695 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010696 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10697 case OMPD_unknown:
10698 llvm_unreachable("Unknown OpenMP directive");
10699 }
10700 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010701 case OMPC_thread_limit:
10702 switch (DKind) {
10703 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010704 case OMPD_target_teams_distribute:
10705 case OMPD_target_teams_distribute_simd:
10706 case OMPD_target_teams_distribute_parallel_for:
10707 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010708 CaptureRegion = OMPD_target;
10709 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010710 case OMPD_teams_distribute_parallel_for:
10711 case OMPD_teams_distribute_parallel_for_simd:
10712 case OMPD_teams:
10713 case OMPD_teams_distribute:
10714 case OMPD_teams_distribute_simd:
10715 // Do not capture thread_limit-clause expressions.
10716 break;
10717 case OMPD_distribute_parallel_for:
10718 case OMPD_distribute_parallel_for_simd:
10719 case OMPD_task:
10720 case OMPD_taskloop:
10721 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010722 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010723 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010724 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010725 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010726 case OMPD_target_data:
10727 case OMPD_target_enter_data:
10728 case OMPD_target_exit_data:
10729 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010730 case OMPD_cancel:
10731 case OMPD_parallel:
10732 case OMPD_parallel_sections:
10733 case OMPD_parallel_for:
10734 case OMPD_parallel_for_simd:
10735 case OMPD_target:
10736 case OMPD_target_simd:
10737 case OMPD_target_parallel:
10738 case OMPD_target_parallel_for:
10739 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010740 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010741 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010742 case OMPD_taskyield:
10743 case OMPD_barrier:
10744 case OMPD_taskwait:
10745 case OMPD_cancellation_point:
10746 case OMPD_flush:
10747 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010748 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010749 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010750 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010751 case OMPD_declare_target:
10752 case OMPD_end_declare_target:
10753 case OMPD_simd:
10754 case OMPD_for:
10755 case OMPD_for_simd:
10756 case OMPD_sections:
10757 case OMPD_section:
10758 case OMPD_single:
10759 case OMPD_master:
10760 case OMPD_critical:
10761 case OMPD_taskgroup:
10762 case OMPD_distribute:
10763 case OMPD_ordered:
10764 case OMPD_atomic:
10765 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010766 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010767 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10768 case OMPD_unknown:
10769 llvm_unreachable("Unknown OpenMP directive");
10770 }
10771 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010772 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010773 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010774 case OMPD_parallel_for:
10775 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010776 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010777 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010778 case OMPD_teams_distribute_parallel_for:
10779 case OMPD_teams_distribute_parallel_for_simd:
10780 case OMPD_target_parallel_for:
10781 case OMPD_target_parallel_for_simd:
10782 case OMPD_target_teams_distribute_parallel_for:
10783 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010784 CaptureRegion = OMPD_parallel;
10785 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010786 case OMPD_for:
10787 case OMPD_for_simd:
10788 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010789 break;
10790 case OMPD_task:
10791 case OMPD_taskloop:
10792 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010793 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010794 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010795 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010796 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010797 case OMPD_target_data:
10798 case OMPD_target_enter_data:
10799 case OMPD_target_exit_data:
10800 case OMPD_target_update:
10801 case OMPD_teams:
10802 case OMPD_teams_distribute:
10803 case OMPD_teams_distribute_simd:
10804 case OMPD_target_teams_distribute:
10805 case OMPD_target_teams_distribute_simd:
10806 case OMPD_target:
10807 case OMPD_target_simd:
10808 case OMPD_target_parallel:
10809 case OMPD_cancel:
10810 case OMPD_parallel:
10811 case OMPD_parallel_sections:
10812 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010813 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010814 case OMPD_taskyield:
10815 case OMPD_barrier:
10816 case OMPD_taskwait:
10817 case OMPD_cancellation_point:
10818 case OMPD_flush:
10819 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010820 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010821 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010822 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010823 case OMPD_declare_target:
10824 case OMPD_end_declare_target:
10825 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010826 case OMPD_sections:
10827 case OMPD_section:
10828 case OMPD_single:
10829 case OMPD_master:
10830 case OMPD_critical:
10831 case OMPD_taskgroup:
10832 case OMPD_distribute:
10833 case OMPD_ordered:
10834 case OMPD_atomic:
10835 case OMPD_distribute_simd:
10836 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010837 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010838 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10839 case OMPD_unknown:
10840 llvm_unreachable("Unknown OpenMP directive");
10841 }
10842 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010843 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010844 switch (DKind) {
10845 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010846 case OMPD_teams_distribute_parallel_for_simd:
10847 case OMPD_teams_distribute:
10848 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010849 case OMPD_target_teams_distribute_parallel_for:
10850 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010851 case OMPD_target_teams_distribute:
10852 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010853 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010854 break;
10855 case OMPD_distribute_parallel_for:
10856 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010857 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010858 case OMPD_distribute_simd:
10859 // Do not capture thread_limit-clause expressions.
10860 break;
10861 case OMPD_parallel_for:
10862 case OMPD_parallel_for_simd:
10863 case OMPD_target_parallel_for_simd:
10864 case OMPD_target_parallel_for:
10865 case OMPD_task:
10866 case OMPD_taskloop:
10867 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010868 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010869 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010870 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010871 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010872 case OMPD_target_data:
10873 case OMPD_target_enter_data:
10874 case OMPD_target_exit_data:
10875 case OMPD_target_update:
10876 case OMPD_teams:
10877 case OMPD_target:
10878 case OMPD_target_simd:
10879 case OMPD_target_parallel:
10880 case OMPD_cancel:
10881 case OMPD_parallel:
10882 case OMPD_parallel_sections:
10883 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010884 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010885 case OMPD_taskyield:
10886 case OMPD_barrier:
10887 case OMPD_taskwait:
10888 case OMPD_cancellation_point:
10889 case OMPD_flush:
10890 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010891 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010892 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010893 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010894 case OMPD_declare_target:
10895 case OMPD_end_declare_target:
10896 case OMPD_simd:
10897 case OMPD_for:
10898 case OMPD_for_simd:
10899 case OMPD_sections:
10900 case OMPD_section:
10901 case OMPD_single:
10902 case OMPD_master:
10903 case OMPD_critical:
10904 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010905 case OMPD_ordered:
10906 case OMPD_atomic:
10907 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010908 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010909 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10910 case OMPD_unknown:
10911 llvm_unreachable("Unknown OpenMP directive");
10912 }
10913 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010914 case OMPC_device:
10915 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010916 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010917 case OMPD_target_enter_data:
10918 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000010919 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000010920 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000010921 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000010922 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000010923 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000010924 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000010925 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000010926 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000010927 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000010928 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010929 CaptureRegion = OMPD_task;
10930 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010931 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010932 // Do not capture device-clause expressions.
10933 break;
10934 case OMPD_teams_distribute_parallel_for:
10935 case OMPD_teams_distribute_parallel_for_simd:
10936 case OMPD_teams:
10937 case OMPD_teams_distribute:
10938 case OMPD_teams_distribute_simd:
10939 case OMPD_distribute_parallel_for:
10940 case OMPD_distribute_parallel_for_simd:
10941 case OMPD_task:
10942 case OMPD_taskloop:
10943 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010944 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010945 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010946 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010947 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010948 case OMPD_cancel:
10949 case OMPD_parallel:
10950 case OMPD_parallel_sections:
10951 case OMPD_parallel_for:
10952 case OMPD_parallel_for_simd:
10953 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010954 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010955 case OMPD_taskyield:
10956 case OMPD_barrier:
10957 case OMPD_taskwait:
10958 case OMPD_cancellation_point:
10959 case OMPD_flush:
10960 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010961 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010962 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010963 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010964 case OMPD_declare_target:
10965 case OMPD_end_declare_target:
10966 case OMPD_simd:
10967 case OMPD_for:
10968 case OMPD_for_simd:
10969 case OMPD_sections:
10970 case OMPD_section:
10971 case OMPD_single:
10972 case OMPD_master:
10973 case OMPD_critical:
10974 case OMPD_taskgroup:
10975 case OMPD_distribute:
10976 case OMPD_ordered:
10977 case OMPD_atomic:
10978 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010979 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010980 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10981 case OMPD_unknown:
10982 llvm_unreachable("Unknown OpenMP directive");
10983 }
10984 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010985 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000010986 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000010987 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000010988 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010989 switch (DKind) {
10990 case OMPD_task:
10991 case OMPD_taskloop:
10992 case OMPD_taskloop_simd:
10993 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010994 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010995 break;
10996 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010997 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010998 CaptureRegion = OMPD_parallel;
10999 break;
11000 case OMPD_target_update:
11001 case OMPD_target_enter_data:
11002 case OMPD_target_exit_data:
11003 case OMPD_target:
11004 case OMPD_target_simd:
11005 case OMPD_target_teams:
11006 case OMPD_target_parallel:
11007 case OMPD_target_teams_distribute:
11008 case OMPD_target_teams_distribute_simd:
11009 case OMPD_target_parallel_for:
11010 case OMPD_target_parallel_for_simd:
11011 case OMPD_target_teams_distribute_parallel_for:
11012 case OMPD_target_teams_distribute_parallel_for_simd:
11013 case OMPD_target_data:
11014 case OMPD_teams_distribute_parallel_for:
11015 case OMPD_teams_distribute_parallel_for_simd:
11016 case OMPD_teams:
11017 case OMPD_teams_distribute:
11018 case OMPD_teams_distribute_simd:
11019 case OMPD_distribute_parallel_for:
11020 case OMPD_distribute_parallel_for_simd:
11021 case OMPD_cancel:
11022 case OMPD_parallel:
11023 case OMPD_parallel_sections:
11024 case OMPD_parallel_for:
11025 case OMPD_parallel_for_simd:
11026 case OMPD_threadprivate:
11027 case OMPD_allocate:
11028 case OMPD_taskyield:
11029 case OMPD_barrier:
11030 case OMPD_taskwait:
11031 case OMPD_cancellation_point:
11032 case OMPD_flush:
11033 case OMPD_declare_reduction:
11034 case OMPD_declare_mapper:
11035 case OMPD_declare_simd:
11036 case OMPD_declare_variant:
11037 case OMPD_declare_target:
11038 case OMPD_end_declare_target:
11039 case OMPD_simd:
11040 case OMPD_for:
11041 case OMPD_for_simd:
11042 case OMPD_sections:
11043 case OMPD_section:
11044 case OMPD_single:
11045 case OMPD_master:
11046 case OMPD_critical:
11047 case OMPD_taskgroup:
11048 case OMPD_distribute:
11049 case OMPD_ordered:
11050 case OMPD_atomic:
11051 case OMPD_distribute_simd:
11052 case OMPD_requires:
11053 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11054 case OMPD_unknown:
11055 llvm_unreachable("Unknown OpenMP directive");
11056 }
11057 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011058 case OMPC_firstprivate:
11059 case OMPC_lastprivate:
11060 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011061 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011062 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011063 case OMPC_linear:
11064 case OMPC_default:
11065 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011066 case OMPC_safelen:
11067 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011068 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011069 case OMPC_collapse:
11070 case OMPC_private:
11071 case OMPC_shared:
11072 case OMPC_aligned:
11073 case OMPC_copyin:
11074 case OMPC_copyprivate:
11075 case OMPC_ordered:
11076 case OMPC_nowait:
11077 case OMPC_untied:
11078 case OMPC_mergeable:
11079 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011080 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011081 case OMPC_flush:
11082 case OMPC_read:
11083 case OMPC_write:
11084 case OMPC_update:
11085 case OMPC_capture:
11086 case OMPC_seq_cst:
11087 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011088 case OMPC_threads:
11089 case OMPC_simd:
11090 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011091 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011092 case OMPC_hint:
11093 case OMPC_defaultmap:
11094 case OMPC_unknown:
11095 case OMPC_uniform:
11096 case OMPC_to:
11097 case OMPC_from:
11098 case OMPC_use_device_ptr:
11099 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011100 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011101 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011102 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011103 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011104 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011105 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011106 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011107 llvm_unreachable("Unexpected OpenMP clause.");
11108 }
11109 return CaptureRegion;
11110}
11111
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011112OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11113 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011114 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011115 SourceLocation NameModifierLoc,
11116 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011117 SourceLocation EndLoc) {
11118 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011119 Stmt *HelperValStmt = nullptr;
11120 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011121 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11122 !Condition->isInstantiationDependent() &&
11123 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011124 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011125 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011126 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011127
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011128 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011129
11130 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11131 CaptureRegion =
11132 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011133 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011134 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011135 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011136 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11137 HelperValStmt = buildPreInits(Context, Captures);
11138 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011139 }
11140
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011141 return new (Context)
11142 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11143 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011144}
11145
Alexey Bataev3778b602014-07-17 07:32:53 +000011146OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11147 SourceLocation StartLoc,
11148 SourceLocation LParenLoc,
11149 SourceLocation EndLoc) {
11150 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011151 Stmt *HelperValStmt = nullptr;
11152 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011153 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11154 !Condition->isInstantiationDependent() &&
11155 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011156 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011157 if (Val.isInvalid())
11158 return nullptr;
11159
Richard Smith03a4aa32016-06-23 19:02:52 +000011160 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011161
11162 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11163 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_final);
11164 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11165 ValExpr = MakeFullExpr(ValExpr).get();
11166 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11167 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11168 HelperValStmt = buildPreInits(Context, Captures);
11169 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011170 }
11171
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011172 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11173 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011174}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011175
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011176ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11177 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011178 if (!Op)
11179 return ExprError();
11180
11181 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11182 public:
11183 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011184 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011185 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11186 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011187 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11188 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011189 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11190 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011191 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11192 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011193 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11194 QualType T,
11195 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011196 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11197 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011198 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11199 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011200 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011201 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011202 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011203 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11204 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011205 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11206 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011207 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11208 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011209 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011210 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011211 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011212 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11213 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011214 llvm_unreachable("conversion functions are permitted");
11215 }
11216 } ConvertDiagnoser;
11217 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11218}
11219
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011220static bool
11221isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11222 bool StrictlyPositive, bool BuildCapture = false,
11223 OpenMPDirectiveKind DKind = OMPD_unknown,
11224 OpenMPDirectiveKind *CaptureRegion = nullptr,
11225 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011226 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11227 !ValExpr->isInstantiationDependent()) {
11228 SourceLocation Loc = ValExpr->getExprLoc();
11229 ExprResult Value =
11230 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11231 if (Value.isInvalid())
11232 return false;
11233
11234 ValExpr = Value.get();
11235 // The expression must evaluate to a non-negative integer value.
11236 llvm::APSInt Result;
11237 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011238 Result.isSigned() &&
11239 !((!StrictlyPositive && Result.isNonNegative()) ||
11240 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011241 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011242 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11243 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011244 return false;
11245 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011246 if (!BuildCapture)
11247 return true;
11248 *CaptureRegion = getOpenMPCaptureRegionForClause(DKind, CKind);
11249 if (*CaptureRegion != OMPD_unknown &&
11250 !SemaRef.CurContext->isDependentContext()) {
11251 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11252 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11253 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11254 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11255 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011256 }
11257 return true;
11258}
11259
Alexey Bataev568a8332014-03-06 06:15:19 +000011260OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11261 SourceLocation StartLoc,
11262 SourceLocation LParenLoc,
11263 SourceLocation EndLoc) {
11264 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011265 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011266
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011267 // OpenMP [2.5, Restrictions]
11268 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011269 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011270 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011271 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011272
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011273 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011274 OpenMPDirectiveKind CaptureRegion =
11275 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
11276 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011277 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011278 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011279 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11280 HelperValStmt = buildPreInits(Context, Captures);
11281 }
11282
11283 return new (Context) OMPNumThreadsClause(
11284 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011285}
11286
Alexey Bataev62c87d22014-03-21 04:51:18 +000011287ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011288 OpenMPClauseKind CKind,
11289 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011290 if (!E)
11291 return ExprError();
11292 if (E->isValueDependent() || E->isTypeDependent() ||
11293 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011294 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011295 llvm::APSInt Result;
11296 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11297 if (ICE.isInvalid())
11298 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011299 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11300 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011301 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011302 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11303 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011304 return ExprError();
11305 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011306 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11307 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11308 << E->getSourceRange();
11309 return ExprError();
11310 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011311 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11312 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011313 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011314 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011315 return ICE;
11316}
11317
11318OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11319 SourceLocation LParenLoc,
11320 SourceLocation EndLoc) {
11321 // OpenMP [2.8.1, simd construct, Description]
11322 // The parameter of the safelen clause must be a constant
11323 // positive integer expression.
11324 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11325 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011326 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011327 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011328 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011329}
11330
Alexey Bataev66b15b52015-08-21 11:14:16 +000011331OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11332 SourceLocation LParenLoc,
11333 SourceLocation EndLoc) {
11334 // OpenMP [2.8.1, simd construct, Description]
11335 // The parameter of the simdlen clause must be a constant
11336 // positive integer expression.
11337 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11338 if (Simdlen.isInvalid())
11339 return nullptr;
11340 return new (Context)
11341 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11342}
11343
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011344/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011345static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11346 DSAStackTy *Stack) {
11347 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011348 if (!OMPAllocatorHandleT.isNull())
11349 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011350 // Build the predefined allocator expressions.
11351 bool ErrorFound = false;
11352 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11353 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11354 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11355 StringRef Allocator =
11356 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11357 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11358 auto *VD = dyn_cast_or_null<ValueDecl>(
11359 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11360 if (!VD) {
11361 ErrorFound = true;
11362 break;
11363 }
11364 QualType AllocatorType =
11365 VD->getType().getNonLValueExprType(S.getASTContext());
11366 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11367 if (!Res.isUsable()) {
11368 ErrorFound = true;
11369 break;
11370 }
11371 if (OMPAllocatorHandleT.isNull())
11372 OMPAllocatorHandleT = AllocatorType;
11373 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11374 ErrorFound = true;
11375 break;
11376 }
11377 Stack->setAllocator(AllocatorKind, Res.get());
11378 }
11379 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011380 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11381 return false;
11382 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011383 OMPAllocatorHandleT.addConst();
11384 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011385 return true;
11386}
11387
11388OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11389 SourceLocation LParenLoc,
11390 SourceLocation EndLoc) {
11391 // OpenMP [2.11.3, allocate Directive, Description]
11392 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011393 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011394 return nullptr;
11395
11396 ExprResult Allocator = DefaultLvalueConversion(A);
11397 if (Allocator.isInvalid())
11398 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011399 Allocator = PerformImplicitConversion(Allocator.get(),
11400 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011401 Sema::AA_Initializing,
11402 /*AllowExplicit=*/true);
11403 if (Allocator.isInvalid())
11404 return nullptr;
11405 return new (Context)
11406 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11407}
11408
Alexander Musman64d33f12014-06-04 07:53:32 +000011409OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11410 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011411 SourceLocation LParenLoc,
11412 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011413 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011414 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011415 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011416 // The parameter of the collapse clause must be a constant
11417 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011418 ExprResult NumForLoopsResult =
11419 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11420 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011421 return nullptr;
11422 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011423 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011424}
11425
Alexey Bataev10e775f2015-07-30 11:36:16 +000011426OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11427 SourceLocation EndLoc,
11428 SourceLocation LParenLoc,
11429 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011430 // OpenMP [2.7.1, loop construct, Description]
11431 // OpenMP [2.8.1, simd construct, Description]
11432 // OpenMP [2.9.6, distribute construct, Description]
11433 // The parameter of the ordered clause must be a constant
11434 // positive integer expression if any.
11435 if (NumForLoops && LParenLoc.isValid()) {
11436 ExprResult NumForLoopsResult =
11437 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11438 if (NumForLoopsResult.isInvalid())
11439 return nullptr;
11440 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011441 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011442 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011443 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011444 auto *Clause = OMPOrderedClause::Create(
11445 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11446 StartLoc, LParenLoc, EndLoc);
11447 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11448 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011449}
11450
Alexey Bataeved09d242014-05-28 05:53:51 +000011451OMPClause *Sema::ActOnOpenMPSimpleClause(
11452 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11453 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011454 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011455 switch (Kind) {
11456 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011457 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011458 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11459 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011460 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011461 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000011462 Res = ActOnOpenMPProcBindClause(
11463 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11464 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011465 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011466 case OMPC_atomic_default_mem_order:
11467 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11468 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11469 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11470 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011471 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011472 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011473 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011474 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011475 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011476 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011477 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011478 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011479 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011480 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011481 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011482 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011483 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011484 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011485 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011486 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011487 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011488 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011489 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011490 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011491 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011492 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011493 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011494 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011495 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011496 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011497 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011498 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011499 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011500 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011501 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011502 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011503 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011504 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011505 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011506 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011507 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011508 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011509 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011510 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011511 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011512 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011513 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011514 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011515 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011516 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011517 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011518 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011519 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011520 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011521 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011522 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011523 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011524 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011525 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011526 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011527 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011528 llvm_unreachable("Clause is not allowed.");
11529 }
11530 return Res;
11531}
11532
Alexey Bataev6402bca2015-12-28 07:25:51 +000011533static std::string
11534getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11535 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011536 SmallString<256> Buffer;
11537 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011538 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11539 unsigned Skipped = Exclude.size();
11540 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011541 for (unsigned I = First; I < Last; ++I) {
11542 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011543 --Skipped;
11544 continue;
11545 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011546 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11547 if (I == Bound - Skipped)
11548 Out << " or ";
11549 else if (I != Bound + 1 - Skipped)
11550 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011551 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011552 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011553}
11554
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011555OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11556 SourceLocation KindKwLoc,
11557 SourceLocation StartLoc,
11558 SourceLocation LParenLoc,
11559 SourceLocation EndLoc) {
11560 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011561 static_assert(OMPC_DEFAULT_unknown > 0,
11562 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011563 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011564 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11565 /*Last=*/OMPC_DEFAULT_unknown)
11566 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011567 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011568 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011569 switch (Kind) {
11570 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011571 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011572 break;
11573 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011574 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011575 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011576 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011577 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011578 break;
11579 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011580 return new (Context)
11581 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011582}
11583
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011584OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11585 SourceLocation KindKwLoc,
11586 SourceLocation StartLoc,
11587 SourceLocation LParenLoc,
11588 SourceLocation EndLoc) {
11589 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011590 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011591 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11592 /*Last=*/OMPC_PROC_BIND_unknown)
11593 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011594 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011595 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011596 return new (Context)
11597 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011598}
11599
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011600OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11601 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11602 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11603 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11604 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11605 << getListOfPossibleValues(
11606 OMPC_atomic_default_mem_order, /*First=*/0,
11607 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11608 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11609 return nullptr;
11610 }
11611 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11612 LParenLoc, EndLoc);
11613}
11614
Alexey Bataev56dafe82014-06-20 07:16:17 +000011615OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011616 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011617 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011618 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011619 SourceLocation EndLoc) {
11620 OMPClause *Res = nullptr;
11621 switch (Kind) {
11622 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011623 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11624 assert(Argument.size() == NumberOfElements &&
11625 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011626 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011627 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11628 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11629 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11630 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11631 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011632 break;
11633 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011634 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11635 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11636 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11637 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011638 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011639 case OMPC_dist_schedule:
11640 Res = ActOnOpenMPDistScheduleClause(
11641 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11642 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11643 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011644 case OMPC_defaultmap:
11645 enum { Modifier, DefaultmapKind };
11646 Res = ActOnOpenMPDefaultmapClause(
11647 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11648 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011649 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11650 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011651 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011652 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011653 case OMPC_num_threads:
11654 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011655 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011656 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011657 case OMPC_collapse:
11658 case OMPC_default:
11659 case OMPC_proc_bind:
11660 case OMPC_private:
11661 case OMPC_firstprivate:
11662 case OMPC_lastprivate:
11663 case OMPC_shared:
11664 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011665 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011666 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011667 case OMPC_linear:
11668 case OMPC_aligned:
11669 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011670 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011671 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011672 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011673 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011674 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011675 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011676 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011677 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011678 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011679 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011680 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011681 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011682 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011683 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011684 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011685 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011686 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011687 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011688 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011689 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011690 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011691 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011692 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011693 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011694 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011695 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011696 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011697 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011698 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011699 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011700 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011701 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011702 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011703 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011704 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011705 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011706 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011707 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011708 llvm_unreachable("Clause is not allowed.");
11709 }
11710 return Res;
11711}
11712
Alexey Bataev6402bca2015-12-28 07:25:51 +000011713static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11714 OpenMPScheduleClauseModifier M2,
11715 SourceLocation M1Loc, SourceLocation M2Loc) {
11716 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11717 SmallVector<unsigned, 2> Excluded;
11718 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11719 Excluded.push_back(M2);
11720 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11721 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11722 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11723 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11724 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11725 << getListOfPossibleValues(OMPC_schedule,
11726 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11727 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11728 Excluded)
11729 << getOpenMPClauseName(OMPC_schedule);
11730 return true;
11731 }
11732 return false;
11733}
11734
Alexey Bataev56dafe82014-06-20 07:16:17 +000011735OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011736 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011737 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011738 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11739 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11740 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11741 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11742 return nullptr;
11743 // OpenMP, 2.7.1, Loop Construct, Restrictions
11744 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11745 // but not both.
11746 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11747 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11748 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11749 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11750 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11751 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11752 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11753 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11754 return nullptr;
11755 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011756 if (Kind == OMPC_SCHEDULE_unknown) {
11757 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011758 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11759 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11760 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11761 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11762 Exclude);
11763 } else {
11764 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11765 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011766 }
11767 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11768 << Values << getOpenMPClauseName(OMPC_schedule);
11769 return nullptr;
11770 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011771 // OpenMP, 2.7.1, Loop Construct, Restrictions
11772 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11773 // schedule(guided).
11774 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11775 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11776 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11777 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11778 diag::err_omp_schedule_nonmonotonic_static);
11779 return nullptr;
11780 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011781 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011782 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011783 if (ChunkSize) {
11784 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11785 !ChunkSize->isInstantiationDependent() &&
11786 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011787 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000011788 ExprResult Val =
11789 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11790 if (Val.isInvalid())
11791 return nullptr;
11792
11793 ValExpr = Val.get();
11794
11795 // OpenMP [2.7.1, Restrictions]
11796 // chunk_size must be a loop invariant integer expression with a positive
11797 // value.
11798 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000011799 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11800 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11801 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011802 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000011803 return nullptr;
11804 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000011805 } else if (getOpenMPCaptureRegionForClause(
11806 DSAStack->getCurrentDirective(), OMPC_schedule) !=
11807 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011808 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011809 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011810 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000011811 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11812 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011813 }
11814 }
11815 }
11816
Alexey Bataev6402bca2015-12-28 07:25:51 +000011817 return new (Context)
11818 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000011819 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011820}
11821
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011822OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
11823 SourceLocation StartLoc,
11824 SourceLocation EndLoc) {
11825 OMPClause *Res = nullptr;
11826 switch (Kind) {
11827 case OMPC_ordered:
11828 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
11829 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000011830 case OMPC_nowait:
11831 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
11832 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011833 case OMPC_untied:
11834 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
11835 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011836 case OMPC_mergeable:
11837 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
11838 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011839 case OMPC_read:
11840 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
11841 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000011842 case OMPC_write:
11843 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
11844 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000011845 case OMPC_update:
11846 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
11847 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000011848 case OMPC_capture:
11849 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
11850 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011851 case OMPC_seq_cst:
11852 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
11853 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000011854 case OMPC_threads:
11855 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
11856 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011857 case OMPC_simd:
11858 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
11859 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000011860 case OMPC_nogroup:
11861 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
11862 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011863 case OMPC_unified_address:
11864 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
11865 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011866 case OMPC_unified_shared_memory:
11867 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11868 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011869 case OMPC_reverse_offload:
11870 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
11871 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011872 case OMPC_dynamic_allocators:
11873 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
11874 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011875 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011876 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011877 case OMPC_num_threads:
11878 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011879 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011880 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011881 case OMPC_collapse:
11882 case OMPC_schedule:
11883 case OMPC_private:
11884 case OMPC_firstprivate:
11885 case OMPC_lastprivate:
11886 case OMPC_shared:
11887 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011888 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011889 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011890 case OMPC_linear:
11891 case OMPC_aligned:
11892 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011893 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011894 case OMPC_default:
11895 case OMPC_proc_bind:
11896 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011897 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011898 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011899 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011900 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011901 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011902 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011903 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011904 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011905 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000011906 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011907 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011908 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011909 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011910 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011911 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011912 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011913 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011914 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011915 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011916 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011917 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011918 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011919 llvm_unreachable("Clause is not allowed.");
11920 }
11921 return Res;
11922}
11923
Alexey Bataev236070f2014-06-20 11:19:47 +000011924OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11925 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000011926 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000011927 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
11928}
11929
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011930OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11931 SourceLocation EndLoc) {
11932 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
11933}
11934
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011935OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11936 SourceLocation EndLoc) {
11937 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
11938}
11939
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011940OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
11941 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011942 return new (Context) OMPReadClause(StartLoc, EndLoc);
11943}
11944
Alexey Bataevdea47612014-07-23 07:46:59 +000011945OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
11946 SourceLocation EndLoc) {
11947 return new (Context) OMPWriteClause(StartLoc, EndLoc);
11948}
11949
Alexey Bataev67a4f222014-07-23 10:25:33 +000011950OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11951 SourceLocation EndLoc) {
11952 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
11953}
11954
Alexey Bataev459dec02014-07-24 06:46:57 +000011955OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11956 SourceLocation EndLoc) {
11957 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
11958}
11959
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011960OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11961 SourceLocation EndLoc) {
11962 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
11963}
11964
Alexey Bataev346265e2015-09-25 10:37:12 +000011965OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11966 SourceLocation EndLoc) {
11967 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
11968}
11969
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011970OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11971 SourceLocation EndLoc) {
11972 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
11973}
11974
Alexey Bataevb825de12015-12-07 10:51:44 +000011975OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11976 SourceLocation EndLoc) {
11977 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
11978}
11979
Kelvin Li1408f912018-09-26 04:28:39 +000011980OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11981 SourceLocation EndLoc) {
11982 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
11983}
11984
Patrick Lyster4a370b92018-10-01 13:47:43 +000011985OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11986 SourceLocation EndLoc) {
11987 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11988}
11989
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011990OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11991 SourceLocation EndLoc) {
11992 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
11993}
11994
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011995OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11996 SourceLocation EndLoc) {
11997 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
11998}
11999
Alexey Bataevc5e02582014-06-16 07:08:35 +000012000OMPClause *Sema::ActOnOpenMPVarListClause(
12001 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012002 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12003 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
12004 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000012005 OpenMPLinearClauseKind LinKind,
12006 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012007 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
12008 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
12009 SourceLocation StartLoc = Locs.StartLoc;
12010 SourceLocation LParenLoc = Locs.LParenLoc;
12011 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012012 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012013 switch (Kind) {
12014 case OMPC_private:
12015 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12016 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012017 case OMPC_firstprivate:
12018 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12019 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012020 case OMPC_lastprivate:
12021 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12022 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012023 case OMPC_shared:
12024 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12025 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012026 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012027 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012028 EndLoc, ReductionOrMapperIdScopeSpec,
12029 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012030 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012031 case OMPC_task_reduction:
12032 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012033 EndLoc, ReductionOrMapperIdScopeSpec,
12034 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012035 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012036 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012037 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12038 EndLoc, ReductionOrMapperIdScopeSpec,
12039 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012040 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012041 case OMPC_linear:
12042 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012043 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012044 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012045 case OMPC_aligned:
12046 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12047 ColonLoc, EndLoc);
12048 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012049 case OMPC_copyin:
12050 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12051 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012052 case OMPC_copyprivate:
12053 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12054 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012055 case OMPC_flush:
12056 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12057 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012058 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000012059 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012060 StartLoc, LParenLoc, EndLoc);
12061 break;
12062 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012063 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
12064 ReductionOrMapperIdScopeSpec,
12065 ReductionOrMapperId, MapType, IsMapTypeImplicit,
12066 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012067 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012068 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012069 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12070 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012071 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012072 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012073 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12074 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012075 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012076 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012077 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012078 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012079 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012080 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012081 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012082 case OMPC_allocate:
12083 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12084 ColonLoc, EndLoc);
12085 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012086 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012087 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012088 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012089 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012090 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012091 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012092 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012093 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012094 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012095 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012096 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012097 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012098 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012099 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012100 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012101 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012102 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012103 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012104 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012105 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012106 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012107 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012108 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012109 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012110 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012111 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012112 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012113 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012114 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012115 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012116 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012117 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012118 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012119 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012120 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012121 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012122 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012123 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012124 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012125 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012126 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012127 llvm_unreachable("Clause is not allowed.");
12128 }
12129 return Res;
12130}
12131
Alexey Bataev90c228f2016-02-08 09:29:13 +000012132ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012133 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012134 ExprResult Res = BuildDeclRefExpr(
12135 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12136 if (!Res.isUsable())
12137 return ExprError();
12138 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12139 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12140 if (!Res.isUsable())
12141 return ExprError();
12142 }
12143 if (VK != VK_LValue && Res.get()->isGLValue()) {
12144 Res = DefaultLvalueConversion(Res.get());
12145 if (!Res.isUsable())
12146 return ExprError();
12147 }
12148 return Res;
12149}
12150
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012151OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12152 SourceLocation StartLoc,
12153 SourceLocation LParenLoc,
12154 SourceLocation EndLoc) {
12155 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012156 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012157 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012158 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012159 SourceLocation ELoc;
12160 SourceRange ERange;
12161 Expr *SimpleRefExpr = RefExpr;
12162 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012163 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012164 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012165 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012166 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012167 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012168 ValueDecl *D = Res.first;
12169 if (!D)
12170 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012171
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012172 QualType Type = D->getType();
12173 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012174
12175 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12176 // A variable that appears in a private clause must not have an incomplete
12177 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012178 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012179 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012180 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012181
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012182 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12183 // A variable that is privatized must not have a const-qualified type
12184 // unless it is of class type with a mutable member. This restriction does
12185 // not apply to the firstprivate clause.
12186 //
12187 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12188 // A variable that appears in a private clause must not have a
12189 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012190 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012191 continue;
12192
Alexey Bataev758e55e2013-09-06 18:03:48 +000012193 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12194 // in a Construct]
12195 // Variables with the predetermined data-sharing attributes may not be
12196 // listed in data-sharing attributes clauses, except for the cases
12197 // listed below. For these exceptions only, listing a predetermined
12198 // variable in a data-sharing attribute clause is allowed and overrides
12199 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012200 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012201 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012202 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12203 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012204 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012205 continue;
12206 }
12207
Alexey Bataeve3727102018-04-18 15:57:46 +000012208 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012209 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012210 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012211 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012212 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12213 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012214 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012215 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012216 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012217 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012218 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012219 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012220 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012221 continue;
12222 }
12223
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012224 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12225 // A list item cannot appear in both a map clause and a data-sharing
12226 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012227 //
12228 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12229 // A list item cannot appear in both a map clause and a data-sharing
12230 // attribute clause on the same construct unless the construct is a
12231 // combined construct.
12232 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12233 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012234 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012235 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012236 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012237 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12238 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12239 ConflictKind = WhereFoundClauseKind;
12240 return true;
12241 })) {
12242 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012243 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012244 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012245 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012246 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012247 continue;
12248 }
12249 }
12250
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012251 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12252 // A variable of class type (or array thereof) that appears in a private
12253 // clause requires an accessible, unambiguous default constructor for the
12254 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012255 // Generate helper private variable and initialize it with the default
12256 // value. The address of the original variable is replaced by the address of
12257 // the new private variable in CodeGen. This new variable is not added to
12258 // IdResolver, so the code in the OpenMP region uses original variable for
12259 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012260 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012261 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012262 buildVarDecl(*this, ELoc, Type, D->getName(),
12263 D->hasAttrs() ? &D->getAttrs() : nullptr,
12264 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012265 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012266 if (VDPrivate->isInvalidDecl())
12267 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012268 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012269 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012270
Alexey Bataev90c228f2016-02-08 09:29:13 +000012271 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012272 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012273 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012274 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012275 Vars.push_back((VD || CurContext->isDependentContext())
12276 ? RefExpr->IgnoreParens()
12277 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012278 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012279 }
12280
Alexey Bataeved09d242014-05-28 05:53:51 +000012281 if (Vars.empty())
12282 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012283
Alexey Bataev03b340a2014-10-21 03:16:40 +000012284 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12285 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012286}
12287
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012288namespace {
12289class DiagsUninitializedSeveretyRAII {
12290private:
12291 DiagnosticsEngine &Diags;
12292 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012293 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012294
12295public:
12296 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12297 bool IsIgnored)
12298 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12299 if (!IsIgnored) {
12300 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12301 /*Map*/ diag::Severity::Ignored, Loc);
12302 }
12303 }
12304 ~DiagsUninitializedSeveretyRAII() {
12305 if (!IsIgnored)
12306 Diags.popMappings(SavedLoc);
12307 }
12308};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012309}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012310
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012311OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12312 SourceLocation StartLoc,
12313 SourceLocation LParenLoc,
12314 SourceLocation EndLoc) {
12315 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012316 SmallVector<Expr *, 8> PrivateCopies;
12317 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012318 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012319 bool IsImplicitClause =
12320 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012321 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012322
Alexey Bataeve3727102018-04-18 15:57:46 +000012323 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012324 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012325 SourceLocation ELoc;
12326 SourceRange ERange;
12327 Expr *SimpleRefExpr = RefExpr;
12328 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012329 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012330 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012331 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012332 PrivateCopies.push_back(nullptr);
12333 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012334 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012335 ValueDecl *D = Res.first;
12336 if (!D)
12337 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012338
Alexey Bataev60da77e2016-02-29 05:54:20 +000012339 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012340 QualType Type = D->getType();
12341 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012342
12343 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12344 // A variable that appears in a private clause must not have an incomplete
12345 // type or a reference type.
12346 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012347 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012348 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012349 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012350
12351 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12352 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012353 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012354 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012355 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012356
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012357 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012358 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012359 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012360 DSAStackTy::DSAVarData DVar =
12361 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012362 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012363 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012364 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012365 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12366 // A list item that specifies a given variable may not appear in more
12367 // than one clause on the same directive, except that a variable may be
12368 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012369 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12370 // A list item may appear in a firstprivate or lastprivate clause but not
12371 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012372 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012373 (isOpenMPDistributeDirective(CurrDir) ||
12374 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012375 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012376 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012377 << getOpenMPClauseName(DVar.CKind)
12378 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012379 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012380 continue;
12381 }
12382
12383 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12384 // in a Construct]
12385 // Variables with the predetermined data-sharing attributes may not be
12386 // listed in data-sharing attributes clauses, except for the cases
12387 // listed below. For these exceptions only, listing a predetermined
12388 // variable in a data-sharing attribute clause is allowed and overrides
12389 // the variable's predetermined data-sharing attributes.
12390 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12391 // in a Construct, C/C++, p.2]
12392 // Variables with const-qualified type having no mutable member may be
12393 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012394 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012395 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12396 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012397 << getOpenMPClauseName(DVar.CKind)
12398 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012399 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012400 continue;
12401 }
12402
12403 // OpenMP [2.9.3.4, Restrictions, p.2]
12404 // A list item that is private within a parallel region must not appear
12405 // in a firstprivate clause on a worksharing construct if any of the
12406 // worksharing regions arising from the worksharing construct ever bind
12407 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012408 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12409 // A list item that is private within a teams region must not appear in a
12410 // firstprivate clause on a distribute construct if any of the distribute
12411 // regions arising from the distribute construct ever bind to any of the
12412 // teams regions arising from the teams construct.
12413 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12414 // A list item that appears in a reduction clause of a teams construct
12415 // must not appear in a firstprivate clause on a distribute construct if
12416 // any of the distribute regions arising from the distribute construct
12417 // ever bind to any of the teams regions arising from the teams construct.
12418 if ((isOpenMPWorksharingDirective(CurrDir) ||
12419 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012420 !isOpenMPParallelDirective(CurrDir) &&
12421 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012422 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012423 if (DVar.CKind != OMPC_shared &&
12424 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012425 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012426 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012427 Diag(ELoc, diag::err_omp_required_access)
12428 << getOpenMPClauseName(OMPC_firstprivate)
12429 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012430 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012431 continue;
12432 }
12433 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012434 // OpenMP [2.9.3.4, Restrictions, p.3]
12435 // A list item that appears in a reduction clause of a parallel construct
12436 // must not appear in a firstprivate clause on a worksharing or task
12437 // construct if any of the worksharing or task regions arising from the
12438 // worksharing or task construct ever bind to any of the parallel regions
12439 // arising from the parallel construct.
12440 // OpenMP [2.9.3.4, Restrictions, p.4]
12441 // A list item that appears in a reduction clause in worksharing
12442 // construct must not appear in a firstprivate clause in a task construct
12443 // encountered during execution of any of the worksharing regions arising
12444 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012445 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012446 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012447 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12448 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012449 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012450 isOpenMPWorksharingDirective(K) ||
12451 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012452 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012453 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012454 if (DVar.CKind == OMPC_reduction &&
12455 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012456 isOpenMPWorksharingDirective(DVar.DKind) ||
12457 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012458 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12459 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012460 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012461 continue;
12462 }
12463 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012464
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012465 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12466 // A list item cannot appear in both a map clause and a data-sharing
12467 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012468 //
12469 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12470 // A list item cannot appear in both a map clause and a data-sharing
12471 // attribute clause on the same construct unless the construct is a
12472 // combined construct.
12473 if ((LangOpts.OpenMP <= 45 &&
12474 isOpenMPTargetExecutionDirective(CurrDir)) ||
12475 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012476 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012477 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012478 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012479 [&ConflictKind](
12480 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12481 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012482 ConflictKind = WhereFoundClauseKind;
12483 return true;
12484 })) {
12485 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012486 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012487 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012488 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012489 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012490 continue;
12491 }
12492 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012493 }
12494
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012495 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012496 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012497 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012498 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12499 << getOpenMPClauseName(OMPC_firstprivate) << Type
12500 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12501 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012502 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012503 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012504 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012505 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012506 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012507 continue;
12508 }
12509
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012510 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012511 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012512 buildVarDecl(*this, ELoc, Type, D->getName(),
12513 D->hasAttrs() ? &D->getAttrs() : nullptr,
12514 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012515 // Generate helper private variable and initialize it with the value of the
12516 // original variable. The address of the original variable is replaced by
12517 // the address of the new private variable in the CodeGen. This new variable
12518 // is not added to IdResolver, so the code in the OpenMP region uses
12519 // original variable for proper diagnostics and variable capturing.
12520 Expr *VDInitRefExpr = nullptr;
12521 // For arrays generate initializer for single element and replace it by the
12522 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012523 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012524 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012525 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012526 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012527 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012528 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012529 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12530 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012531 InitializedEntity Entity =
12532 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012533 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12534
12535 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12536 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12537 if (Result.isInvalid())
12538 VDPrivate->setInvalidDecl();
12539 else
12540 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012541 // Remove temp variable declaration.
12542 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012543 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012544 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12545 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012546 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12547 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012548 AddInitializerToDecl(VDPrivate,
12549 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012550 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012551 }
12552 if (VDPrivate->isInvalidDecl()) {
12553 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012554 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012555 diag::note_omp_task_predetermined_firstprivate_here);
12556 }
12557 continue;
12558 }
12559 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012560 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012561 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12562 RefExpr->getExprLoc());
12563 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012564 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012565 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012566 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012567 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012568 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012569 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012570 ExprCaptures.push_back(Ref->getDecl());
12571 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012572 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012573 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012574 Vars.push_back((VD || CurContext->isDependentContext())
12575 ? RefExpr->IgnoreParens()
12576 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012577 PrivateCopies.push_back(VDPrivateRefExpr);
12578 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012579 }
12580
Alexey Bataeved09d242014-05-28 05:53:51 +000012581 if (Vars.empty())
12582 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012583
12584 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012585 Vars, PrivateCopies, Inits,
12586 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012587}
12588
Alexander Musman1bb328c2014-06-04 13:06:39 +000012589OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12590 SourceLocation StartLoc,
12591 SourceLocation LParenLoc,
12592 SourceLocation EndLoc) {
12593 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012594 SmallVector<Expr *, 8> SrcExprs;
12595 SmallVector<Expr *, 8> DstExprs;
12596 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012597 SmallVector<Decl *, 4> ExprCaptures;
12598 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012599 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012600 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012601 SourceLocation ELoc;
12602 SourceRange ERange;
12603 Expr *SimpleRefExpr = RefExpr;
12604 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012605 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012606 // It will be analyzed later.
12607 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012608 SrcExprs.push_back(nullptr);
12609 DstExprs.push_back(nullptr);
12610 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012611 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012612 ValueDecl *D = Res.first;
12613 if (!D)
12614 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012615
Alexey Bataev74caaf22016-02-20 04:09:36 +000012616 QualType Type = D->getType();
12617 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012618
12619 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12620 // A variable that appears in a lastprivate clause must not have an
12621 // incomplete type or a reference type.
12622 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012623 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012624 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012625 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012626
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012627 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12628 // A variable that is privatized must not have a const-qualified type
12629 // unless it is of class type with a mutable member. This restriction does
12630 // not apply to the firstprivate clause.
12631 //
12632 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12633 // A variable that appears in a lastprivate clause must not have a
12634 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012635 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012636 continue;
12637
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012638 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012639 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12640 // in a Construct]
12641 // Variables with the predetermined data-sharing attributes may not be
12642 // listed in data-sharing attributes clauses, except for the cases
12643 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012644 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12645 // A list item may appear in a firstprivate or lastprivate clause but not
12646 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012647 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012648 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012649 (isOpenMPDistributeDirective(CurrDir) ||
12650 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012651 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12652 Diag(ELoc, diag::err_omp_wrong_dsa)
12653 << getOpenMPClauseName(DVar.CKind)
12654 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012655 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012656 continue;
12657 }
12658
Alexey Bataevf29276e2014-06-18 04:14:57 +000012659 // OpenMP [2.14.3.5, Restrictions, p.2]
12660 // A list item that is private within a parallel region, or that appears in
12661 // the reduction clause of a parallel construct, must not appear in a
12662 // lastprivate clause on a worksharing construct if any of the corresponding
12663 // worksharing regions ever binds to any of the corresponding parallel
12664 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012665 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012666 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012667 !isOpenMPParallelDirective(CurrDir) &&
12668 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012669 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012670 if (DVar.CKind != OMPC_shared) {
12671 Diag(ELoc, diag::err_omp_required_access)
12672 << getOpenMPClauseName(OMPC_lastprivate)
12673 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012674 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012675 continue;
12676 }
12677 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012678
Alexander Musman1bb328c2014-06-04 13:06:39 +000012679 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012680 // A variable of class type (or array thereof) that appears in a
12681 // lastprivate clause requires an accessible, unambiguous default
12682 // constructor for the class type, unless the list item is also specified
12683 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012684 // A variable of class type (or array thereof) that appears in a
12685 // lastprivate clause requires an accessible, unambiguous copy assignment
12686 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012687 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012688 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12689 Type.getUnqualifiedType(), ".lastprivate.src",
12690 D->hasAttrs() ? &D->getAttrs() : nullptr);
12691 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012692 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012693 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012694 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012695 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012696 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012697 // For arrays generate assignment operation for single element and replace
12698 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012699 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12700 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012701 if (AssignmentOp.isInvalid())
12702 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012703 AssignmentOp =
12704 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012705 if (AssignmentOp.isInvalid())
12706 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012707
Alexey Bataev74caaf22016-02-20 04:09:36 +000012708 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012709 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012710 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012711 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012712 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012713 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012714 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012715 ExprCaptures.push_back(Ref->getDecl());
12716 }
12717 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012718 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012719 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012720 ExprResult RefRes = DefaultLvalueConversion(Ref);
12721 if (!RefRes.isUsable())
12722 continue;
12723 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012724 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12725 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012726 if (!PostUpdateRes.isUsable())
12727 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012728 ExprPostUpdates.push_back(
12729 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012730 }
12731 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012732 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012733 Vars.push_back((VD || CurContext->isDependentContext())
12734 ? RefExpr->IgnoreParens()
12735 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012736 SrcExprs.push_back(PseudoSrcExpr);
12737 DstExprs.push_back(PseudoDstExpr);
12738 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012739 }
12740
12741 if (Vars.empty())
12742 return nullptr;
12743
12744 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012745 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012746 buildPreInits(Context, ExprCaptures),
12747 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012748}
12749
Alexey Bataev758e55e2013-09-06 18:03:48 +000012750OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12751 SourceLocation StartLoc,
12752 SourceLocation LParenLoc,
12753 SourceLocation EndLoc) {
12754 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012755 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012756 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012757 SourceLocation ELoc;
12758 SourceRange ERange;
12759 Expr *SimpleRefExpr = RefExpr;
12760 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012761 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012762 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012763 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012764 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012765 ValueDecl *D = Res.first;
12766 if (!D)
12767 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012768
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012769 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012770 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12771 // in a Construct]
12772 // Variables with the predetermined data-sharing attributes may not be
12773 // listed in data-sharing attributes clauses, except for the cases
12774 // listed below. For these exceptions only, listing a predetermined
12775 // variable in a data-sharing attribute clause is allowed and overrides
12776 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012777 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012778 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12779 DVar.RefExpr) {
12780 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12781 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012782 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012783 continue;
12784 }
12785
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012786 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012787 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012788 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012789 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012790 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12791 ? RefExpr->IgnoreParens()
12792 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012793 }
12794
Alexey Bataeved09d242014-05-28 05:53:51 +000012795 if (Vars.empty())
12796 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012797
12798 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
12799}
12800
Alexey Bataevc5e02582014-06-16 07:08:35 +000012801namespace {
12802class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
12803 DSAStackTy *Stack;
12804
12805public:
12806 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012807 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
12808 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012809 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
12810 return false;
12811 if (DVar.CKind != OMPC_unknown)
12812 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012813 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012814 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012815 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012816 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012817 }
12818 return false;
12819 }
12820 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012821 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012822 if (Child && Visit(Child))
12823 return true;
12824 }
12825 return false;
12826 }
Alexey Bataev23b69422014-06-18 07:08:49 +000012827 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012828};
Alexey Bataev23b69422014-06-18 07:08:49 +000012829} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000012830
Alexey Bataev60da77e2016-02-29 05:54:20 +000012831namespace {
12832// Transform MemberExpression for specified FieldDecl of current class to
12833// DeclRefExpr to specified OMPCapturedExprDecl.
12834class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
12835 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000012836 ValueDecl *Field = nullptr;
12837 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012838
12839public:
12840 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
12841 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
12842
12843 ExprResult TransformMemberExpr(MemberExpr *E) {
12844 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
12845 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000012846 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012847 return CapturedExpr;
12848 }
12849 return BaseTransform::TransformMemberExpr(E);
12850 }
12851 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
12852};
12853} // namespace
12854
Alexey Bataev97d18bf2018-04-11 19:21:00 +000012855template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000012856static T filterLookupForUDReductionAndMapper(
12857 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012858 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012859 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012860 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012861 return Res;
12862 }
12863 }
12864 return T();
12865}
12866
Alexey Bataev43b90b72018-09-12 16:31:59 +000012867static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
12868 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
12869
12870 for (auto RD : D->redecls()) {
12871 // Don't bother with extra checks if we already know this one isn't visible.
12872 if (RD == D)
12873 continue;
12874
12875 auto ND = cast<NamedDecl>(RD);
12876 if (LookupResult::isVisible(SemaRef, ND))
12877 return ND;
12878 }
12879
12880 return nullptr;
12881}
12882
12883static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000012884argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000012885 SourceLocation Loc, QualType Ty,
12886 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
12887 // Find all of the associated namespaces and classes based on the
12888 // arguments we have.
12889 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12890 Sema::AssociatedClassSet AssociatedClasses;
12891 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
12892 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
12893 AssociatedClasses);
12894
12895 // C++ [basic.lookup.argdep]p3:
12896 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12897 // and let Y be the lookup set produced by argument dependent
12898 // lookup (defined as follows). If X contains [...] then Y is
12899 // empty. Otherwise Y is the set of declarations found in the
12900 // namespaces associated with the argument types as described
12901 // below. The set of declarations found by the lookup of the name
12902 // is the union of X and Y.
12903 //
12904 // Here, we compute Y and add its members to the overloaded
12905 // candidate set.
12906 for (auto *NS : AssociatedNamespaces) {
12907 // When considering an associated namespace, the lookup is the
12908 // same as the lookup performed when the associated namespace is
12909 // used as a qualifier (3.4.3.2) except that:
12910 //
12911 // -- Any using-directives in the associated namespace are
12912 // ignored.
12913 //
12914 // -- Any namespace-scope friend functions declared in
12915 // associated classes are visible within their respective
12916 // namespaces even if they are not visible during an ordinary
12917 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000012918 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000012919 for (auto *D : R) {
12920 auto *Underlying = D;
12921 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12922 Underlying = USD->getTargetDecl();
12923
Michael Kruse4304e9d2019-02-19 16:38:20 +000012924 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
12925 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000012926 continue;
12927
12928 if (!SemaRef.isVisible(D)) {
12929 D = findAcceptableDecl(SemaRef, D);
12930 if (!D)
12931 continue;
12932 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12933 Underlying = USD->getTargetDecl();
12934 }
12935 Lookups.emplace_back();
12936 Lookups.back().addDecl(Underlying);
12937 }
12938 }
12939}
12940
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012941static ExprResult
12942buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
12943 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
12944 const DeclarationNameInfo &ReductionId, QualType Ty,
12945 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
12946 if (ReductionIdScopeSpec.isInvalid())
12947 return ExprError();
12948 SmallVector<UnresolvedSet<8>, 4> Lookups;
12949 if (S) {
12950 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12951 Lookup.suppressDiagnostics();
12952 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012953 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012954 do {
12955 S = S->getParent();
12956 } while (S && !S->isDeclScope(D));
12957 if (S)
12958 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000012959 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012960 Lookups.back().append(Lookup.begin(), Lookup.end());
12961 Lookup.clear();
12962 }
12963 } else if (auto *ULE =
12964 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
12965 Lookups.push_back(UnresolvedSet<8>());
12966 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012967 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012968 if (D == PrevD)
12969 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000012970 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012971 Lookups.back().addDecl(DRD);
12972 PrevD = D;
12973 }
12974 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000012975 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
12976 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012977 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000012978 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012979 return !D->isInvalidDecl() &&
12980 (D->getType()->isDependentType() ||
12981 D->getType()->isInstantiationDependentType() ||
12982 D->getType()->containsUnexpandedParameterPack());
12983 })) {
12984 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000012985 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000012986 if (Set.empty())
12987 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012988 ResSet.append(Set.begin(), Set.end());
12989 // The last item marks the end of all declarations at the specified scope.
12990 ResSet.addDecl(Set[Set.size() - 1]);
12991 }
12992 return UnresolvedLookupExpr::Create(
12993 SemaRef.Context, /*NamingClass=*/nullptr,
12994 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
12995 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
12996 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000012997 // Lookup inside the classes.
12998 // C++ [over.match.oper]p3:
12999 // For a unary operator @ with an operand of a type whose
13000 // cv-unqualified version is T1, and for a binary operator @ with
13001 // a left operand of a type whose cv-unqualified version is T1 and
13002 // a right operand of a type whose cv-unqualified version is T2,
13003 // three sets of candidate functions, designated member
13004 // candidates, non-member candidates and built-in candidates, are
13005 // constructed as follows:
13006 // -- If T1 is a complete class type or a class currently being
13007 // defined, the set of member candidates is the result of the
13008 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13009 // the set of member candidates is empty.
13010 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13011 Lookup.suppressDiagnostics();
13012 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13013 // Complete the type if it can be completed.
13014 // If the type is neither complete nor being defined, bail out now.
13015 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13016 TyRec->getDecl()->getDefinition()) {
13017 Lookup.clear();
13018 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13019 if (Lookup.empty()) {
13020 Lookups.emplace_back();
13021 Lookups.back().append(Lookup.begin(), Lookup.end());
13022 }
13023 }
13024 }
13025 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013026 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013027 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013028 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13029 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13030 if (!D->isInvalidDecl() &&
13031 SemaRef.Context.hasSameType(D->getType(), Ty))
13032 return D;
13033 return nullptr;
13034 }))
13035 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13036 VK_LValue, Loc);
13037 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013038 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13039 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13040 if (!D->isInvalidDecl() &&
13041 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13042 !Ty.isMoreQualifiedThan(D->getType()))
13043 return D;
13044 return nullptr;
13045 })) {
13046 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13047 /*DetectVirtual=*/false);
13048 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13049 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13050 VD->getType().getUnqualifiedType()))) {
13051 if (SemaRef.CheckBaseClassAccess(
13052 Loc, VD->getType(), Ty, Paths.front(),
13053 /*DiagID=*/0) != Sema::AR_inaccessible) {
13054 SemaRef.BuildBasePathArray(Paths, BasePath);
13055 return SemaRef.BuildDeclRefExpr(
13056 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13057 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013058 }
13059 }
13060 }
13061 }
13062 if (ReductionIdScopeSpec.isSet()) {
13063 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
13064 return ExprError();
13065 }
13066 return ExprEmpty();
13067}
13068
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013069namespace {
13070/// Data for the reduction-based clauses.
13071struct ReductionData {
13072 /// List of original reduction items.
13073 SmallVector<Expr *, 8> Vars;
13074 /// List of private copies of the reduction items.
13075 SmallVector<Expr *, 8> Privates;
13076 /// LHS expressions for the reduction_op expressions.
13077 SmallVector<Expr *, 8> LHSs;
13078 /// RHS expressions for the reduction_op expressions.
13079 SmallVector<Expr *, 8> RHSs;
13080 /// Reduction operation expression.
13081 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013082 /// Taskgroup descriptors for the corresponding reduction items in
13083 /// in_reduction clauses.
13084 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013085 /// List of captures for clause.
13086 SmallVector<Decl *, 4> ExprCaptures;
13087 /// List of postupdate expressions.
13088 SmallVector<Expr *, 4> ExprPostUpdates;
13089 ReductionData() = delete;
13090 /// Reserves required memory for the reduction data.
13091 ReductionData(unsigned Size) {
13092 Vars.reserve(Size);
13093 Privates.reserve(Size);
13094 LHSs.reserve(Size);
13095 RHSs.reserve(Size);
13096 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013097 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013098 ExprCaptures.reserve(Size);
13099 ExprPostUpdates.reserve(Size);
13100 }
13101 /// Stores reduction item and reduction operation only (required for dependent
13102 /// reduction item).
13103 void push(Expr *Item, Expr *ReductionOp) {
13104 Vars.emplace_back(Item);
13105 Privates.emplace_back(nullptr);
13106 LHSs.emplace_back(nullptr);
13107 RHSs.emplace_back(nullptr);
13108 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013109 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013110 }
13111 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013112 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13113 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013114 Vars.emplace_back(Item);
13115 Privates.emplace_back(Private);
13116 LHSs.emplace_back(LHS);
13117 RHSs.emplace_back(RHS);
13118 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013119 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013120 }
13121};
13122} // namespace
13123
Alexey Bataeve3727102018-04-18 15:57:46 +000013124static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013125 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13126 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13127 const Expr *Length = OASE->getLength();
13128 if (Length == nullptr) {
13129 // For array sections of the form [1:] or [:], we would need to analyze
13130 // the lower bound...
13131 if (OASE->getColonLoc().isValid())
13132 return false;
13133
13134 // This is an array subscript which has implicit length 1!
13135 SingleElement = true;
13136 ArraySizes.push_back(llvm::APSInt::get(1));
13137 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013138 Expr::EvalResult Result;
13139 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013140 return false;
13141
Fangrui Song407659a2018-11-30 23:41:18 +000013142 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013143 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13144 ArraySizes.push_back(ConstantLengthValue);
13145 }
13146
13147 // Get the base of this array section and walk up from there.
13148 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13149
13150 // We require length = 1 for all array sections except the right-most to
13151 // guarantee that the memory region is contiguous and has no holes in it.
13152 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13153 Length = TempOASE->getLength();
13154 if (Length == nullptr) {
13155 // For array sections of the form [1:] or [:], we would need to analyze
13156 // the lower bound...
13157 if (OASE->getColonLoc().isValid())
13158 return false;
13159
13160 // This is an array subscript which has implicit length 1!
13161 ArraySizes.push_back(llvm::APSInt::get(1));
13162 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013163 Expr::EvalResult Result;
13164 if (!Length->EvaluateAsInt(Result, Context))
13165 return false;
13166
13167 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13168 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013169 return false;
13170
13171 ArraySizes.push_back(ConstantLengthValue);
13172 }
13173 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13174 }
13175
13176 // If we have a single element, we don't need to add the implicit lengths.
13177 if (!SingleElement) {
13178 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13179 // Has implicit length 1!
13180 ArraySizes.push_back(llvm::APSInt::get(1));
13181 Base = TempASE->getBase()->IgnoreParenImpCasts();
13182 }
13183 }
13184
13185 // This array section can be privatized as a single value or as a constant
13186 // sized array.
13187 return true;
13188}
13189
Alexey Bataeve3727102018-04-18 15:57:46 +000013190static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013191 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13192 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13193 SourceLocation ColonLoc, SourceLocation EndLoc,
13194 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013195 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013196 DeclarationName DN = ReductionId.getName();
13197 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013198 BinaryOperatorKind BOK = BO_Comma;
13199
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013200 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013201 // OpenMP [2.14.3.6, reduction clause]
13202 // C
13203 // reduction-identifier is either an identifier or one of the following
13204 // operators: +, -, *, &, |, ^, && and ||
13205 // C++
13206 // reduction-identifier is either an id-expression or one of the following
13207 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013208 switch (OOK) {
13209 case OO_Plus:
13210 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013211 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013212 break;
13213 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013214 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013215 break;
13216 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013217 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013218 break;
13219 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013220 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013221 break;
13222 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013223 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013224 break;
13225 case OO_AmpAmp:
13226 BOK = BO_LAnd;
13227 break;
13228 case OO_PipePipe:
13229 BOK = BO_LOr;
13230 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013231 case OO_New:
13232 case OO_Delete:
13233 case OO_Array_New:
13234 case OO_Array_Delete:
13235 case OO_Slash:
13236 case OO_Percent:
13237 case OO_Tilde:
13238 case OO_Exclaim:
13239 case OO_Equal:
13240 case OO_Less:
13241 case OO_Greater:
13242 case OO_LessEqual:
13243 case OO_GreaterEqual:
13244 case OO_PlusEqual:
13245 case OO_MinusEqual:
13246 case OO_StarEqual:
13247 case OO_SlashEqual:
13248 case OO_PercentEqual:
13249 case OO_CaretEqual:
13250 case OO_AmpEqual:
13251 case OO_PipeEqual:
13252 case OO_LessLess:
13253 case OO_GreaterGreater:
13254 case OO_LessLessEqual:
13255 case OO_GreaterGreaterEqual:
13256 case OO_EqualEqual:
13257 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013258 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013259 case OO_PlusPlus:
13260 case OO_MinusMinus:
13261 case OO_Comma:
13262 case OO_ArrowStar:
13263 case OO_Arrow:
13264 case OO_Call:
13265 case OO_Subscript:
13266 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013267 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013268 case NUM_OVERLOADED_OPERATORS:
13269 llvm_unreachable("Unexpected reduction identifier");
13270 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013271 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013272 if (II->isStr("max"))
13273 BOK = BO_GT;
13274 else if (II->isStr("min"))
13275 BOK = BO_LT;
13276 }
13277 break;
13278 }
13279 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013280 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013281 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013282 else
13283 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013284 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013285
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013286 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13287 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013288 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013289 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013290 // OpenMP [2.1, C/C++]
13291 // A list item is a variable or array section, subject to the restrictions
13292 // specified in Section 2.4 on page 42 and in each of the sections
13293 // describing clauses and directives for which a list appears.
13294 // OpenMP [2.14.3.3, Restrictions, p.1]
13295 // A variable that is part of another variable (as an array or
13296 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013297 if (!FirstIter && IR != ER)
13298 ++IR;
13299 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013300 SourceLocation ELoc;
13301 SourceRange ERange;
13302 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013303 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013304 /*AllowArraySection=*/true);
13305 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013306 // Try to find 'declare reduction' corresponding construct before using
13307 // builtin/overloaded operators.
13308 QualType Type = Context.DependentTy;
13309 CXXCastPath BasePath;
13310 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013311 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013312 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013313 Expr *ReductionOp = nullptr;
13314 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013315 (DeclareReductionRef.isUnset() ||
13316 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013317 ReductionOp = DeclareReductionRef.get();
13318 // It will be analyzed later.
13319 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013320 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013321 ValueDecl *D = Res.first;
13322 if (!D)
13323 continue;
13324
Alexey Bataev88202be2017-07-27 13:20:36 +000013325 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013326 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013327 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13328 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013329 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013330 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013331 } else if (OASE) {
13332 QualType BaseType =
13333 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13334 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013335 Type = ATy->getElementType();
13336 else
13337 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013338 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013339 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013340 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013341 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013342 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013343
Alexey Bataevc5e02582014-06-16 07:08:35 +000013344 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13345 // A variable that appears in a private clause must not have an incomplete
13346 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013347 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013348 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013349 continue;
13350 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013351 // A list item that appears in a reduction clause must not be
13352 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013353 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13354 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013355 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013356
13357 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013358 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13359 // If a list-item is a reference type then it must bind to the same object
13360 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013361 if (!ASE && !OASE) {
13362 if (VD) {
13363 VarDecl *VDDef = VD->getDefinition();
13364 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13365 DSARefChecker Check(Stack);
13366 if (Check.Visit(VDDef->getInit())) {
13367 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13368 << getOpenMPClauseName(ClauseKind) << ERange;
13369 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13370 continue;
13371 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013372 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013373 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013374
Alexey Bataevbc529672018-09-28 19:33:14 +000013375 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13376 // in a Construct]
13377 // Variables with the predetermined data-sharing attributes may not be
13378 // listed in data-sharing attributes clauses, except for the cases
13379 // listed below. For these exceptions only, listing a predetermined
13380 // variable in a data-sharing attribute clause is allowed and overrides
13381 // the variable's predetermined data-sharing attributes.
13382 // OpenMP [2.14.3.6, Restrictions, p.3]
13383 // Any number of reduction clauses can be specified on the directive,
13384 // but a list item can appear only once in the reduction clauses for that
13385 // directive.
13386 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13387 if (DVar.CKind == OMPC_reduction) {
13388 S.Diag(ELoc, diag::err_omp_once_referenced)
13389 << getOpenMPClauseName(ClauseKind);
13390 if (DVar.RefExpr)
13391 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13392 continue;
13393 }
13394 if (DVar.CKind != OMPC_unknown) {
13395 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13396 << getOpenMPClauseName(DVar.CKind)
13397 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013398 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013399 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013400 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013401
13402 // OpenMP [2.14.3.6, Restrictions, p.1]
13403 // A list item that appears in a reduction clause of a worksharing
13404 // construct must be shared in the parallel regions to which any of the
13405 // worksharing regions arising from the worksharing construct bind.
13406 if (isOpenMPWorksharingDirective(CurrDir) &&
13407 !isOpenMPParallelDirective(CurrDir) &&
13408 !isOpenMPTeamsDirective(CurrDir)) {
13409 DVar = Stack->getImplicitDSA(D, true);
13410 if (DVar.CKind != OMPC_shared) {
13411 S.Diag(ELoc, diag::err_omp_required_access)
13412 << getOpenMPClauseName(OMPC_reduction)
13413 << getOpenMPClauseName(OMPC_shared);
13414 reportOriginalDsa(S, Stack, D, DVar);
13415 continue;
13416 }
13417 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013418 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013419
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013420 // Try to find 'declare reduction' corresponding construct before using
13421 // builtin/overloaded operators.
13422 CXXCastPath BasePath;
13423 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013424 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013425 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13426 if (DeclareReductionRef.isInvalid())
13427 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013428 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013429 (DeclareReductionRef.isUnset() ||
13430 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013431 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013432 continue;
13433 }
13434 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13435 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013436 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013437 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013438 << Type << ReductionIdRange;
13439 continue;
13440 }
13441
13442 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13443 // The type of a list item that appears in a reduction clause must be valid
13444 // for the reduction-identifier. For a max or min reduction in C, the type
13445 // of the list item must be an allowed arithmetic data type: char, int,
13446 // float, double, or _Bool, possibly modified with long, short, signed, or
13447 // unsigned. For a max or min reduction in C++, the type of the list item
13448 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13449 // double, or bool, possibly modified with long, short, signed, or unsigned.
13450 if (DeclareReductionRef.isUnset()) {
13451 if ((BOK == BO_GT || BOK == BO_LT) &&
13452 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013453 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13454 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013455 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013456 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013457 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13458 VarDecl::DeclarationOnly;
13459 S.Diag(D->getLocation(),
13460 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013461 << D;
13462 }
13463 continue;
13464 }
13465 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013466 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013467 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13468 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013469 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013470 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13471 VarDecl::DeclarationOnly;
13472 S.Diag(D->getLocation(),
13473 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013474 << D;
13475 }
13476 continue;
13477 }
13478 }
13479
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013480 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013481 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13482 D->hasAttrs() ? &D->getAttrs() : nullptr);
13483 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13484 D->hasAttrs() ? &D->getAttrs() : nullptr);
13485 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013486
13487 // Try if we can determine constant lengths for all array sections and avoid
13488 // the VLA.
13489 bool ConstantLengthOASE = false;
13490 if (OASE) {
13491 bool SingleElement;
13492 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013493 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013494 Context, OASE, SingleElement, ArraySizes);
13495
13496 // If we don't have a single element, we must emit a constant array type.
13497 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013498 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013499 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13500 ArrayType::Normal,
13501 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013502 }
13503 }
13504
13505 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013506 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013507 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013508 if (!Context.getTargetInfo().isVLASupported()) {
13509 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13510 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13511 S.Diag(ELoc, diag::note_vla_unsupported);
13512 } else {
13513 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13514 S.targetDiag(ELoc, diag::note_vla_unsupported);
13515 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013516 continue;
13517 }
David Majnemer9d168222016-08-05 17:44:54 +000013518 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013519 // Create pseudo array type for private copy. The size for this array will
13520 // be generated during codegen.
13521 // For array subscripts or single variables Private Ty is the same as Type
13522 // (type of the variable or single array element).
13523 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013524 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013525 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013526 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013527 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013528 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013529 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013530 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013531 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013532 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013533 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13534 D->hasAttrs() ? &D->getAttrs() : nullptr,
13535 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013536 // Add initializer for private variable.
13537 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013538 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13539 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013540 if (DeclareReductionRef.isUsable()) {
13541 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13542 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13543 if (DRD->getInitializer()) {
13544 Init = DRDRef;
13545 RHSVD->setInit(DRDRef);
13546 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013547 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013548 } else {
13549 switch (BOK) {
13550 case BO_Add:
13551 case BO_Xor:
13552 case BO_Or:
13553 case BO_LOr:
13554 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13555 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013556 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013557 break;
13558 case BO_Mul:
13559 case BO_LAnd:
13560 if (Type->isScalarType() || Type->isAnyComplexType()) {
13561 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013562 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013563 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013564 break;
13565 case BO_And: {
13566 // '&' reduction op - initializer is '~0'.
13567 QualType OrigType = Type;
13568 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13569 Type = ComplexTy->getElementType();
13570 if (Type->isRealFloatingType()) {
13571 llvm::APFloat InitValue =
13572 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13573 /*isIEEE=*/true);
13574 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13575 Type, ELoc);
13576 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013577 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013578 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13579 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13580 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13581 }
13582 if (Init && OrigType->isAnyComplexType()) {
13583 // Init = 0xFFFF + 0xFFFFi;
13584 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013585 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013586 }
13587 Type = OrigType;
13588 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013589 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013590 case BO_LT:
13591 case BO_GT: {
13592 // 'min' reduction op - initializer is 'Largest representable number in
13593 // the reduction list item type'.
13594 // 'max' reduction op - initializer is 'Least representable number in
13595 // the reduction list item type'.
13596 if (Type->isIntegerType() || Type->isPointerType()) {
13597 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013598 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013599 QualType IntTy =
13600 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13601 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013602 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13603 : llvm::APInt::getMinValue(Size)
13604 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13605 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013606 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13607 if (Type->isPointerType()) {
13608 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013609 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013610 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013611 if (CastExpr.isInvalid())
13612 continue;
13613 Init = CastExpr.get();
13614 }
13615 } else if (Type->isRealFloatingType()) {
13616 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13617 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13618 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13619 Type, ELoc);
13620 }
13621 break;
13622 }
13623 case BO_PtrMemD:
13624 case BO_PtrMemI:
13625 case BO_MulAssign:
13626 case BO_Div:
13627 case BO_Rem:
13628 case BO_Sub:
13629 case BO_Shl:
13630 case BO_Shr:
13631 case BO_LE:
13632 case BO_GE:
13633 case BO_EQ:
13634 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013635 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013636 case BO_AndAssign:
13637 case BO_XorAssign:
13638 case BO_OrAssign:
13639 case BO_Assign:
13640 case BO_AddAssign:
13641 case BO_SubAssign:
13642 case BO_DivAssign:
13643 case BO_RemAssign:
13644 case BO_ShlAssign:
13645 case BO_ShrAssign:
13646 case BO_Comma:
13647 llvm_unreachable("Unexpected reduction operation");
13648 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013649 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013650 if (Init && DeclareReductionRef.isUnset())
13651 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13652 else if (!Init)
13653 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013654 if (RHSVD->isInvalidDecl())
13655 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013656 if (!RHSVD->hasInit() &&
13657 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013658 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13659 << Type << ReductionIdRange;
13660 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13661 VarDecl::DeclarationOnly;
13662 S.Diag(D->getLocation(),
13663 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013664 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013665 continue;
13666 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013667 // Store initializer for single element in private copy. Will be used during
13668 // codegen.
13669 PrivateVD->setInit(RHSVD->getInit());
13670 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013671 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013672 ExprResult ReductionOp;
13673 if (DeclareReductionRef.isUsable()) {
13674 QualType RedTy = DeclareReductionRef.get()->getType();
13675 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013676 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13677 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013678 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013679 LHS = S.DefaultLvalueConversion(LHS.get());
13680 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013681 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13682 CK_UncheckedDerivedToBase, LHS.get(),
13683 &BasePath, LHS.get()->getValueKind());
13684 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13685 CK_UncheckedDerivedToBase, RHS.get(),
13686 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013687 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013688 FunctionProtoType::ExtProtoInfo EPI;
13689 QualType Params[] = {PtrRedTy, PtrRedTy};
13690 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13691 auto *OVE = new (Context) OpaqueValueExpr(
13692 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013693 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013694 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013695 ReductionOp =
13696 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013697 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013698 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013699 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013700 if (ReductionOp.isUsable()) {
13701 if (BOK != BO_LT && BOK != BO_GT) {
13702 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013703 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013704 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013705 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013706 auto *ConditionalOp = new (Context)
13707 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13708 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013709 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013710 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013711 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013712 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013713 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013714 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13715 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013716 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013717 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013718 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013719 }
13720
Alexey Bataevfa312f32017-07-21 18:48:21 +000013721 // OpenMP [2.15.4.6, Restrictions, p.2]
13722 // A list item that appears in an in_reduction clause of a task construct
13723 // must appear in a task_reduction clause of a construct associated with a
13724 // taskgroup region that includes the participating task in its taskgroup
13725 // set. The construct associated with the innermost region that meets this
13726 // condition must specify the same reduction-identifier as the in_reduction
13727 // clause.
13728 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013729 SourceRange ParentSR;
13730 BinaryOperatorKind ParentBOK;
13731 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013732 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013733 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013734 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13735 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013736 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013737 Stack->getTopMostTaskgroupReductionData(
13738 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013739 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13740 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13741 if (!IsParentBOK && !IsParentReductionOp) {
13742 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13743 continue;
13744 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013745 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13746 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13747 IsParentReductionOp) {
13748 bool EmitError = true;
13749 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13750 llvm::FoldingSetNodeID RedId, ParentRedId;
13751 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13752 DeclareReductionRef.get()->Profile(RedId, Context,
13753 /*Canonical=*/true);
13754 EmitError = RedId != ParentRedId;
13755 }
13756 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013757 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013758 diag::err_omp_reduction_identifier_mismatch)
13759 << ReductionIdRange << RefExpr->getSourceRange();
13760 S.Diag(ParentSR.getBegin(),
13761 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013762 << ParentSR
13763 << (IsParentBOK ? ParentBOKDSA.RefExpr
13764 : ParentReductionOpDSA.RefExpr)
13765 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013766 continue;
13767 }
13768 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013769 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13770 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013771 }
13772
Alexey Bataev60da77e2016-02-29 05:54:20 +000013773 DeclRefExpr *Ref = nullptr;
13774 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013775 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013776 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013777 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013778 VarsExpr =
13779 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13780 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013781 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013782 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013783 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013784 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013785 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013786 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013787 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013788 if (!RefRes.isUsable())
13789 continue;
13790 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013791 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13792 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013793 if (!PostUpdateRes.isUsable())
13794 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013795 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
13796 Stack->getCurrentDirective() == OMPD_taskgroup) {
13797 S.Diag(RefExpr->getExprLoc(),
13798 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000013799 << RefExpr->getSourceRange();
13800 continue;
13801 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013802 RD.ExprPostUpdates.emplace_back(
13803 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000013804 }
13805 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013806 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000013807 // All reduction items are still marked as reduction (to do not increase
13808 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013809 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013810 if (CurrDir == OMPD_taskgroup) {
13811 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013812 Stack->addTaskgroupReductionData(D, ReductionIdRange,
13813 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000013814 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013815 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013816 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013817 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
13818 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013819 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013820 return RD.Vars.empty();
13821}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013822
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013823OMPClause *Sema::ActOnOpenMPReductionClause(
13824 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13825 SourceLocation ColonLoc, SourceLocation EndLoc,
13826 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13827 ArrayRef<Expr *> UnresolvedReductions) {
13828 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013829 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013830 StartLoc, LParenLoc, ColonLoc, EndLoc,
13831 ReductionIdScopeSpec, ReductionId,
13832 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013833 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000013834
Alexey Bataevc5e02582014-06-16 07:08:35 +000013835 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013836 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13837 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13838 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13839 buildPreInits(Context, RD.ExprCaptures),
13840 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000013841}
13842
Alexey Bataev169d96a2017-07-18 20:17:46 +000013843OMPClause *Sema::ActOnOpenMPTaskReductionClause(
13844 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13845 SourceLocation ColonLoc, SourceLocation EndLoc,
13846 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13847 ArrayRef<Expr *> UnresolvedReductions) {
13848 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013849 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
13850 StartLoc, LParenLoc, ColonLoc, EndLoc,
13851 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013852 UnresolvedReductions, RD))
13853 return nullptr;
13854
13855 return OMPTaskReductionClause::Create(
13856 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13857 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13858 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13859 buildPreInits(Context, RD.ExprCaptures),
13860 buildPostUpdate(*this, RD.ExprPostUpdates));
13861}
13862
Alexey Bataevfa312f32017-07-21 18:48:21 +000013863OMPClause *Sema::ActOnOpenMPInReductionClause(
13864 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13865 SourceLocation ColonLoc, SourceLocation EndLoc,
13866 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13867 ArrayRef<Expr *> UnresolvedReductions) {
13868 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013869 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013870 StartLoc, LParenLoc, ColonLoc, EndLoc,
13871 ReductionIdScopeSpec, ReductionId,
13872 UnresolvedReductions, RD))
13873 return nullptr;
13874
13875 return OMPInReductionClause::Create(
13876 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13877 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000013878 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013879 buildPreInits(Context, RD.ExprCaptures),
13880 buildPostUpdate(*this, RD.ExprPostUpdates));
13881}
13882
Alexey Bataevecba70f2016-04-12 11:02:11 +000013883bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
13884 SourceLocation LinLoc) {
13885 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
13886 LinKind == OMPC_LINEAR_unknown) {
13887 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
13888 return true;
13889 }
13890 return false;
13891}
13892
Alexey Bataeve3727102018-04-18 15:57:46 +000013893bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000013894 OpenMPLinearClauseKind LinKind,
13895 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013896 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000013897 // A variable must not have an incomplete type or a reference type.
13898 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
13899 return true;
13900 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
13901 !Type->isReferenceType()) {
13902 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
13903 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
13904 return true;
13905 }
13906 Type = Type.getNonReferenceType();
13907
Joel E. Dennybae586f2019-01-04 22:12:13 +000013908 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13909 // A variable that is privatized must not have a const-qualified type
13910 // unless it is of class type with a mutable member. This restriction does
13911 // not apply to the firstprivate clause.
13912 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000013913 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013914
13915 // A list item must be of integral or pointer type.
13916 Type = Type.getUnqualifiedType().getCanonicalType();
13917 const auto *Ty = Type.getTypePtrOrNull();
13918 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
13919 !Ty->isPointerType())) {
13920 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
13921 if (D) {
13922 bool IsDecl =
13923 !VD ||
13924 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13925 Diag(D->getLocation(),
13926 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13927 << D;
13928 }
13929 return true;
13930 }
13931 return false;
13932}
13933
Alexey Bataev182227b2015-08-20 10:54:39 +000013934OMPClause *Sema::ActOnOpenMPLinearClause(
13935 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
13936 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
13937 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013938 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013939 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000013940 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013941 SmallVector<Decl *, 4> ExprCaptures;
13942 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013943 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000013944 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000013945 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000013946 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013947 SourceLocation ELoc;
13948 SourceRange ERange;
13949 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013950 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013951 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013952 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013953 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013954 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013955 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000013956 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013957 ValueDecl *D = Res.first;
13958 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000013959 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000013960
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013961 QualType Type = D->getType();
13962 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000013963
13964 // OpenMP [2.14.3.7, linear clause]
13965 // A list-item cannot appear in more than one linear clause.
13966 // A list-item that appears in a linear clause cannot appear in any
13967 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013968 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000013969 if (DVar.RefExpr) {
13970 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13971 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000013972 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000013973 continue;
13974 }
13975
Alexey Bataevecba70f2016-04-12 11:02:11 +000013976 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000013977 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013978 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000013979
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013980 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000013981 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013982 buildVarDecl(*this, ELoc, Type, D->getName(),
13983 D->hasAttrs() ? &D->getAttrs() : nullptr,
13984 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013985 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013986 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013987 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013988 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013989 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013990 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013991 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013992 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013993 ExprCaptures.push_back(Ref->getDecl());
13994 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
13995 ExprResult RefRes = DefaultLvalueConversion(Ref);
13996 if (!RefRes.isUsable())
13997 continue;
13998 ExprResult PostUpdateRes =
13999 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14000 SimpleRefExpr, RefRes.get());
14001 if (!PostUpdateRes.isUsable())
14002 continue;
14003 ExprPostUpdates.push_back(
14004 IgnoredValueConversions(PostUpdateRes.get()).get());
14005 }
14006 }
14007 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014008 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014009 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014010 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014011 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014012 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014013 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014014 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014015
14016 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014017 Vars.push_back((VD || CurContext->isDependentContext())
14018 ? RefExpr->IgnoreParens()
14019 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014020 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014021 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014022 }
14023
14024 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014025 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014026
14027 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014028 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014029 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14030 !Step->isInstantiationDependent() &&
14031 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014032 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014033 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014034 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014035 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014036 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014037
Alexander Musman3276a272015-03-21 10:12:56 +000014038 // Build var to save the step value.
14039 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014040 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014041 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014042 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014043 ExprResult CalcStep =
14044 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014045 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014046
Alexander Musman8dba6642014-04-22 13:09:42 +000014047 // Warn about zero linear step (it would be probably better specified as
14048 // making corresponding variables 'const').
14049 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014050 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14051 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014052 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14053 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014054 if (!IsConstant && CalcStep.isUsable()) {
14055 // Calculate the step beforehand instead of doing this on each iteration.
14056 // (This is not used if the number of iterations may be kfold-ed).
14057 CalcStepExpr = CalcStep.get();
14058 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014059 }
14060
Alexey Bataev182227b2015-08-20 10:54:39 +000014061 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14062 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014063 StepExpr, CalcStepExpr,
14064 buildPreInits(Context, ExprCaptures),
14065 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014066}
14067
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014068static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14069 Expr *NumIterations, Sema &SemaRef,
14070 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014071 // Walk the vars and build update/final expressions for the CodeGen.
14072 SmallVector<Expr *, 8> Updates;
14073 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014074 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014075 Expr *Step = Clause.getStep();
14076 Expr *CalcStep = Clause.getCalcStep();
14077 // OpenMP [2.14.3.7, linear clause]
14078 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014079 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014080 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014081 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014082 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14083 bool HasErrors = false;
14084 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014085 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014086 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14087 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014088 SourceLocation ELoc;
14089 SourceRange ERange;
14090 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014091 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014092 ValueDecl *D = Res.first;
14093 if (Res.second || !D) {
14094 Updates.push_back(nullptr);
14095 Finals.push_back(nullptr);
14096 HasErrors = true;
14097 continue;
14098 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014099 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014100 // OpenMP [2.15.11, distribute simd Construct]
14101 // A list item may not appear in a linear clause, unless it is the loop
14102 // iteration variable.
14103 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14104 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14105 SemaRef.Diag(ELoc,
14106 diag::err_omp_linear_distribute_var_non_loop_iteration);
14107 Updates.push_back(nullptr);
14108 Finals.push_back(nullptr);
14109 HasErrors = true;
14110 continue;
14111 }
Alexander Musman3276a272015-03-21 10:12:56 +000014112 Expr *InitExpr = *CurInit;
14113
14114 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014115 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014116 Expr *CapturedRef;
14117 if (LinKind == OMPC_LINEAR_uval)
14118 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14119 else
14120 CapturedRef =
14121 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14122 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14123 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014124
14125 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014126 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014127 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014128 Update = buildCounterUpdate(
14129 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14130 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014131 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014132 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014133 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014134 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014135
14136 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014137 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014138 if (!Info.first)
14139 Final =
14140 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014141 InitExpr, NumIterations, Step, /*Subtract=*/false,
14142 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014143 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014144 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014145 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014146 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014147
Alexander Musman3276a272015-03-21 10:12:56 +000014148 if (!Update.isUsable() || !Final.isUsable()) {
14149 Updates.push_back(nullptr);
14150 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014151 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014152 HasErrors = true;
14153 } else {
14154 Updates.push_back(Update.get());
14155 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014156 if (!Info.first)
14157 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014158 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014159 ++CurInit;
14160 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014161 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014162 if (Expr *S = Clause.getStep())
14163 UsedExprs.push_back(S);
14164 // Fill the remaining part with the nullptr.
14165 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014166 Clause.setUpdates(Updates);
14167 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014168 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014169 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014170}
14171
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014172OMPClause *Sema::ActOnOpenMPAlignedClause(
14173 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14174 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014175 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014176 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014177 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14178 SourceLocation ELoc;
14179 SourceRange ERange;
14180 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014181 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014182 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014183 // It will be analyzed later.
14184 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014185 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014186 ValueDecl *D = Res.first;
14187 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014188 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014189
Alexey Bataev1efd1662016-03-29 10:59:56 +000014190 QualType QType = D->getType();
14191 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014192
14193 // OpenMP [2.8.1, simd construct, Restrictions]
14194 // The type of list items appearing in the aligned clause must be
14195 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014196 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014197 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014198 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014199 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014200 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014201 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014202 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014203 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014204 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014205 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014206 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014207 continue;
14208 }
14209
14210 // OpenMP [2.8.1, simd construct, Restrictions]
14211 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014212 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000014213 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014214 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14215 << getOpenMPClauseName(OMPC_aligned);
14216 continue;
14217 }
14218
Alexey Bataev1efd1662016-03-29 10:59:56 +000014219 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014220 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014221 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14222 Vars.push_back(DefaultFunctionArrayConversion(
14223 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14224 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014225 }
14226
14227 // OpenMP [2.8.1, simd construct, Description]
14228 // The parameter of the aligned clause, alignment, must be a constant
14229 // positive integer expression.
14230 // If no optional parameter is specified, implementation-defined default
14231 // alignments for SIMD instructions on the target platforms are assumed.
14232 if (Alignment != nullptr) {
14233 ExprResult AlignResult =
14234 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14235 if (AlignResult.isInvalid())
14236 return nullptr;
14237 Alignment = AlignResult.get();
14238 }
14239 if (Vars.empty())
14240 return nullptr;
14241
14242 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14243 EndLoc, Vars, Alignment);
14244}
14245
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014246OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14247 SourceLocation StartLoc,
14248 SourceLocation LParenLoc,
14249 SourceLocation EndLoc) {
14250 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014251 SmallVector<Expr *, 8> SrcExprs;
14252 SmallVector<Expr *, 8> DstExprs;
14253 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014254 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014255 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14256 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014257 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014258 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014259 SrcExprs.push_back(nullptr);
14260 DstExprs.push_back(nullptr);
14261 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014262 continue;
14263 }
14264
Alexey Bataeved09d242014-05-28 05:53:51 +000014265 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014266 // OpenMP [2.1, C/C++]
14267 // A list item is a variable name.
14268 // OpenMP [2.14.4.1, Restrictions, p.1]
14269 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014270 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014271 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014272 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14273 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014274 continue;
14275 }
14276
14277 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014278 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014279
14280 QualType Type = VD->getType();
14281 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14282 // It will be analyzed later.
14283 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014284 SrcExprs.push_back(nullptr);
14285 DstExprs.push_back(nullptr);
14286 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014287 continue;
14288 }
14289
14290 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14291 // A list item that appears in a copyin clause must be threadprivate.
14292 if (!DSAStack->isThreadPrivate(VD)) {
14293 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014294 << getOpenMPClauseName(OMPC_copyin)
14295 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014296 continue;
14297 }
14298
14299 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14300 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014301 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014302 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014303 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14304 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014305 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014306 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014307 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014308 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014309 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014310 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014311 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014312 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014313 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014314 // For arrays generate assignment operation for single element and replace
14315 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014316 ExprResult AssignmentOp =
14317 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14318 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014319 if (AssignmentOp.isInvalid())
14320 continue;
14321 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014322 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014323 if (AssignmentOp.isInvalid())
14324 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014325
14326 DSAStack->addDSA(VD, DE, OMPC_copyin);
14327 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014328 SrcExprs.push_back(PseudoSrcExpr);
14329 DstExprs.push_back(PseudoDstExpr);
14330 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014331 }
14332
Alexey Bataeved09d242014-05-28 05:53:51 +000014333 if (Vars.empty())
14334 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014335
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014336 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14337 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014338}
14339
Alexey Bataevbae9a792014-06-27 10:37:06 +000014340OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14341 SourceLocation StartLoc,
14342 SourceLocation LParenLoc,
14343 SourceLocation EndLoc) {
14344 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014345 SmallVector<Expr *, 8> SrcExprs;
14346 SmallVector<Expr *, 8> DstExprs;
14347 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014348 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014349 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14350 SourceLocation ELoc;
14351 SourceRange ERange;
14352 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014353 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014354 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014355 // It will be analyzed later.
14356 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014357 SrcExprs.push_back(nullptr);
14358 DstExprs.push_back(nullptr);
14359 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014360 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014361 ValueDecl *D = Res.first;
14362 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014363 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014364
Alexey Bataeve122da12016-03-17 10:50:17 +000014365 QualType Type = D->getType();
14366 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014367
14368 // OpenMP [2.14.4.2, Restrictions, p.2]
14369 // A list item that appears in a copyprivate clause may not appear in a
14370 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014371 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014372 DSAStackTy::DSAVarData DVar =
14373 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014374 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14375 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014376 Diag(ELoc, diag::err_omp_wrong_dsa)
14377 << getOpenMPClauseName(DVar.CKind)
14378 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014379 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014380 continue;
14381 }
14382
14383 // OpenMP [2.11.4.2, Restrictions, p.1]
14384 // All list items that appear in a copyprivate clause must be either
14385 // threadprivate or private in the enclosing context.
14386 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014387 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014388 if (DVar.CKind == OMPC_shared) {
14389 Diag(ELoc, diag::err_omp_required_access)
14390 << getOpenMPClauseName(OMPC_copyprivate)
14391 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014392 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014393 continue;
14394 }
14395 }
14396 }
14397
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014398 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014399 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014400 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014401 << getOpenMPClauseName(OMPC_copyprivate) << Type
14402 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014403 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014404 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014405 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014406 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014407 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014408 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014409 continue;
14410 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014411
Alexey Bataevbae9a792014-06-27 10:37:06 +000014412 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14413 // A variable of class type (or array thereof) that appears in a
14414 // copyin clause requires an accessible, unambiguous copy assignment
14415 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014416 Type = Context.getBaseElementType(Type.getNonReferenceType())
14417 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014418 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014419 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014420 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014421 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14422 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014423 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014424 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014425 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14426 ExprResult AssignmentOp = BuildBinOp(
14427 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014428 if (AssignmentOp.isInvalid())
14429 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014430 AssignmentOp =
14431 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014432 if (AssignmentOp.isInvalid())
14433 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014434
14435 // No need to mark vars as copyprivate, they are already threadprivate or
14436 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014437 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014438 Vars.push_back(
14439 VD ? RefExpr->IgnoreParens()
14440 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014441 SrcExprs.push_back(PseudoSrcExpr);
14442 DstExprs.push_back(PseudoDstExpr);
14443 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014444 }
14445
14446 if (Vars.empty())
14447 return nullptr;
14448
Alexey Bataeva63048e2015-03-23 06:18:07 +000014449 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14450 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014451}
14452
Alexey Bataev6125da92014-07-21 11:26:11 +000014453OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14454 SourceLocation StartLoc,
14455 SourceLocation LParenLoc,
14456 SourceLocation EndLoc) {
14457 if (VarList.empty())
14458 return nullptr;
14459
14460 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14461}
Alexey Bataevdea47612014-07-23 07:46:59 +000014462
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014463OMPClause *
14464Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14465 SourceLocation DepLoc, SourceLocation ColonLoc,
14466 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14467 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014468 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014469 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014470 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014471 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014472 return nullptr;
14473 }
14474 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014475 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14476 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014477 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014478 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014479 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14480 /*Last=*/OMPC_DEPEND_unknown, Except)
14481 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014482 return nullptr;
14483 }
14484 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014485 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014486 llvm::APSInt DepCounter(/*BitWidth=*/32);
14487 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014488 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14489 if (const Expr *OrderedCountExpr =
14490 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014491 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14492 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014493 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014494 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014495 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014496 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14497 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14498 // It will be analyzed later.
14499 Vars.push_back(RefExpr);
14500 continue;
14501 }
14502
14503 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014504 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014505 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014506 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014507 DepCounter >= TotalDepCount) {
14508 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14509 continue;
14510 }
14511 ++DepCounter;
14512 // OpenMP [2.13.9, Summary]
14513 // depend(dependence-type : vec), where dependence-type is:
14514 // 'sink' and where vec is the iteration vector, which has the form:
14515 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14516 // where n is the value specified by the ordered clause in the loop
14517 // directive, xi denotes the loop iteration variable of the i-th nested
14518 // loop associated with the loop directive, and di is a constant
14519 // non-negative integer.
14520 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014521 // It will be analyzed later.
14522 Vars.push_back(RefExpr);
14523 continue;
14524 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014525 SimpleExpr = SimpleExpr->IgnoreImplicit();
14526 OverloadedOperatorKind OOK = OO_None;
14527 SourceLocation OOLoc;
14528 Expr *LHS = SimpleExpr;
14529 Expr *RHS = nullptr;
14530 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14531 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14532 OOLoc = BO->getOperatorLoc();
14533 LHS = BO->getLHS()->IgnoreParenImpCasts();
14534 RHS = BO->getRHS()->IgnoreParenImpCasts();
14535 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14536 OOK = OCE->getOperator();
14537 OOLoc = OCE->getOperatorLoc();
14538 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14539 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14540 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14541 OOK = MCE->getMethodDecl()
14542 ->getNameInfo()
14543 .getName()
14544 .getCXXOverloadedOperator();
14545 OOLoc = MCE->getCallee()->getExprLoc();
14546 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14547 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014548 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014549 SourceLocation ELoc;
14550 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014551 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014552 if (Res.second) {
14553 // It will be analyzed later.
14554 Vars.push_back(RefExpr);
14555 }
14556 ValueDecl *D = Res.first;
14557 if (!D)
14558 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014559
Alexey Bataev17daedf2018-02-15 22:42:57 +000014560 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14561 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14562 continue;
14563 }
14564 if (RHS) {
14565 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14566 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14567 if (RHSRes.isInvalid())
14568 continue;
14569 }
14570 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014571 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014572 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014573 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014574 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014575 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014576 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14577 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014578 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014579 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014580 continue;
14581 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014582 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014583 } else {
14584 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14585 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14586 (ASE &&
14587 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14588 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14589 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14590 << RefExpr->getSourceRange();
14591 continue;
14592 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014593
14594 ExprResult Res;
14595 {
14596 Sema::TentativeAnalysisScope Trap(*this);
14597 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14598 RefExpr->IgnoreParenImpCasts());
14599 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014600 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14601 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14602 << RefExpr->getSourceRange();
14603 continue;
14604 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014605 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014606 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014607 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014608
14609 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14610 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014611 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014612 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14613 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14614 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14615 }
14616 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14617 Vars.empty())
14618 return nullptr;
14619
Alexey Bataev8b427062016-05-25 12:36:08 +000014620 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014621 DepKind, DepLoc, ColonLoc, Vars,
14622 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014623 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14624 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014625 DSAStack->addDoacrossDependClause(C, OpsOffs);
14626 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014627}
Michael Wonge710d542015-08-07 16:16:36 +000014628
14629OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14630 SourceLocation LParenLoc,
14631 SourceLocation EndLoc) {
14632 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014633 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014634
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014635 // OpenMP [2.9.1, Restrictions]
14636 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014637 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014638 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014639 return nullptr;
14640
Alexey Bataev931e19b2017-10-02 16:32:39 +000014641 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014642 OpenMPDirectiveKind CaptureRegion =
14643 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
14644 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014645 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014646 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014647 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14648 HelperValStmt = buildPreInits(Context, Captures);
14649 }
14650
Alexey Bataev8451efa2018-01-15 19:06:12 +000014651 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14652 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014653}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014654
Alexey Bataeve3727102018-04-18 15:57:46 +000014655static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014656 DSAStackTy *Stack, QualType QTy,
14657 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014658 NamedDecl *ND;
14659 if (QTy->isIncompleteType(&ND)) {
14660 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14661 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014662 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014663 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14664 !QTy.isTrivialType(SemaRef.Context))
14665 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014666 return true;
14667}
14668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014669/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014670/// (array section or array subscript) does NOT specify the whole size of the
14671/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014672static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014673 const Expr *E,
14674 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014675 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014676
14677 // If this is an array subscript, it refers to the whole size if the size of
14678 // the dimension is constant and equals 1. Also, an array section assumes the
14679 // format of an array subscript if no colon is used.
14680 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014681 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014682 return ATy->getSize().getSExtValue() != 1;
14683 // Size can't be evaluated statically.
14684 return false;
14685 }
14686
14687 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014688 const Expr *LowerBound = OASE->getLowerBound();
14689 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014690
14691 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014692 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014693 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014694 Expr::EvalResult Result;
14695 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014696 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014697
14698 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014699 if (ConstLowerBound.getSExtValue())
14700 return true;
14701 }
14702
14703 // If we don't have a length we covering the whole dimension.
14704 if (!Length)
14705 return false;
14706
14707 // If the base is a pointer, we don't have a way to get the size of the
14708 // pointee.
14709 if (BaseQTy->isPointerType())
14710 return false;
14711
14712 // We can only check if the length is the same as the size of the dimension
14713 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014714 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014715 if (!CATy)
14716 return false;
14717
Fangrui Song407659a2018-11-30 23:41:18 +000014718 Expr::EvalResult Result;
14719 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014720 return false; // Can't get the integer value as a constant.
14721
Fangrui Song407659a2018-11-30 23:41:18 +000014722 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014723 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14724}
14725
14726// Return true if it can be proven that the provided array expression (array
14727// section or array subscript) does NOT specify a single element of the array
14728// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014729static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014730 const Expr *E,
14731 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014732 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014733
14734 // An array subscript always refer to a single element. Also, an array section
14735 // assumes the format of an array subscript if no colon is used.
14736 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14737 return false;
14738
14739 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014740 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014741
14742 // If we don't have a length we have to check if the array has unitary size
14743 // for this dimension. Also, we should always expect a length if the base type
14744 // is pointer.
14745 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014746 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014747 return ATy->getSize().getSExtValue() != 1;
14748 // We cannot assume anything.
14749 return false;
14750 }
14751
14752 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014753 Expr::EvalResult Result;
14754 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014755 return false; // Can't get the integer value as a constant.
14756
Fangrui Song407659a2018-11-30 23:41:18 +000014757 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014758 return ConstLength.getSExtValue() != 1;
14759}
14760
Samuel Antao661c0902016-05-26 17:39:58 +000014761// Return the expression of the base of the mappable expression or null if it
14762// cannot be determined and do all the necessary checks to see if the expression
14763// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014764// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014765static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014766 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014767 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014768 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014769 SourceLocation ELoc = E->getExprLoc();
14770 SourceRange ERange = E->getSourceRange();
14771
14772 // The base of elements of list in a map clause have to be either:
14773 // - a reference to variable or field.
14774 // - a member expression.
14775 // - an array expression.
14776 //
14777 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14778 // reference to 'r'.
14779 //
14780 // If we have:
14781 //
14782 // struct SS {
14783 // Bla S;
14784 // foo() {
14785 // #pragma omp target map (S.Arr[:12]);
14786 // }
14787 // }
14788 //
14789 // We want to retrieve the member expression 'this->S';
14790
Alexey Bataeve3727102018-04-18 15:57:46 +000014791 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014792
Samuel Antao5de996e2016-01-22 20:21:36 +000014793 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
14794 // If a list item is an array section, it must specify contiguous storage.
14795 //
14796 // For this restriction it is sufficient that we make sure only references
14797 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014798 // exist except in the rightmost expression (unless they cover the whole
14799 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000014800 //
14801 // r.ArrS[3:5].Arr[6:7]
14802 //
14803 // r.ArrS[3:5].x
14804 //
14805 // but these would be valid:
14806 // r.ArrS[3].Arr[6:7]
14807 //
14808 // r.ArrS[3].x
14809
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014810 bool AllowUnitySizeArraySection = true;
14811 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014812
Dmitry Polukhin644a9252016-03-11 07:58:34 +000014813 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014814 E = E->IgnoreParenImpCasts();
14815
14816 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
14817 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000014818 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014819
14820 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014821
14822 // If we got a reference to a declaration, we should not expect any array
14823 // section before that.
14824 AllowUnitySizeArraySection = false;
14825 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014826
14827 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014828 CurComponents.emplace_back(CurE, CurE->getDecl());
14829 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014830 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000014831
14832 if (isa<CXXThisExpr>(BaseE))
14833 // We found a base expression: this->Val.
14834 RelevantExpr = CurE;
14835 else
14836 E = BaseE;
14837
14838 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014839 if (!NoDiagnose) {
14840 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
14841 << CurE->getSourceRange();
14842 return nullptr;
14843 }
14844 if (RelevantExpr)
14845 return nullptr;
14846 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014847 }
14848
14849 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
14850
14851 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
14852 // A bit-field cannot appear in a map clause.
14853 //
14854 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014855 if (!NoDiagnose) {
14856 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
14857 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
14858 return nullptr;
14859 }
14860 if (RelevantExpr)
14861 return nullptr;
14862 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014863 }
14864
14865 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14866 // If the type of a list item is a reference to a type T then the type
14867 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014868 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014869
14870 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
14871 // A list item cannot be a variable that is a member of a structure with
14872 // a union type.
14873 //
Alexey Bataeve3727102018-04-18 15:57:46 +000014874 if (CurType->isUnionType()) {
14875 if (!NoDiagnose) {
14876 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
14877 << CurE->getSourceRange();
14878 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014879 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014880 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014881 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014882
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014883 // If we got a member expression, we should not expect any array section
14884 // before that:
14885 //
14886 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
14887 // If a list item is an element of a structure, only the rightmost symbol
14888 // of the variable reference can be an array section.
14889 //
14890 AllowUnitySizeArraySection = false;
14891 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014892
14893 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014894 CurComponents.emplace_back(CurE, FD);
14895 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014896 E = CurE->getBase()->IgnoreParenImpCasts();
14897
14898 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014899 if (!NoDiagnose) {
14900 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14901 << 0 << CurE->getSourceRange();
14902 return nullptr;
14903 }
14904 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014905 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014906
14907 // If we got an array subscript that express the whole dimension we
14908 // can have any array expressions before. If it only expressing part of
14909 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000014910 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014911 E->getType()))
14912 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014913
Patrick Lystere13b1e32019-01-02 19:28:48 +000014914 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14915 Expr::EvalResult Result;
14916 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
14917 if (!Result.Val.getInt().isNullValue()) {
14918 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14919 diag::err_omp_invalid_map_this_expr);
14920 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14921 diag::note_omp_invalid_subscript_on_this_ptr_map);
14922 }
14923 }
14924 RelevantExpr = TE;
14925 }
14926
Samuel Antao90927002016-04-26 14:54:23 +000014927 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014928 CurComponents.emplace_back(CurE, nullptr);
14929 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014930 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000014931 E = CurE->getBase()->IgnoreParenImpCasts();
14932
Alexey Bataev27041fa2017-12-05 15:22:49 +000014933 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014934 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14935
Samuel Antao5de996e2016-01-22 20:21:36 +000014936 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14937 // If the type of a list item is a reference to a type T then the type
14938 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000014939 if (CurType->isReferenceType())
14940 CurType = CurType->getPointeeType();
14941
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014942 bool IsPointer = CurType->isAnyPointerType();
14943
14944 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014945 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14946 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014947 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014948 }
14949
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014950 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000014951 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014952 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000014953 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014954
Samuel Antaodab51bb2016-07-18 23:22:11 +000014955 if (AllowWholeSizeArraySection) {
14956 // Any array section is currently allowed. Allowing a whole size array
14957 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014958 //
14959 // If this array section refers to the whole dimension we can still
14960 // accept other array sections before this one, except if the base is a
14961 // pointer. Otherwise, only unitary sections are accepted.
14962 if (NotWhole || IsPointer)
14963 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000014964 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014965 // A unity or whole array section is not allowed and that is not
14966 // compatible with the properties of the current array section.
14967 SemaRef.Diag(
14968 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
14969 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014970 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014971 }
Samuel Antao90927002016-04-26 14:54:23 +000014972
Patrick Lystere13b1e32019-01-02 19:28:48 +000014973 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14974 Expr::EvalResult ResultR;
14975 Expr::EvalResult ResultL;
14976 if (CurE->getLength()->EvaluateAsInt(ResultR,
14977 SemaRef.getASTContext())) {
14978 if (!ResultR.Val.getInt().isOneValue()) {
14979 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14980 diag::err_omp_invalid_map_this_expr);
14981 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14982 diag::note_omp_invalid_length_on_this_ptr_mapping);
14983 }
14984 }
14985 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
14986 ResultL, SemaRef.getASTContext())) {
14987 if (!ResultL.Val.getInt().isNullValue()) {
14988 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14989 diag::err_omp_invalid_map_this_expr);
14990 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14991 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
14992 }
14993 }
14994 RelevantExpr = TE;
14995 }
14996
Samuel Antao90927002016-04-26 14:54:23 +000014997 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014998 CurComponents.emplace_back(CurE, nullptr);
14999 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015000 if (!NoDiagnose) {
15001 // If nothing else worked, this is not a valid map clause expression.
15002 SemaRef.Diag(
15003 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15004 << ERange;
15005 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015006 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015007 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015008 }
15009
15010 return RelevantExpr;
15011}
15012
15013// Return true if expression E associated with value VD has conflicts with other
15014// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015015static bool checkMapConflicts(
15016 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015017 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015018 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15019 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015020 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015021 SourceLocation ELoc = E->getExprLoc();
15022 SourceRange ERange = E->getSourceRange();
15023
15024 // In order to easily check the conflicts we need to match each component of
15025 // the expression under test with the components of the expressions that are
15026 // already in the stack.
15027
Samuel Antao5de996e2016-01-22 20:21:36 +000015028 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015029 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015030 "Map clause expression with unexpected base!");
15031
15032 // Variables to help detecting enclosing problems in data environment nests.
15033 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015034 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015035
Samuel Antao90927002016-04-26 14:54:23 +000015036 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15037 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015038 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15039 ERange, CKind, &EnclosingExpr,
15040 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15041 StackComponents,
15042 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015043 assert(!StackComponents.empty() &&
15044 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015045 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015046 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015047 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015048
Samuel Antao90927002016-04-26 14:54:23 +000015049 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015050 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015051
Samuel Antao5de996e2016-01-22 20:21:36 +000015052 // Expressions must start from the same base. Here we detect at which
15053 // point both expressions diverge from each other and see if we can
15054 // detect if the memory referred to both expressions is contiguous and
15055 // do not overlap.
15056 auto CI = CurComponents.rbegin();
15057 auto CE = CurComponents.rend();
15058 auto SI = StackComponents.rbegin();
15059 auto SE = StackComponents.rend();
15060 for (; CI != CE && SI != SE; ++CI, ++SI) {
15061
15062 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15063 // At most one list item can be an array item derived from a given
15064 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015065 if (CurrentRegionOnly &&
15066 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15067 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15068 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15069 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15070 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015071 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015072 << CI->getAssociatedExpression()->getSourceRange();
15073 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15074 diag::note_used_here)
15075 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015076 return true;
15077 }
15078
15079 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015080 if (CI->getAssociatedExpression()->getStmtClass() !=
15081 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015082 break;
15083
15084 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015085 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015086 break;
15087 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015088 // Check if the extra components of the expressions in the enclosing
15089 // data environment are redundant for the current base declaration.
15090 // If they are, the maps completely overlap, which is legal.
15091 for (; SI != SE; ++SI) {
15092 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015093 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015094 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015095 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015096 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015097 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015098 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015099 Type =
15100 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15101 }
15102 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015103 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015104 SemaRef, SI->getAssociatedExpression(), Type))
15105 break;
15106 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015107
15108 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15109 // List items of map clauses in the same construct must not share
15110 // original storage.
15111 //
15112 // If the expressions are exactly the same or one is a subset of the
15113 // other, it means they are sharing storage.
15114 if (CI == CE && SI == SE) {
15115 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015116 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015117 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015118 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015119 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015120 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15121 << ERange;
15122 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015123 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15124 << RE->getSourceRange();
15125 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015126 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015127 // If we find the same expression in the enclosing data environment,
15128 // that is legal.
15129 IsEnclosedByDataEnvironmentExpr = true;
15130 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015131 }
15132
Samuel Antao90927002016-04-26 14:54:23 +000015133 QualType DerivedType =
15134 std::prev(CI)->getAssociatedDeclaration()->getType();
15135 SourceLocation DerivedLoc =
15136 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015137
15138 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15139 // If the type of a list item is a reference to a type T then the type
15140 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015141 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015142
15143 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15144 // A variable for which the type is pointer and an array section
15145 // derived from that variable must not appear as list items of map
15146 // clauses of the same construct.
15147 //
15148 // Also, cover one of the cases in:
15149 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15150 // If any part of the original storage of a list item has corresponding
15151 // storage in the device data environment, all of the original storage
15152 // must have corresponding storage in the device data environment.
15153 //
15154 if (DerivedType->isAnyPointerType()) {
15155 if (CI == CE || SI == SE) {
15156 SemaRef.Diag(
15157 DerivedLoc,
15158 diag::err_omp_pointer_mapped_along_with_derived_section)
15159 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015160 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15161 << RE->getSourceRange();
15162 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015163 }
15164 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015165 SI->getAssociatedExpression()->getStmtClass() ||
15166 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15167 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015168 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015169 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015170 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015171 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15172 << RE->getSourceRange();
15173 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015174 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015175 }
15176
15177 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15178 // List items of map clauses in the same construct must not share
15179 // original storage.
15180 //
15181 // An expression is a subset of the other.
15182 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015183 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015184 if (CI != CE || SI != SE) {
15185 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15186 // a pointer.
15187 auto Begin =
15188 CI != CE ? CurComponents.begin() : StackComponents.begin();
15189 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15190 auto It = Begin;
15191 while (It != End && !It->getAssociatedDeclaration())
15192 std::advance(It, 1);
15193 assert(It != End &&
15194 "Expected at least one component with the declaration.");
15195 if (It != Begin && It->getAssociatedDeclaration()
15196 ->getType()
15197 .getCanonicalType()
15198 ->isAnyPointerType()) {
15199 IsEnclosedByDataEnvironmentExpr = false;
15200 EnclosingExpr = nullptr;
15201 return false;
15202 }
15203 }
Samuel Antao661c0902016-05-26 17:39:58 +000015204 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015205 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015206 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015207 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15208 << ERange;
15209 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015210 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15211 << RE->getSourceRange();
15212 return true;
15213 }
15214
15215 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015216 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015217 if (!CurrentRegionOnly && SI != SE)
15218 EnclosingExpr = RE;
15219
15220 // The current expression is a subset of the expression in the data
15221 // environment.
15222 IsEnclosedByDataEnvironmentExpr |=
15223 (!CurrentRegionOnly && CI != CE && SI == SE);
15224
15225 return false;
15226 });
15227
15228 if (CurrentRegionOnly)
15229 return FoundError;
15230
15231 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15232 // If any part of the original storage of a list item has corresponding
15233 // storage in the device data environment, all of the original storage must
15234 // have corresponding storage in the device data environment.
15235 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15236 // If a list item is an element of a structure, and a different element of
15237 // the structure has a corresponding list item in the device data environment
15238 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015239 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015240 // data environment prior to the task encountering the construct.
15241 //
15242 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15243 SemaRef.Diag(ELoc,
15244 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15245 << ERange;
15246 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15247 << EnclosingExpr->getSourceRange();
15248 return true;
15249 }
15250
15251 return FoundError;
15252}
15253
Michael Kruse4304e9d2019-02-19 16:38:20 +000015254// Look up the user-defined mapper given the mapper name and mapped type, and
15255// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015256static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15257 CXXScopeSpec &MapperIdScopeSpec,
15258 const DeclarationNameInfo &MapperId,
15259 QualType Type,
15260 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015261 if (MapperIdScopeSpec.isInvalid())
15262 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015263 // Get the actual type for the array type.
15264 if (Type->isArrayType()) {
15265 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15266 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15267 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015268 // Find all user-defined mappers with the given MapperId.
15269 SmallVector<UnresolvedSet<8>, 4> Lookups;
15270 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15271 Lookup.suppressDiagnostics();
15272 if (S) {
15273 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15274 NamedDecl *D = Lookup.getRepresentativeDecl();
15275 while (S && !S->isDeclScope(D))
15276 S = S->getParent();
15277 if (S)
15278 S = S->getParent();
15279 Lookups.emplace_back();
15280 Lookups.back().append(Lookup.begin(), Lookup.end());
15281 Lookup.clear();
15282 }
15283 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15284 // Extract the user-defined mappers with the given MapperId.
15285 Lookups.push_back(UnresolvedSet<8>());
15286 for (NamedDecl *D : ULE->decls()) {
15287 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15288 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15289 Lookups.back().addDecl(DMD);
15290 }
15291 }
15292 // Defer the lookup for dependent types. The results will be passed through
15293 // UnresolvedMapper on instantiation.
15294 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15295 Type->isInstantiationDependentType() ||
15296 Type->containsUnexpandedParameterPack() ||
15297 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15298 return !D->isInvalidDecl() &&
15299 (D->getType()->isDependentType() ||
15300 D->getType()->isInstantiationDependentType() ||
15301 D->getType()->containsUnexpandedParameterPack());
15302 })) {
15303 UnresolvedSet<8> URS;
15304 for (const UnresolvedSet<8> &Set : Lookups) {
15305 if (Set.empty())
15306 continue;
15307 URS.append(Set.begin(), Set.end());
15308 }
15309 return UnresolvedLookupExpr::Create(
15310 SemaRef.Context, /*NamingClass=*/nullptr,
15311 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15312 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15313 }
Michael Kruse945249b2019-09-26 22:53:01 +000015314 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015315 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15316 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015317 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15318 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15319 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15320 return ExprError();
15321 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015322 // Perform argument dependent lookup.
15323 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15324 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15325 // Return the first user-defined mapper with the desired type.
15326 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15327 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15328 if (!D->isInvalidDecl() &&
15329 SemaRef.Context.hasSameType(D->getType(), Type))
15330 return D;
15331 return nullptr;
15332 }))
15333 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15334 // Find the first user-defined mapper with a type derived from the desired
15335 // type.
15336 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15337 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15338 if (!D->isInvalidDecl() &&
15339 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15340 !Type.isMoreQualifiedThan(D->getType()))
15341 return D;
15342 return nullptr;
15343 })) {
15344 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15345 /*DetectVirtual=*/false);
15346 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15347 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15348 VD->getType().getUnqualifiedType()))) {
15349 if (SemaRef.CheckBaseClassAccess(
15350 Loc, VD->getType(), Type, Paths.front(),
15351 /*DiagID=*/0) != Sema::AR_inaccessible) {
15352 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15353 }
15354 }
15355 }
15356 }
15357 // Report error if a mapper is specified, but cannot be found.
15358 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15359 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15360 << Type << MapperId.getName();
15361 return ExprError();
15362 }
15363 return ExprEmpty();
15364}
15365
Samuel Antao661c0902016-05-26 17:39:58 +000015366namespace {
15367// Utility struct that gathers all the related lists associated with a mappable
15368// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015369struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015370 // The list of expressions.
15371 ArrayRef<Expr *> VarList;
15372 // The list of processed expressions.
15373 SmallVector<Expr *, 16> ProcessedVarList;
15374 // The mappble components for each expression.
15375 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15376 // The base declaration of the variable.
15377 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015378 // The reference to the user-defined mapper associated with every expression.
15379 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015380
15381 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15382 // We have a list of components and base declarations for each entry in the
15383 // variable list.
15384 VarComponents.reserve(VarList.size());
15385 VarBaseDeclarations.reserve(VarList.size());
15386 }
15387};
15388}
15389
15390// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015391// \a CKind. In the check process the valid expressions, mappable expression
15392// components, variables, and user-defined mappers are extracted and used to
15393// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15394// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15395// and \a MapperId are expected to be valid if the clause kind is 'map'.
15396static void checkMappableExpressionList(
15397 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15398 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015399 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15400 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015401 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015402 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015403 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15404 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015405 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015406
15407 // If the identifier of user-defined mapper is not specified, it is "default".
15408 // We do not change the actual name in this clause to distinguish whether a
15409 // mapper is specified explicitly, i.e., it is not explicitly specified when
15410 // MapperId.getName() is empty.
15411 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15412 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15413 MapperId.setName(DeclNames.getIdentifier(
15414 &SemaRef.getASTContext().Idents.get("default")));
15415 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015416
15417 // Iterators to find the current unresolved mapper expression.
15418 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15419 bool UpdateUMIt = false;
15420 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015421
Samuel Antao90927002016-04-26 14:54:23 +000015422 // Keep track of the mappable components and base declarations in this clause.
15423 // Each entry in the list is going to have a list of components associated. We
15424 // record each set of the components so that we can build the clause later on.
15425 // In the end we should have the same amount of declarations and component
15426 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015427
Alexey Bataeve3727102018-04-18 15:57:46 +000015428 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015429 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015430 SourceLocation ELoc = RE->getExprLoc();
15431
Michael Kruse4304e9d2019-02-19 16:38:20 +000015432 // Find the current unresolved mapper expression.
15433 if (UpdateUMIt && UMIt != UMEnd) {
15434 UMIt++;
15435 assert(
15436 UMIt != UMEnd &&
15437 "Expect the size of UnresolvedMappers to match with that of VarList");
15438 }
15439 UpdateUMIt = true;
15440 if (UMIt != UMEnd)
15441 UnresolvedMapper = *UMIt;
15442
Alexey Bataeve3727102018-04-18 15:57:46 +000015443 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015444
15445 if (VE->isValueDependent() || VE->isTypeDependent() ||
15446 VE->isInstantiationDependent() ||
15447 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015448 // Try to find the associated user-defined mapper.
15449 ExprResult ER = buildUserDefinedMapperRef(
15450 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15451 VE->getType().getCanonicalType(), UnresolvedMapper);
15452 if (ER.isInvalid())
15453 continue;
15454 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015455 // We can only analyze this information once the missing information is
15456 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015457 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015458 continue;
15459 }
15460
Alexey Bataeve3727102018-04-18 15:57:46 +000015461 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015462
Samuel Antao5de996e2016-01-22 20:21:36 +000015463 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015464 SemaRef.Diag(ELoc,
15465 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015466 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015467 continue;
15468 }
15469
Samuel Antao90927002016-04-26 14:54:23 +000015470 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15471 ValueDecl *CurDeclaration = nullptr;
15472
15473 // Obtain the array or member expression bases if required. Also, fill the
15474 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015475 const Expr *BE = checkMapClauseExpressionBase(
15476 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015477 if (!BE)
15478 continue;
15479
Samuel Antao90927002016-04-26 14:54:23 +000015480 assert(!CurComponents.empty() &&
15481 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015482
Patrick Lystere13b1e32019-01-02 19:28:48 +000015483 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15484 // Add store "this" pointer to class in DSAStackTy for future checking
15485 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015486 // Try to find the associated user-defined mapper.
15487 ExprResult ER = buildUserDefinedMapperRef(
15488 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15489 VE->getType().getCanonicalType(), UnresolvedMapper);
15490 if (ER.isInvalid())
15491 continue;
15492 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015493 // Skip restriction checking for variable or field declarations
15494 MVLI.ProcessedVarList.push_back(RE);
15495 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15496 MVLI.VarComponents.back().append(CurComponents.begin(),
15497 CurComponents.end());
15498 MVLI.VarBaseDeclarations.push_back(nullptr);
15499 continue;
15500 }
15501
Samuel Antao90927002016-04-26 14:54:23 +000015502 // For the following checks, we rely on the base declaration which is
15503 // expected to be associated with the last component. The declaration is
15504 // expected to be a variable or a field (if 'this' is being mapped).
15505 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15506 assert(CurDeclaration && "Null decl on map clause.");
15507 assert(
15508 CurDeclaration->isCanonicalDecl() &&
15509 "Expecting components to have associated only canonical declarations.");
15510
15511 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015512 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015513
15514 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015515 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015516
15517 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015518 // threadprivate variables cannot appear in a map clause.
15519 // OpenMP 4.5 [2.10.5, target update Construct]
15520 // threadprivate variables cannot appear in a from clause.
15521 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015522 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015523 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15524 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015525 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015526 continue;
15527 }
15528
Samuel Antao5de996e2016-01-22 20:21:36 +000015529 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15530 // A list item cannot appear in both a map clause and a data-sharing
15531 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015532
Samuel Antao5de996e2016-01-22 20:21:36 +000015533 // Check conflicts with other map clause expressions. We check the conflicts
15534 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015535 // environment, because the restrictions are different. We only have to
15536 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015537 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015538 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015539 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015540 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015541 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015542 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015543 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015544
Samuel Antao661c0902016-05-26 17:39:58 +000015545 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015546 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15547 // If the type of a list item is a reference to a type T then the type will
15548 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015549 auto I = llvm::find_if(
15550 CurComponents,
15551 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15552 return MC.getAssociatedDeclaration();
15553 });
15554 assert(I != CurComponents.end() && "Null decl on map clause.");
15555 QualType Type =
15556 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015557
Samuel Antao661c0902016-05-26 17:39:58 +000015558 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15559 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015560 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015561 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015562 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015563 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015564 continue;
15565
Samuel Antao661c0902016-05-26 17:39:58 +000015566 if (CKind == OMPC_map) {
15567 // target enter data
15568 // OpenMP [2.10.2, Restrictions, p. 99]
15569 // A map-type must be specified in all map clauses and must be either
15570 // to or alloc.
15571 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15572 if (DKind == OMPD_target_enter_data &&
15573 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15574 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15575 << (IsMapTypeImplicit ? 1 : 0)
15576 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15577 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015578 continue;
15579 }
Samuel Antao661c0902016-05-26 17:39:58 +000015580
15581 // target exit_data
15582 // OpenMP [2.10.3, Restrictions, p. 102]
15583 // A map-type must be specified in all map clauses and must be either
15584 // from, release, or delete.
15585 if (DKind == OMPD_target_exit_data &&
15586 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15587 MapType == OMPC_MAP_delete)) {
15588 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15589 << (IsMapTypeImplicit ? 1 : 0)
15590 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15591 << getOpenMPDirectiveName(DKind);
15592 continue;
15593 }
15594
15595 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15596 // A list item cannot appear in both a map clause and a data-sharing
15597 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015598 //
15599 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15600 // A list item cannot appear in both a map clause and a data-sharing
15601 // attribute clause on the same construct unless the construct is a
15602 // combined construct.
15603 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15604 isOpenMPTargetExecutionDirective(DKind)) ||
15605 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015606 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015607 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015608 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015609 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015610 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015611 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015612 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015613 continue;
15614 }
15615 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015616 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015617
Michael Kruse01f670d2019-02-22 22:29:42 +000015618 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015619 ExprResult ER = buildUserDefinedMapperRef(
15620 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15621 Type.getCanonicalType(), UnresolvedMapper);
15622 if (ER.isInvalid())
15623 continue;
15624 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015625
Samuel Antao90927002016-04-26 14:54:23 +000015626 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015627 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015628
15629 // Store the components in the stack so that they can be used to check
15630 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015631 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15632 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015633
15634 // Save the components and declaration to create the clause. For purposes of
15635 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015636 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015637 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15638 MVLI.VarComponents.back().append(CurComponents.begin(),
15639 CurComponents.end());
15640 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15641 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015642 }
Samuel Antao661c0902016-05-26 17:39:58 +000015643}
15644
Michael Kruse4304e9d2019-02-19 16:38:20 +000015645OMPClause *Sema::ActOnOpenMPMapClause(
15646 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15647 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15648 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15649 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15650 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15651 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15652 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15653 OMPC_MAP_MODIFIER_unknown,
15654 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015655 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15656
15657 // Process map-type-modifiers, flag errors for duplicate modifiers.
15658 unsigned Count = 0;
15659 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15660 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15661 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15662 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15663 continue;
15664 }
15665 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015666 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015667 Modifiers[Count] = MapTypeModifiers[I];
15668 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15669 ++Count;
15670 }
15671
Michael Kruse4304e9d2019-02-19 16:38:20 +000015672 MappableVarListInfo MVLI(VarList);
15673 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015674 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15675 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015676
Samuel Antao5de996e2016-01-22 20:21:36 +000015677 // We need to produce a map clause even if we don't have variables so that
15678 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015679 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15680 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15681 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15682 MapperIdScopeSpec.getWithLocInContext(Context),
15683 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015684}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015685
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015686QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15687 TypeResult ParsedType) {
15688 assert(ParsedType.isUsable());
15689
15690 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15691 if (ReductionType.isNull())
15692 return QualType();
15693
15694 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15695 // A type name in a declare reduction directive cannot be a function type, an
15696 // array type, a reference type, or a type qualified with const, volatile or
15697 // restrict.
15698 if (ReductionType.hasQualifiers()) {
15699 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15700 return QualType();
15701 }
15702
15703 if (ReductionType->isFunctionType()) {
15704 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15705 return QualType();
15706 }
15707 if (ReductionType->isReferenceType()) {
15708 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15709 return QualType();
15710 }
15711 if (ReductionType->isArrayType()) {
15712 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15713 return QualType();
15714 }
15715 return ReductionType;
15716}
15717
15718Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15719 Scope *S, DeclContext *DC, DeclarationName Name,
15720 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15721 AccessSpecifier AS, Decl *PrevDeclInScope) {
15722 SmallVector<Decl *, 8> Decls;
15723 Decls.reserve(ReductionTypes.size());
15724
15725 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015726 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015727 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15728 // A reduction-identifier may not be re-declared in the current scope for the
15729 // same type or for a type that is compatible according to the base language
15730 // rules.
15731 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15732 OMPDeclareReductionDecl *PrevDRD = nullptr;
15733 bool InCompoundScope = true;
15734 if (S != nullptr) {
15735 // Find previous declaration with the same name not referenced in other
15736 // declarations.
15737 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15738 InCompoundScope =
15739 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15740 LookupName(Lookup, S);
15741 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15742 /*AllowInlineNamespace=*/false);
15743 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015744 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015745 while (Filter.hasNext()) {
15746 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15747 if (InCompoundScope) {
15748 auto I = UsedAsPrevious.find(PrevDecl);
15749 if (I == UsedAsPrevious.end())
15750 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015751 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015752 UsedAsPrevious[D] = true;
15753 }
15754 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15755 PrevDecl->getLocation();
15756 }
15757 Filter.done();
15758 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015759 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015760 if (!PrevData.second) {
15761 PrevDRD = PrevData.first;
15762 break;
15763 }
15764 }
15765 }
15766 } else if (PrevDeclInScope != nullptr) {
15767 auto *PrevDRDInScope = PrevDRD =
15768 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15769 do {
15770 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15771 PrevDRDInScope->getLocation();
15772 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15773 } while (PrevDRDInScope != nullptr);
15774 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015775 for (const auto &TyData : ReductionTypes) {
15776 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015777 bool Invalid = false;
15778 if (I != PreviousRedeclTypes.end()) {
15779 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15780 << TyData.first;
15781 Diag(I->second, diag::note_previous_definition);
15782 Invalid = true;
15783 }
15784 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15785 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15786 Name, TyData.first, PrevDRD);
15787 DC->addDecl(DRD);
15788 DRD->setAccess(AS);
15789 Decls.push_back(DRD);
15790 if (Invalid)
15791 DRD->setInvalidDecl();
15792 else
15793 PrevDRD = DRD;
15794 }
15795
15796 return DeclGroupPtrTy::make(
15797 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
15798}
15799
15800void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
15801 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15802
15803 // Enter new function scope.
15804 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015805 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015806 getCurFunction()->setHasOMPDeclareReductionCombiner();
15807
15808 if (S != nullptr)
15809 PushDeclContext(S, DRD);
15810 else
15811 CurContext = DRD;
15812
Faisal Valid143a0c2017-04-01 21:30:49 +000015813 PushExpressionEvaluationContext(
15814 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015815
15816 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015817 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
15818 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
15819 // uses semantics of argument handles by value, but it should be passed by
15820 // reference. C lang does not support references, so pass all parameters as
15821 // pointers.
15822 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015823 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015824 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015825 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
15826 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
15827 // uses semantics of argument handles by value, but it should be passed by
15828 // reference. C lang does not support references, so pass all parameters as
15829 // pointers.
15830 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015831 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015832 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
15833 if (S != nullptr) {
15834 PushOnScopeChains(OmpInParm, S);
15835 PushOnScopeChains(OmpOutParm, S);
15836 } else {
15837 DRD->addDecl(OmpInParm);
15838 DRD->addDecl(OmpOutParm);
15839 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015840 Expr *InE =
15841 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
15842 Expr *OutE =
15843 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
15844 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015845}
15846
15847void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
15848 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15849 DiscardCleanupsInEvaluationContext();
15850 PopExpressionEvaluationContext();
15851
15852 PopDeclContext();
15853 PopFunctionScopeInfo();
15854
15855 if (Combiner != nullptr)
15856 DRD->setCombiner(Combiner);
15857 else
15858 DRD->setInvalidDecl();
15859}
15860
Alexey Bataev070f43a2017-09-06 14:49:58 +000015861VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015862 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15863
15864 // Enter new function scope.
15865 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015866 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015867
15868 if (S != nullptr)
15869 PushDeclContext(S, DRD);
15870 else
15871 CurContext = DRD;
15872
Faisal Valid143a0c2017-04-01 21:30:49 +000015873 PushExpressionEvaluationContext(
15874 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015875
15876 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015877 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
15878 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
15879 // uses semantics of argument handles by value, but it should be passed by
15880 // reference. C lang does not support references, so pass all parameters as
15881 // pointers.
15882 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015883 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015884 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015885 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
15886 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
15887 // uses semantics of argument handles by value, but it should be passed by
15888 // reference. C lang does not support references, so pass all parameters as
15889 // pointers.
15890 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015891 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015892 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015893 if (S != nullptr) {
15894 PushOnScopeChains(OmpPrivParm, S);
15895 PushOnScopeChains(OmpOrigParm, S);
15896 } else {
15897 DRD->addDecl(OmpPrivParm);
15898 DRD->addDecl(OmpOrigParm);
15899 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015900 Expr *OrigE =
15901 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
15902 Expr *PrivE =
15903 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
15904 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000015905 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015906}
15907
Alexey Bataev070f43a2017-09-06 14:49:58 +000015908void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
15909 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015910 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15911 DiscardCleanupsInEvaluationContext();
15912 PopExpressionEvaluationContext();
15913
15914 PopDeclContext();
15915 PopFunctionScopeInfo();
15916
Alexey Bataev070f43a2017-09-06 14:49:58 +000015917 if (Initializer != nullptr) {
15918 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
15919 } else if (OmpPrivParm->hasInit()) {
15920 DRD->setInitializer(OmpPrivParm->getInit(),
15921 OmpPrivParm->isDirectInit()
15922 ? OMPDeclareReductionDecl::DirectInit
15923 : OMPDeclareReductionDecl::CopyInit);
15924 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015925 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000015926 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015927}
15928
15929Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
15930 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015931 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015932 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015933 if (S)
15934 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
15935 /*AddToContext=*/false);
15936 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015937 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000015938 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015939 }
15940 return DeclReductions;
15941}
15942
Michael Kruse251e1482019-02-01 20:25:04 +000015943TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
15944 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15945 QualType T = TInfo->getType();
15946 if (D.isInvalidType())
15947 return true;
15948
15949 if (getLangOpts().CPlusPlus) {
15950 // Check that there are no default arguments (C++ only).
15951 CheckExtraCXXDefaultArguments(D);
15952 }
15953
15954 return CreateParsedType(T, TInfo);
15955}
15956
15957QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
15958 TypeResult ParsedType) {
15959 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
15960
15961 QualType MapperType = GetTypeFromParser(ParsedType.get());
15962 assert(!MapperType.isNull() && "Expect valid mapper type");
15963
15964 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15965 // The type must be of struct, union or class type in C and C++
15966 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
15967 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
15968 return QualType();
15969 }
15970 return MapperType;
15971}
15972
15973OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
15974 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
15975 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
15976 Decl *PrevDeclInScope) {
15977 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
15978 forRedeclarationInCurContext());
15979 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15980 // A mapper-identifier may not be redeclared in the current scope for the
15981 // same type or for a type that is compatible according to the base language
15982 // rules.
15983 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15984 OMPDeclareMapperDecl *PrevDMD = nullptr;
15985 bool InCompoundScope = true;
15986 if (S != nullptr) {
15987 // Find previous declaration with the same name not referenced in other
15988 // declarations.
15989 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15990 InCompoundScope =
15991 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15992 LookupName(Lookup, S);
15993 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15994 /*AllowInlineNamespace=*/false);
15995 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
15996 LookupResult::Filter Filter = Lookup.makeFilter();
15997 while (Filter.hasNext()) {
15998 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
15999 if (InCompoundScope) {
16000 auto I = UsedAsPrevious.find(PrevDecl);
16001 if (I == UsedAsPrevious.end())
16002 UsedAsPrevious[PrevDecl] = false;
16003 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16004 UsedAsPrevious[D] = true;
16005 }
16006 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16007 PrevDecl->getLocation();
16008 }
16009 Filter.done();
16010 if (InCompoundScope) {
16011 for (const auto &PrevData : UsedAsPrevious) {
16012 if (!PrevData.second) {
16013 PrevDMD = PrevData.first;
16014 break;
16015 }
16016 }
16017 }
16018 } else if (PrevDeclInScope) {
16019 auto *PrevDMDInScope = PrevDMD =
16020 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16021 do {
16022 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16023 PrevDMDInScope->getLocation();
16024 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16025 } while (PrevDMDInScope != nullptr);
16026 }
16027 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16028 bool Invalid = false;
16029 if (I != PreviousRedeclTypes.end()) {
16030 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16031 << MapperType << Name;
16032 Diag(I->second, diag::note_previous_definition);
16033 Invalid = true;
16034 }
16035 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16036 MapperType, VN, PrevDMD);
16037 DC->addDecl(DMD);
16038 DMD->setAccess(AS);
16039 if (Invalid)
16040 DMD->setInvalidDecl();
16041
16042 // Enter new function scope.
16043 PushFunctionScope();
16044 setFunctionHasBranchProtectedScope();
16045
16046 CurContext = DMD;
16047
16048 return DMD;
16049}
16050
16051void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16052 Scope *S,
16053 QualType MapperType,
16054 SourceLocation StartLoc,
16055 DeclarationName VN) {
16056 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16057 if (S)
16058 PushOnScopeChains(VD, S);
16059 else
16060 DMD->addDecl(VD);
16061 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16062 DMD->setMapperVarRef(MapperVarRefExpr);
16063}
16064
16065Sema::DeclGroupPtrTy
16066Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16067 ArrayRef<OMPClause *> ClauseList) {
16068 PopDeclContext();
16069 PopFunctionScopeInfo();
16070
16071 if (D) {
16072 if (S)
16073 PushOnScopeChains(D, S, /*AddToContext=*/false);
16074 D->CreateClauses(Context, ClauseList);
16075 }
16076
16077 return DeclGroupPtrTy::make(DeclGroupRef(D));
16078}
16079
David Majnemer9d168222016-08-05 17:44:54 +000016080OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016081 SourceLocation StartLoc,
16082 SourceLocation LParenLoc,
16083 SourceLocation EndLoc) {
16084 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016085 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016086
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016087 // OpenMP [teams Constrcut, Restrictions]
16088 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016089 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016090 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016091 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016092
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016093 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016094 OpenMPDirectiveKind CaptureRegion =
16095 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
16096 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016097 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016098 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016099 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16100 HelperValStmt = buildPreInits(Context, Captures);
16101 }
16102
16103 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16104 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016105}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016106
16107OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16108 SourceLocation StartLoc,
16109 SourceLocation LParenLoc,
16110 SourceLocation EndLoc) {
16111 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016112 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016113
16114 // OpenMP [teams Constrcut, Restrictions]
16115 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016116 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016117 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016118 return nullptr;
16119
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016120 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016121 OpenMPDirectiveKind CaptureRegion =
16122 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
16123 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016124 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016125 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016126 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16127 HelperValStmt = buildPreInits(Context, Captures);
16128 }
16129
16130 return new (Context) OMPThreadLimitClause(
16131 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016132}
Alexey Bataeva0569352015-12-01 10:17:31 +000016133
16134OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16135 SourceLocation StartLoc,
16136 SourceLocation LParenLoc,
16137 SourceLocation EndLoc) {
16138 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016139 Stmt *HelperValStmt = nullptr;
16140 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016141
16142 // OpenMP [2.9.1, task Constrcut]
16143 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016144 if (!isNonNegativeIntegerValue(
16145 ValExpr, *this, OMPC_priority,
16146 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16147 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016148 return nullptr;
16149
Alexey Bataev31ba4762019-10-16 18:09:37 +000016150 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16151 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016152}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016153
16154OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16155 SourceLocation StartLoc,
16156 SourceLocation LParenLoc,
16157 SourceLocation EndLoc) {
16158 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016159 Stmt *HelperValStmt = nullptr;
16160 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016161
16162 // OpenMP [2.9.2, taskloop Constrcut]
16163 // The parameter of the grainsize clause must be a positive integer
16164 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016165 if (!isNonNegativeIntegerValue(
16166 ValExpr, *this, OMPC_grainsize,
16167 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16168 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016169 return nullptr;
16170
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016171 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16172 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016173}
Alexey Bataev382967a2015-12-08 12:06:20 +000016174
16175OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16176 SourceLocation StartLoc,
16177 SourceLocation LParenLoc,
16178 SourceLocation EndLoc) {
16179 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016180 Stmt *HelperValStmt = nullptr;
16181 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016182
16183 // OpenMP [2.9.2, taskloop Constrcut]
16184 // The parameter of the num_tasks clause must be a positive integer
16185 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016186 if (!isNonNegativeIntegerValue(
16187 ValExpr, *this, OMPC_num_tasks,
16188 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16189 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016190 return nullptr;
16191
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016192 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16193 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016194}
16195
Alexey Bataev28c75412015-12-15 08:19:24 +000016196OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16197 SourceLocation LParenLoc,
16198 SourceLocation EndLoc) {
16199 // OpenMP [2.13.2, critical construct, Description]
16200 // ... where hint-expression is an integer constant expression that evaluates
16201 // to a valid lock hint.
16202 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16203 if (HintExpr.isInvalid())
16204 return nullptr;
16205 return new (Context)
16206 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16207}
16208
Carlo Bertollib4adf552016-01-15 18:50:31 +000016209OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16210 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16211 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16212 SourceLocation EndLoc) {
16213 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16214 std::string Values;
16215 Values += "'";
16216 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16217 Values += "'";
16218 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16219 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16220 return nullptr;
16221 }
16222 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016223 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016224 if (ChunkSize) {
16225 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16226 !ChunkSize->isInstantiationDependent() &&
16227 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016228 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016229 ExprResult Val =
16230 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16231 if (Val.isInvalid())
16232 return nullptr;
16233
16234 ValExpr = Val.get();
16235
16236 // OpenMP [2.7.1, Restrictions]
16237 // chunk_size must be a loop invariant integer expression with a positive
16238 // value.
16239 llvm::APSInt Result;
16240 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16241 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16242 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16243 << "dist_schedule" << ChunkSize->getSourceRange();
16244 return nullptr;
16245 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016246 } else if (getOpenMPCaptureRegionForClause(
16247 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
16248 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016249 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016250 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016251 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016252 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16253 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016254 }
16255 }
16256 }
16257
16258 return new (Context)
16259 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016260 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016261}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016262
16263OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16264 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16265 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16266 SourceLocation KindLoc, SourceLocation EndLoc) {
16267 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000016268 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016269 std::string Value;
16270 SourceLocation Loc;
16271 Value += "'";
16272 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16273 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000016274 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016275 Loc = MLoc;
16276 } else {
16277 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000016278 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016279 Loc = KindLoc;
16280 }
16281 Value += "'";
16282 Diag(Loc, diag::err_omp_unexpected_clause_value)
16283 << Value << getOpenMPClauseName(OMPC_defaultmap);
16284 return nullptr;
16285 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000016286 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016287
16288 return new (Context)
16289 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16290}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016291
16292bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16293 DeclContext *CurLexicalContext = getCurLexicalContext();
16294 if (!CurLexicalContext->isFileContext() &&
16295 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016296 !CurLexicalContext->isExternCXXContext() &&
16297 !isa<CXXRecordDecl>(CurLexicalContext) &&
16298 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16299 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16300 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016301 Diag(Loc, diag::err_omp_region_not_file_context);
16302 return false;
16303 }
Kelvin Libc38e632018-09-10 02:07:09 +000016304 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016305 return true;
16306}
16307
16308void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016309 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016310 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016311 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016312}
16313
Alexey Bataev729e2422019-08-23 16:11:14 +000016314NamedDecl *
16315Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16316 const DeclarationNameInfo &Id,
16317 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016318 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16319 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16320
16321 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016322 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016323 Lookup.suppressDiagnostics();
16324
16325 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016326 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016327 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016328 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016329 CTK_ErrorRecovery)) {
16330 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16331 << Id.getName());
16332 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016333 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016334 }
16335
16336 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016337 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016338 }
16339
16340 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016341 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16342 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016343 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016344 return nullptr;
16345 }
16346 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16347 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16348 return ND;
16349}
16350
16351void Sema::ActOnOpenMPDeclareTargetName(
16352 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16353 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16354 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16355 isa<FunctionTemplateDecl>(ND)) &&
16356 "Expected variable, function or function template.");
16357
16358 // Diagnose marking after use as it may lead to incorrect diagnosis and
16359 // codegen.
16360 if (LangOpts.OpenMP >= 50 &&
16361 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16362 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16363
16364 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16365 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16366 if (DevTy.hasValue() && *DevTy != DT) {
16367 Diag(Loc, diag::err_omp_device_type_mismatch)
16368 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16369 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16370 return;
16371 }
16372 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16373 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16374 if (!Res) {
16375 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16376 SourceRange(Loc, Loc));
16377 ND->addAttr(A);
16378 if (ASTMutationListener *ML = Context.getASTMutationListener())
16379 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16380 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16381 } else if (*Res != MT) {
16382 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016383 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016384}
16385
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016386static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16387 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016388 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016389 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016390 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016391 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16392 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16393 if (SemaRef.LangOpts.OpenMP >= 50 &&
16394 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16395 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16396 VD->hasGlobalStorage()) {
16397 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16398 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16399 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16400 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16401 // If a lambda declaration and definition appears between a
16402 // declare target directive and the matching end declare target
16403 // directive, all variables that are captured by the lambda
16404 // expression must also appear in a to clause.
16405 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016406 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016407 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16408 << VD << 0 << SR;
16409 return;
16410 }
16411 }
16412 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016413 return;
16414 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16415 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016416}
16417
16418static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16419 Sema &SemaRef, DSAStackTy *Stack,
16420 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016421 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016422 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16423 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016424}
16425
Kelvin Li1ce87c72017-12-12 20:08:12 +000016426void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16427 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016428 if (!D || D->isInvalidDecl())
16429 return;
16430 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016431 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016432 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016433 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016434 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16435 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016436 return;
16437 // 2.10.6: threadprivate variable cannot appear in a declare target
16438 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016439 if (DSAStack->isThreadPrivate(VD)) {
16440 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016441 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016442 return;
16443 }
16444 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016445 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16446 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016447 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016448 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16449 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016450 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016451 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16452 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16453 return;
16454 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016455 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016456 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16457 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16458 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16459 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016460 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016461 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16462 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16463 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016464 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016465 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16466 // Problem if any with var declared with incomplete type will be reported
16467 // as normal, so no need to check it here.
16468 if ((E || !VD->getType()->isIncompleteType()) &&
16469 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16470 return;
16471 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16472 // Checking declaration inside declare target region.
16473 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16474 isa<FunctionTemplateDecl>(D)) {
16475 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016476 Context, OMPDeclareTargetDeclAttr::MT_To,
16477 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016478 D->addAttr(A);
16479 if (ASTMutationListener *ML = Context.getASTMutationListener())
16480 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16481 }
16482 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016483 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016484 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016485 if (!E)
16486 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016487 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16488}
Samuel Antao661c0902016-05-26 17:39:58 +000016489
16490OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016491 CXXScopeSpec &MapperIdScopeSpec,
16492 DeclarationNameInfo &MapperId,
16493 const OMPVarListLocTy &Locs,
16494 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016495 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016496 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16497 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016498 if (MVLI.ProcessedVarList.empty())
16499 return nullptr;
16500
Michael Kruse01f670d2019-02-22 22:29:42 +000016501 return OMPToClause::Create(
16502 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16503 MVLI.VarComponents, MVLI.UDMapperList,
16504 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016505}
Samuel Antaoec172c62016-05-26 17:49:04 +000016506
16507OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016508 CXXScopeSpec &MapperIdScopeSpec,
16509 DeclarationNameInfo &MapperId,
16510 const OMPVarListLocTy &Locs,
16511 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016512 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016513 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16514 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016515 if (MVLI.ProcessedVarList.empty())
16516 return nullptr;
16517
Michael Kruse0336c752019-02-25 20:34:15 +000016518 return OMPFromClause::Create(
16519 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16520 MVLI.VarComponents, MVLI.UDMapperList,
16521 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016522}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016523
16524OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016525 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016526 MappableVarListInfo MVLI(VarList);
16527 SmallVector<Expr *, 8> PrivateCopies;
16528 SmallVector<Expr *, 8> Inits;
16529
Alexey Bataeve3727102018-04-18 15:57:46 +000016530 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016531 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16532 SourceLocation ELoc;
16533 SourceRange ERange;
16534 Expr *SimpleRefExpr = RefExpr;
16535 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16536 if (Res.second) {
16537 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016538 MVLI.ProcessedVarList.push_back(RefExpr);
16539 PrivateCopies.push_back(nullptr);
16540 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016541 }
16542 ValueDecl *D = Res.first;
16543 if (!D)
16544 continue;
16545
16546 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016547 Type = Type.getNonReferenceType().getUnqualifiedType();
16548
16549 auto *VD = dyn_cast<VarDecl>(D);
16550
16551 // Item should be a pointer or reference to pointer.
16552 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016553 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16554 << 0 << RefExpr->getSourceRange();
16555 continue;
16556 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016557
16558 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016559 auto VDPrivate =
16560 buildVarDecl(*this, ELoc, Type, D->getName(),
16561 D->hasAttrs() ? &D->getAttrs() : nullptr,
16562 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016563 if (VDPrivate->isInvalidDecl())
16564 continue;
16565
16566 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016567 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016568 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16569
16570 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016571 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016572 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016573 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16574 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016575 AddInitializerToDecl(VDPrivate,
16576 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016577 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016578
16579 // If required, build a capture to implement the privatization initialized
16580 // with the current list item value.
16581 DeclRefExpr *Ref = nullptr;
16582 if (!VD)
16583 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16584 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16585 PrivateCopies.push_back(VDPrivateRefExpr);
16586 Inits.push_back(VDInitRefExpr);
16587
16588 // We need to add a data sharing attribute for this variable to make sure it
16589 // is correctly captured. A variable that shows up in a use_device_ptr has
16590 // similar properties of a first private variable.
16591 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16592
16593 // Create a mappable component for the list item. List items in this clause
16594 // only need a component.
16595 MVLI.VarBaseDeclarations.push_back(D);
16596 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16597 MVLI.VarComponents.back().push_back(
16598 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016599 }
16600
Samuel Antaocc10b852016-07-28 14:23:26 +000016601 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016602 return nullptr;
16603
Samuel Antaocc10b852016-07-28 14:23:26 +000016604 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016605 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16606 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016607}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016608
16609OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016610 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016611 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016612 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016613 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016614 SourceLocation ELoc;
16615 SourceRange ERange;
16616 Expr *SimpleRefExpr = RefExpr;
16617 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16618 if (Res.second) {
16619 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016620 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016621 }
16622 ValueDecl *D = Res.first;
16623 if (!D)
16624 continue;
16625
16626 QualType Type = D->getType();
16627 // item should be a pointer or array or reference to pointer or array
16628 if (!Type.getNonReferenceType()->isPointerType() &&
16629 !Type.getNonReferenceType()->isArrayType()) {
16630 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16631 << 0 << RefExpr->getSourceRange();
16632 continue;
16633 }
Samuel Antao6890b092016-07-28 14:25:09 +000016634
16635 // Check if the declaration in the clause does not show up in any data
16636 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016637 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016638 if (isOpenMPPrivate(DVar.CKind)) {
16639 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16640 << getOpenMPClauseName(DVar.CKind)
16641 << getOpenMPClauseName(OMPC_is_device_ptr)
16642 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016643 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016644 continue;
16645 }
16646
Alexey Bataeve3727102018-04-18 15:57:46 +000016647 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016648 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016649 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016650 [&ConflictExpr](
16651 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16652 OpenMPClauseKind) -> bool {
16653 ConflictExpr = R.front().getAssociatedExpression();
16654 return true;
16655 })) {
16656 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16657 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16658 << ConflictExpr->getSourceRange();
16659 continue;
16660 }
16661
16662 // Store the components in the stack so that they can be used to check
16663 // against other clauses later on.
16664 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16665 DSAStack->addMappableExpressionComponents(
16666 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16667
16668 // Record the expression we've just processed.
16669 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16670
16671 // Create a mappable component for the list item. List items in this clause
16672 // only need a component. We use a null declaration to signal fields in
16673 // 'this'.
16674 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16675 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16676 "Unexpected device pointer expression!");
16677 MVLI.VarBaseDeclarations.push_back(
16678 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16679 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16680 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016681 }
16682
Samuel Antao6890b092016-07-28 14:25:09 +000016683 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016684 return nullptr;
16685
Michael Kruse4304e9d2019-02-19 16:38:20 +000016686 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16687 MVLI.VarBaseDeclarations,
16688 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016689}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016690
16691OMPClause *Sema::ActOnOpenMPAllocateClause(
16692 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16693 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16694 if (Allocator) {
16695 // OpenMP [2.11.4 allocate Clause, Description]
16696 // allocator is an expression of omp_allocator_handle_t type.
16697 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16698 return nullptr;
16699
16700 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16701 if (AllocatorRes.isInvalid())
16702 return nullptr;
16703 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16704 DSAStack->getOMPAllocatorHandleT(),
16705 Sema::AA_Initializing,
16706 /*AllowExplicit=*/true);
16707 if (AllocatorRes.isInvalid())
16708 return nullptr;
16709 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016710 } else {
16711 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16712 // allocate clauses that appear on a target construct or on constructs in a
16713 // target region must specify an allocator expression unless a requires
16714 // directive with the dynamic_allocators clause is present in the same
16715 // compilation unit.
16716 if (LangOpts.OpenMPIsDevice &&
16717 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16718 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016719 }
16720 // Analyze and build list of variables.
16721 SmallVector<Expr *, 8> Vars;
16722 for (Expr *RefExpr : VarList) {
16723 assert(RefExpr && "NULL expr in OpenMP private clause.");
16724 SourceLocation ELoc;
16725 SourceRange ERange;
16726 Expr *SimpleRefExpr = RefExpr;
16727 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16728 if (Res.second) {
16729 // It will be analyzed later.
16730 Vars.push_back(RefExpr);
16731 }
16732 ValueDecl *D = Res.first;
16733 if (!D)
16734 continue;
16735
16736 auto *VD = dyn_cast<VarDecl>(D);
16737 DeclRefExpr *Ref = nullptr;
16738 if (!VD && !CurContext->isDependentContext())
16739 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16740 Vars.push_back((VD || CurContext->isDependentContext())
16741 ? RefExpr->IgnoreParens()
16742 : Ref);
16743 }
16744
16745 if (Vars.empty())
16746 return nullptr;
16747
16748 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16749 ColonLoc, EndLoc, Vars);
16750}